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 prompt set
nirholas29c764992bf5
diff --git a/docs/monetization-prompts/01-display-priced-skills.md b/docs/monetization-prompts/01-display-priced-skills.mddeleted file mode 100644index 83cdb6daf..000000000--- a/docs/monetization-prompts/01-display-priced-skills.md+++ /dev/null@@ -1,68 +0,0 @@-# Prompt 1: Display Priced Skills in Marketplace--**Status:** - [ ] Not Started--## 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-prompts/02-add-purchase-button.md b/docs/monetization-prompts/02-add-purchase-button.mddeleted file mode 100644index f8532c255..000000000--- a/docs/monetization-prompts/02-add-purchase-button.md+++ /dev/null@@ -1,101 +0,0 @@-# Prompt 2: Add Purchase Button for Priced Skills--**Status:** - [ ] Not Started--## Objective-On the agent detail page, display a "Purchase" button next to paid skills and an "Owned" or "Equipped" label for skills the user has already purchased.--## Explanation-Building on the previous step, now that prices are displayed, the next logical step is to provide a call to action for users to buy the skill. This prompt focuses on updating the UI to include this button and reflect the user's ownership status of a skill.--## Instructions-1. **Fetch User's Purchased Skills:**- * You'll need an API endpoint to get the skills a user has purchased for a specific agent. Let's assume a new endpoint `/api/users/me/agent-skills/:agentId`.- * This endpoint should return a list of skill names the user owns for that agent.--2. **Update Frontend Data Fetching:**- * In `src/marketplace.js`, within `renderDetail`, after fetching the agent details, make another API call to fetch the user's purchased skills for the current agent.--3. **Modify UI Rendering Logic:**- * In the `renderDetail` function, when looping through the agent's skills, you now have access to `skillPrices` and the `purchasedSkills`.- * The logic for rendering each skill entry should be updated:- * If the skill is free (no price in `skillPrices`), show the "Free" badge.- * If the skill is paid and the user has purchased it (skill name is in `purchasedSkills`), show an "Owned" badge/label.- * If the skill is paid and the user has *not* purchased it, show the price and a "Purchase" button.--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside renderDetail function, after fetching agent and purchased skills--const skillPrices = a.skill_prices || {};-const purchasedSkills = userSkills || []; // from new API call--$('d-skills').innerHTML = skillsArr.length- ? skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];- const isOwned = purchasedSkills.includes(name);-- let badgeOrButton = '';- if (isOwned) {- badgeOrButton = `<span class="skill-status-badge skill-owned">Owned</span>`;- } else if (price) {- const priceInUSDC = (price.amount / 1e6).toFixed(2);- badgeOrButton = `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}">Purchase for ${priceInUSDC} USDC</button>`;- } else {- badgeOrButton = `<span class="price-badge price-free">Free</span>`;- }-- return `<div class="skill-entry">- <span class="skill-name">${escapeHtml(name)}</span>- ${badgeOrButton}- </div>`;- }).join('')- : '<div>This Agent has no skills defined.</div>';--```--## CSS Example--Add these styles to `/marketplace.css` for the new elements.--```css-.skill-entry {- display: flex;- justify-content: space-between;- align-items: center;- padding: 8px 0;- border-bottom: 1px solid var(--border);-}--.purchase-btn {- background-color: var(--accent);- color: white;- border: none;- padding: 6px 12px;- font-size: 12px;- font-weight: 600;- border-radius: 6px;- cursor: pointer;- transition: background-color 0.2s;-}--.purchase-btn:hover {- background-color: #5a4ccc; /* A slightly darker shade of accent */-}--.skill-status-badge {- display: inline-block;- padding: 2px 6px;- font-size: 10px;- font-weight: 600;- border-radius: 4px;- vertical-align: middle;-}--.skill-owned {- color: #a7f3d0;- background-color: rgba(52, 211, 153, 0.1);-}-```diff --git a/docs/monetization-prompts/02-database-schema-skill-prices.md b/docs/monetization-prompts/02-database-schema-skill-prices.mddeleted file mode 100644index e4e7ca435..000000000--- a/docs/monetization-prompts/02-database-schema-skill-prices.md+++ /dev/null@@ -1,49 +0,0 @@-# Prompt 02: Database Schema for Skill Prices--## Objective-Create the necessary database table to store pricing information for agent skills.--## Explanation-To make skills sellable, we need a way to persist their price, currency, and associated creator. This prompt establishes the foundational database schema for skill monetization. The `agent_skill_prices` table will be the single source of truth for skill pricing.--## Instructions-1. **Locate the Schema File:**- * Find the main database schema definition file at `api/_lib/schema.sql`.--2. **Define the `agent_skill_prices` Table:**- * Add a new `CREATE TABLE` statement to `schema.sql`.- * The table should include the following columns:- * `id`: A UUID primary key.- * `agent_id`: A UUID foreign key referencing `agent_identities(id)`.- * `skill_id`: A text field representing the unique identifier of the skill (e.g., its URI or name).- * `creator_id`: A UUID foreign key referencing `users(id)`, to know who gets paid.- * `amount`: A `BIGINT` to store the price in the smallest unit of the currency (e.g., lamports for SOL, or 10^-6 for USDC).- * `currency_mint`: A text field for the mint address of the currency (e.g., the USDC mint address on Solana).- * `created_at`, `updated_at`, `deleted_at`: Standard timestamp columns.--3. **Add an Index:**- * Create a unique index on `(agent_id, skill_id)` to ensure a skill on a specific agent can only have one price.--## SQL Example--```sql--- In api/_lib/schema.sql--CREATE TABLE agent_skill_prices (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,- skill_id TEXT NOT NULL,- creator_id UUID NOT NULL REFERENCES users(id),- amount BIGINT NOT NULL CHECK (amount > 0),- currency_mint TEXT NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- deleted_at TIMESTAMPTZ-);--CREATE UNIQUE INDEX idx_agent_skill_prices_one_price_per_skill-ON agent_skill_prices (agent_id, skill_id)-WHERE deleted_at IS NULL;--CREATE INDEX idx_agent_skill_prices_creator_id ON agent_skill_prices(creator_id);-```diff --git a/docs/monetization-prompts/02-purchase-skill-button.md b/docs/monetization-prompts/02-purchase-skill-button.mddeleted file mode 100644index 02314968d..000000000--- a/docs/monetization-prompts/02-purchase-skill-button.md+++ /dev/null@@ -1,71 +0,0 @@-----status: not-started------# Prompt 02: Add Purchase Button for Priced Skills--## Objective-Add a "Purchase" button next to paid skills on the agent detail page, creating a clear call-to-action for users.--## Explanation-With prices now visible, the next step is to provide a way for users to initiate a purchase. This prompt focuses on adding the button to the UI. The button's functionality will be implemented in subsequent steps.--## Instructions-- [ ] **Update the Frontend UI (`src/marketplace.js`):**- - [ ] Modify the `renderDetail` function.- - [ ] In the skill rendering loop, if a skill is paid, render a "Purchase" button next to the price badge.- - [ ] For now, we will assume the user does not own any skills. In a later prompt, we will fetch user ownership data and update the button state (e.g., to a disabled "Unlocked" button).- - [ ] Add a `data-skill-name` attribute to the button to easily identify which skill is being purchased when the button is clicked.--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside renderDetail's map function for skills-const name = typeof s === 'string' ? s : (s.name || '');-const price = skillPrices[name];--if (price) {- // In a future step, isOwned will be dynamically determined.- const isOwned = false;- const priceText = `${(price.amount / 1e6).toFixed(2)} USDC`;- const badge = `<span class="price-badge price-paid">${priceText}</span>`;- const button = isOwned- ? `<button class="purchase-btn" disabled>Unlocked</button>`- : `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}">Purchase</button>`;- return `<span class="skill-entry">${escapeHtml(name)}${badge}${button}</span>`;-} else {- const badge = `<span class="price-badge price-free">Free</span>`;- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;-}-```--## CSS Example--Add these styles to a relevant CSS file.--```css-.purchase-btn {- margin-left: 8px;- padding: 4px 10px;- font-size: 12px;- font-weight: 600;- border-radius: 6px;- border: 1px solid #fde047;- background-color: transparent;- color: #fde047;- cursor: pointer;- transition: background-color 0.2s, color 0.2s;-}--.purchase-btn:hover {- background-color: #fde047;- color: #111;-}--.purchase-btn:disabled {- border-color: #444;- color: #444;- cursor: not-allowed;- background-color: transparent;-}-```diff --git a/docs/monetization-prompts/03-create-purchase-modal.md b/docs/monetization-prompts/03-create-purchase-modal.mddeleted file mode 100644index 20e0d8078..000000000--- a/docs/monetization-prompts/03-create-purchase-modal.md+++ /dev/null@@ -1,128 +0,0 @@-# Prompt 3: Create Purchase Confirmation Modal--**Status:** - [ ] Not Started--## Objective-Implement a modal dialog that appears when a user clicks the "Purchase" button for a skill, asking for confirmation before proceeding with the transaction.--## Explanation-A confirmation step is crucial for any purchasing flow to prevent accidental purchases. This modal will summarize the transaction (skill name, price) and require an explicit user action to continue. It will serve as the container for wallet interactions in subsequent steps.--## Instructions-1. **Create Modal HTML Structure:**- * Add the HTML for a modal to `marketplace.html`. It should be hidden by default.- * The modal should contain elements for the skill name, price, a "Confirm Purchase" button, and a close button.--2. **Add JavaScript Logic to Control the Modal:**- * In `src/marketplace.js`, add event listeners for the "Purchase" buttons. Since these buttons are dynamically generated, use event delegation on a parent element (e.g., `$('d-skills')`).- * When a purchase button is clicked, populate the modal with the correct skill name and price.- * Show the modal.- * Implement the logic for the close button and for closing the modal by clicking the backdrop.--3. **Style the Modal:**- * Add CSS to `/marketplace.css` to style the modal, its backdrop, and its contents for a clean, user-friendly appearance.--## Code Example (HTML in `marketplace.html`)--```html-<!-- Add this somewhere in the body of marketplace.html -->-<div id="purchase-modal-backdrop" class="modal-backdrop" style="display: none;">- <div id="purchase-modal" class="modal">- <div class="modal-header">- <h2>Confirm Purchase</h2>- <button id="modal-close-btn" class="modal-close-btn">×</button>- </div>- <div class="modal-body">- <p>You are about to purchase the skill:</p>- <h3 id="modal-skill-name"></h3>- <p>Price:</p>- <h3 id="modal-skill-price"></h3>- </div>- <div class="modal-footer">- <button id="modal-confirm-purchase-btn" class="purchase-btn">Confirm Purchase</button>- </div>- </div>-</div>-```--## Code Example (JavaScript in `src/marketplace.js`)--```javascript-// At the top of the script-const purchaseModal = $('purchase-modal-backdrop');-const modalSkillName = $('modal-skill-name');-const modalSkillPrice = $('modal-skill-price');--// Event listener using delegation-$('d-skills').addEventListener('click', (e) => {- if (e.target.classList.contains('purchase-btn')) {- const skillName = e.target.dataset.skillName;- const agent = window.currentAgent; // Assuming current agent data is available- const priceInfo = agent.skill_prices[skillName];-- if (priceInfo) {- modalSkillName.textContent = skillName;- modalSkillPrice.textContent = `${(priceInfo.amount / 1e6).toFixed(2)} USDC`;- purchaseModal.style.display = 'flex';- }- }-});--// Close modal logic-$('modal-close-btn').addEventListener('click', () => {- purchaseModal.style.display = 'none';-});-purchaseModal.addEventListener('click', (e) => {- if (e.target === purchaseModal) {- purchaseModal.style.display = 'none';- }-});-```--## CSS Example (`/marketplace.css`)--```css-.modal-backdrop {- position: fixed;- top: 0;- left: 0;- width: 100%;- height: 100%;- background-color: rgba(0, 0, 0, 0.6);- display: flex;- justify-content: center;- align-items: center;- z-index: 1000;-}--.modal {- background-color: var(--panel);- padding: 24px;- border-radius: 12px;- border: 1px solid var(--border);- width: 90%;- max-width: 400px;-}--.modal-header {- display: flex;- justify-content: space-between;- align-items: center;- border-bottom: 1px solid var(--border);- padding-bottom: 16px;- margin-bottom: 16px;-}--.modal-header h2 {- margin: 0;- font-size: 18px;-}--.modal-close-btn {- background: none;- border: none;- font-size: 24px;- color: var(--muted);- cursor: pointer;-}-```diff --git a/docs/monetization-prompts/03-creator-api-set-skill-prices.md b/docs/monetization-prompts/03-creator-api-set-skill-prices.mddeleted file mode 100644index 2f8017bfb..000000000--- a/docs/monetization-prompts/03-creator-api-set-skill-prices.md+++ /dev/null@@ -1,68 +0,0 @@-# Prompt 03: Creator API to Set Skill Prices--## Objective-Create a secure API endpoint for agent creators to set, update, and remove prices for their skills.--## Explanation-With the database schema in place, creators need a way to manage their skill prices. This requires a new API endpoint that authenticates the user, verifies they own the agent, and allows them to perform CRUD operations on the `agent_skill_prices` table for that agent.--## Instructions-1. **Create a New API Endpoint File:**- * Create a new file, for example, `api/agents/[id]/skill-prices.js`. Vercel's file-based routing will handle the `[id]` parameter.--2. **Implement the Endpoint Logic:**- * The endpoint should handle `POST`, `PUT`, and `DELETE` requests.- * **Authentication:** Use the existing `getSessionUser` or `authenticateBearer` helpers to get the current user.- * **Authorization:** Verify that the authenticated user is the owner of the agent specified in the URL (`agent_id`). Query `agent_identities` to check ownership.- * **`POST` (Create):**- * Accept a payload with `skill_id`, `amount`, and `currency_mint`.- * Insert a new record into `agent_skill_prices`.- * **`PUT` (Update):**- * Accept `skill_id` and the new `amount`.- * Update the existing record in `agent_skill_prices`.- * **`DELETE` (Remove):**- * Accept `skill_id`.- * Soft-delete the record by setting `deleted_at`.- * **Validation:** Use `zod` to validate the incoming request bodies.--## Code Example (`api/agents/[id]/skill-prices.js`)--```javascript-import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { error, json, wrap } from '../_lib/http.js';-import { z } from 'zod';--const priceSchema = z.object({- skill_id: z.string().min(1),- amount: z.number().int().positive(),- currency_mint: z.string().min(32), // Solana mint address length-});--export default wrap(async (req, res) => {- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized');-- const agentId = req.query.id;- const [agent] = await sql`- SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL- `;-- if (!agent || agent.user_id !== user.id) {- return error(res, 403, 'forbidden', 'You do not own this agent.');- }-- if (req.method === 'POST') {- const body = priceSchema.parse(await req.json());- await sql`- INSERT INTO agent_skill_prices (agent_id, skill_id, creator_id, amount, currency_mint)- VALUES (${agentId}, ${body.skill_id}, ${user.id}, ${body.amount}, ${body.currency_mint})- `;- return json(res, { success: true });- }-- // ... implement PUT and DELETE handlers similarly ...-- return error(res, 405, 'method_not_allowed');-});-```diff --git a/docs/monetization-prompts/03-skill-purchase-modal.md b/docs/monetization-prompts/03-skill-purchase-modal.mddeleted file mode 100644index 87f42d96f..000000000--- a/docs/monetization-prompts/03-skill-purchase-modal.md+++ /dev/null@@ -1,64 +0,0 @@-----status: not-started------# Prompt 03: Create Skill Purchase Modal--## Objective-Create a modal that appears when a user clicks the "Purchase" button, confirming the skill details and price before the transaction.--## Explanation-A confirmation modal prevents accidental purchases and provides a clear, focused step in the user journey. This modal will be the central point for initiating the wallet transaction.--## Instructions-- [ ] **Create the Modal HTML:**- - [ ] Add the HTML structure for a hidden modal to `marketplace.html`. It should include placeholders for the skill name, price, and agent name, along with "Confirm Purchase" and "Cancel" buttons.--- [ ] **Add JavaScript Logic (`src/marketplace.js`):**- - [ ] Create a new function, `openPurchaseModal(skillName, price, agentName)`. This function will populate the modal with the correct data and make it visible.- - [ ] Attach an event listener to the `d-skills` container that listens for clicks on `.purchase-btn`.- - [ ] When a purchase button is clicked, get the skill name from the `data-skill-name` attribute, find its price from the agent data, and call `openPurchaseModal`.- - [ ] Add event listeners for the "Confirm" and "Cancel" buttons within the modal. For now, they can just log to the console.--## HTML Example (in `marketplace.html`)--```html-<div id="purchase-modal" class="modal-hidden">- <div class="modal-content">- <h2>Confirm Purchase</h2>- <p>Unlock the skill <strong id="modal-skill-name"></strong> for agent <strong id="modal-agent-name"></strong>?</p>- <div class="modal-price">Price: <span id="modal-skill-price"></span></div>- <div class="modal-actions">- <button id="modal-cancel-btn">Cancel</button>- <button id="modal-confirm-btn">Confirm Purchase</button>- </div>- </div>-</div>-```--## JavaScript Example (`src/marketplace.js`)--```javascript-// At the end of init function-const skillsContainer = document.getElementById('d-skills');-skillsContainer.addEventListener('click', (event) => {- if (event.target.classList.contains('purchase-btn')) {- const skillName = event.target.dataset.skillName;- // Assume 'currentAgent' is available in a higher scope- const price = currentAgent.skill_prices[skillName];- if (price) {- openPurchaseModal(skillName, price, currentAgent.name);- }- }-});--function openPurchaseModal(skillName, price, agentName) {- document.getElementById('modal-skill-name').textContent = skillName;- document.getElementById('modal-agent-name').textContent = agentName;- const priceText = `${(price.amount / 1e6).toFixed(2)} USDC`;- document.getElementById('modal-skill-price').textContent = priceText;- document.getElementById('purchase-modal').classList.remove('modal-hidden');-}--// Add listeners for modal buttons to close it, etc.-```diff --git a/docs/monetization-prompts/04-connect-wallet-integration.md b/docs/monetization-prompts/04-connect-wallet-integration.mddeleted file mode 100644index a1301ffb9..000000000--- a/docs/monetization-prompts/04-connect-wallet-integration.md+++ /dev/null@@ -1,70 +0,0 @@-# Prompt 4: Connect Wallet Integration--**Status:** - [ ] Not Started--## Objective-Integrate a "Connect Wallet" feature into the purchase modal, allowing users to connect their Solana wallet before making a purchase.--## Explanation-To purchase skills, users must have a connected Solana wallet. This prompt focuses on adding the necessary UI and logic to handle wallet connection directly within the purchase flow, ensuring a seamless user experience. We will use `@solana/wallet-adapter-react` and related libraries, which might already be in the project.--## Instructions-1. **Add a Wallet Connection Button:**- * In the purchase modal's HTML, add a "Connect Wallet" button. This button should be shown if the user's wallet is not connected, and the "Confirm Purchase" button should be hidden.--2. **Implement Wallet Connection Logic:**- * Use a wallet adapter library (like `@solana/wallet-adapter-react` or equivalent for vanilla JS) to handle the wallet connection logic.- * When the "Connect Wallet" button is clicked, trigger the wallet adapter's connection modal.- * Once the wallet is connected, update the UI of the purchase modal to hide the "Connect Wallet" button and show the "Confirm Purchase" button.--3. **Manage Wallet State:**- * Maintain a global state that tracks the user's wallet connection status and public key.- * The `renderDetail` function and the purchase modal logic should react to changes in this wallet state.--## Code Example (JavaScript in `src/marketplace.js`)--```javascript-// This example assumes a wallet adapter setup that exposes a `wallet` object-// and `connectWallet` function.--// In the event listener for the purchase button-$('d-skills').addEventListener('click', (e) => {- if (e.target.classList.contains('purchase-btn')) {- // ... (previous modal logic)-- // New logic to handle wallet connection- if (wallet.connected) {- $('modal-connect-wallet-btn').style.display = 'none';- $('modal-confirm-purchase-btn').style.display = 'block';- } else {- $('modal-connect-wallet-btn').style.display = 'block';- $('modal-confirm-purchase-btn').style.display = 'none';- }-- purchaseModal.style.display = 'flex';- }-});--// Event listener for the new connect wallet button-$('modal-connect-wallet-btn').addEventListener('click', async () => {- try {- await connectWallet();- // After successful connection, update the modal UI- $('modal-connect-wallet-btn').style.display = 'none';- $('modal-confirm-purchase-btn').style.display = 'block';- } catch (error) {- console.error('Failed to connect wallet:', error);- // Handle connection error (e.g., show a toast message)- }-});-```--## Code Example (HTML in `marketplace.html`)--```html-<!-- Update the modal footer -->-<div class="modal-footer">- <button id="modal-connect-wallet-btn" class="purchase-btn" style="display: none;">Connect Wallet</button>- <button id="modal-confirm-purchase-btn" class="purchase-btn" style="display: none;">Confirm Purchase</button>-</div>-```diff --git a/docs/monetization-prompts/04-database-schema-user-purchases.md b/docs/monetization-prompts/04-database-schema-user-purchases.mddeleted file mode 100644index 36eda9ea9..000000000--- a/docs/monetization-prompts/04-database-schema-user-purchases.md+++ /dev/null@@ -1,52 +0,0 @@-# Prompt 04: Database Schema for User Skill Purchases--## Objective-Create a database table to track which users have purchased which skills, effectively acting as a license or entitlement ledger.--## Explanation-When a user buys a skill, we need to record that transaction to grant them access. The `user_skill_purchases` table will store this information, linking a user, a skill, and the transaction details of their purchase. This table is critical for gating access to paid skills.--## Instructions-1. **Locate the Schema File:**- * Open the main database schema definition file at `api/_lib/schema.sql`.--2. **Define the `user_skill_purchases` Table:**- * Add a `CREATE TABLE` statement for `user_skill_purchases`.- * The table should include:- * `id`: UUID primary key.- * `user_id`: Foreign key to `users(id)`.- * `agent_id`: Foreign key to `agent_identities(id)`.- * `skill_id`: The identifier of the purchased skill.- * `price_id`: Foreign key to `agent_skill_prices(id)` to link to the exact price at time of purchase.- * `transaction_id`: A text field to store the on-chain transaction signature.- * `status`: An enum or text field for the purchase status (e.g., 'pending', 'confirmed', 'failed').- * `created_at`: Standard timestamp.--3. **Add Indexes:**- * Create a unique index on `(user_id, agent_id, skill_id)` to prevent duplicate purchase records.- * Create an index on `transaction_id` for quick lookups.--## SQL Example--```sql--- In api/_lib/schema.sql--CREATE TYPE purchase_status AS ENUM ('pending', 'confirmed', 'failed');--CREATE TABLE user_skill_purchases (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL REFERENCES users(id),- agent_id UUID NOT NULL REFERENCES agent_identities(id),- skill_id TEXT NOT NULL,- price_id UUID NOT NULL REFERENCES agent_skill_prices(id),- transaction_id TEXT, -- e.g., Solana transaction signature- status purchase_status NOT NULL DEFAULT 'pending',- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);--CREATE UNIQUE INDEX idx_user_skill_purchases_one_per_user-ON user_skill_purchases (user_id, agent_id, skill_id);--CREATE INDEX idx_user_skill_purchases_tx_id ON user_skill_purchases(transaction_id);-```diff --git a/docs/monetization-prompts/04-wallet-integration-setup.md b/docs/monetization-prompts/04-wallet-integration-setup.mddeleted file mode 100644index 81caaf2c5..000000000--- a/docs/monetization-prompts/04-wallet-integration-setup.md+++ /dev/null@@ -1,76 +0,0 @@-----status: not-started------# Prompt 04: Frontend Wallet Integration Setup--## Objective-Integrate a Solana wallet adapter to allow users to connect their wallets (e.g., Phantom) to the application.--## Explanation-To perform any on-chain transactions, the user must first connect their cryptocurrency wallet. This step involves adding the necessary libraries and UI elements for wallet connection. We will use the official Solana wallet-adapter libraries.--## Instructions-- [ ] **Add Wallet-Adapter Libraries:**- - [ ] Include the Solana wallet-adapter scripts in `marketplace.html`. You can use a CDN like unpkg for this proof-of-concept. You'll need `@solana/wallet-adapter-base` and `@solana/wallet-adapter-wallets`, plus the DOM integration package.--- [ ] **Add "Connect Wallet" Button:**- - [ ] Add a "Connect Wallet" button to the header of the application. The button text should dynamically update to show the user's wallet address when connected.--- [ ] **Initialize the Wallet Adapter:**- - [ ] In your main JavaScript file (`src/marketplace.js`), initialize the wallet adapter.- - [ ] Configure the wallets you want to support (e.g., Phantom, Solflare).- - [ ] Add logic to the "Connect Wallet" button to trigger the connection prompt.- - [ ] Listen for connection status changes to update the UI accordingly.--## HTML Example (in `marketplace.html` header)--```html-<div class="wallet-controls">- <button id="connect-wallet-btn">Connect Wallet</button>-</div>-```--## JavaScript Example (`src/marketplace.js`)--```javascript-// This is a simplified example. Refer to Solana wallet-adapter docs for the full setup.--// Use imports if you have a build system, or window vars from CDN-const { WalletAdapterNetwork } = solanaWalletAdapter;-const {- ConnectionProvider,- WalletProvider,-} = solanaWalletAdapterReact;-const {- WalletModalProvider,- WalletMultiButton,-} = solanaWalletAdapterReactUi;--// In your main app logic-const network = WalletAdapterNetwork.Devnet;-const endpoint = web3.clusterApiUrl(network);-const wallets = [new PhantomWalletAdapter()];--// You would typically wrap your app in providers.-// For vanilla JS, you'll need to instantiate and manage the adapter manually.--const wallet = ... // initialization logic--const connectBtn = document.getElementById('connect-wallet-btn');-connectBtn.addEventListener('click', async () => {- try {- await wallet.connect();- } catch (error) {- console.error('Failed to connect wallet', error);- }-});--wallet.on('connect', (publicKey) => {- connectBtn.textContent = `${publicKey.toBase58().slice(0, 4)}...${publicKey.toBase58().slice(-4)}`;-});--wallet.on('disconnect', () => {- connectBtn.textContent = 'Connect Wallet';-});-```diff --git a/docs/monetization-prompts/05-api-initiate-purchase.md b/docs/monetization-prompts/05-api-initiate-purchase.mddeleted file mode 100644index 9807f7792..000000000--- a/docs/monetization-prompts/05-api-initiate-purchase.md+++ /dev/null@@ -1,74 +0,0 @@-# Prompt 05: API Endpoint to Initiate a Purchase--## Objective-Create a backend endpoint that initiates the skill purchase process by creating a pending purchase record and returning transaction details to the client.--## Explanation-The purchase flow begins when a user clicks "buy". This endpoint will be responsible for creating a record in the `user_skill_purchases` table with a 'pending' status. For a Solana-based payment, it will then generate the necessary parameters for the frontend to construct a Solana Pay transaction request.--## Instructions-1. **Create the API Endpoint File:**- * Create a new file, e.g., `api/marketplace/purchase.js`.--2. **Implement the `POST` Handler:**- * **Authentication:** Get the logged-in user.- * **Input Validation:** Expect an `agent_id` and `skill_id` in the request body. Use `zod` for validation.- * **Check for Existing Purchase:** Verify the user hasn't already bought this skill.- * **Fetch Skill Price:** Get the current price from `agent_skill_prices`.- * **Create Pending Record:** Insert a new row into `user_skill_purchases` with `status = 'pending'`.- * **Generate Solana Pay Parameters:**- * Create a unique reference key for the transaction (e.g., the new purchase ID).- * Return the recipient address (the creator's wallet), the SPL token mint (e.g., USDC), the amount, and the reference key.- * **Return Response:** Send back the Solana Pay parameters and the `purchaseId` to the client.--## Code Example (`api/marketplace/purchase.js`)--```javascript-import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { error, json, wrap } from '../_lib/http.js';-import { z } from 'zod';-import { Keypair } from '@solana/web3.js'; // Assuming solana-sdk is available--const purchaseSchema = z.object({- agent_id: z.string().uuid(),- skill_id: z.string().min(1),-});--export default wrap(async (req, res) => {- if (req.method !== 'POST') return error(res, 405, 'method_not_allowed');-- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized');-- const body = purchaseSchema.parse(await req.json());-- // Fetch price and creator info- const [priceInfo] = await sql`- SELECT id, creator_id, amount, currency_mint- FROM agent_skill_prices- WHERE agent_id = ${body.agent_id} AND skill_id = ${body.skill_id} AND deleted_at IS NULL- `;- if (!priceInfo) return error(res, 404, 'price_not_found');-- // TODO: Fetch creator's wallet address from users table- const creatorWallet = '...'; // Placeholder-- // Create pending purchase record- const [purchase] = await sql`- INSERT INTO user_skill_purchases (user_id, agent_id, skill_id, price_id, status)- VALUES (${user.id}, ${body.agent_id}, ${body.skill_id}, ${priceInfo.id}, 'pending')- RETURNING id- `;-- // Return details for Solana Pay transaction- return json(res, {- purchaseId: purchase.id,- recipient: creatorWallet,- amount: (priceInfo.amount / 1_000_000).toString(), // Assuming 6 decimals for USDC- splToken: priceInfo.currency_mint,- reference: purchase.id,- label: `3D-Agent Skill: ${body.skill_id}`,- });-});-```diff --git a/docs/monetization-prompts/05-solana-pay-integration.md b/docs/monetization-prompts/05-solana-pay-integration.mddeleted file mode 100644index 7eb3a6193..000000000--- a/docs/monetization-prompts/05-solana-pay-integration.md+++ /dev/null@@ -1,70 +0,0 @@-----status: not-started------# Prompt 05: Solana Pay Transaction Integration--## Objective-Integrate Solana Pay into the purchase modal to generate a transaction for the user to sign.--## Explanation-When the user clicks "Confirm Purchase", we need to construct and present a Solana transaction. We'll use the Solana Pay standard, which allows for reliable transaction requests. The backend will create the transaction, and the frontend will use it.--## Instructions-- [ ] **Create a Backend Endpoint for Transaction Creation:**- - [ ] Create a new API endpoint, e.g., `POST /api/transactions/create-skill-purchase`.- - [ ] This endpoint will take `agentId`, `skillName`, and the `buyerPublicKey` as input.- - [ ] It should look up the skill price, the creator's destination wallet, and the platform fee wallet.- - [ ] Using the Solana SDK (`@solana/web3.js`), it will construct a transaction that transfers the correct amount of USDC from the buyer to the creator (and platform).- - [ ] The endpoint should return the serialized transaction.--- [ ] **Update Frontend Modal Logic:**- - [ ] In `src/marketplace.js`, modify the event listener for the "Confirm Purchase" button (`#modal-confirm-btn`).- - [ ] When clicked, it should first check if the user's wallet is connected.- - [ ] Then, it should make a `POST` request to your new backend endpoint.- - [ ] The frontend receives the serialized transaction from the backend.--- [ ] **Sign and Send the Transaction:**- - [ ] Use the wallet-adapter's `sendTransaction` method to ask the user to sign and send the transaction received from the backend.- - [ ] Handle potential errors during this process (e.g., user rejection).--## JavaScript Example (`src/marketplace.js` - Confirm Button Listener)--```javascript-const confirmBtn = document.getElementById('modal-confirm-btn');-confirmBtn.addEventListener('click', async () => {- if (!wallet.connected) {- alert('Please connect your wallet first.');- return;- }-- // Get details from modal/app state- const skillName = document.getElementById('modal-skill-name').textContent;- const buyerPublicKey = wallet.publicKey.toBase58();-- try {- // 1. Fetch transaction from backend- const response = await fetch('/api/transactions/create-skill-purchase', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ skillName, agentId: currentAgent.id, buyerPublicKey }),- });- const { transaction } = await response.json();-- // 2. Deserialize and send- const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));- const tx = solanaWeb3.Transaction.from(Buffer.from(transaction, 'base64'));-- const signature = await wallet.sendTransaction(tx, connection);-- // 3. Start polling for confirmation (covered in next prompt)- console.log('Transaction sent with signature:', signature);- await connection.confirmTransaction(signature, 'processed');- alert('Purchase successful!');-- } catch (error) {- console.error('Purchase failed', error);- alert('Purchase failed. See console for details.');- }-});-```diff --git a/docs/monetization-prompts/05-spl-token-transfer.md b/docs/monetization-prompts/05-spl-token-transfer.mddeleted file mode 100644index 53ed602b6..000000000--- a/docs/monetization-prompts/05-spl-token-transfer.md+++ /dev/null@@ -1,79 +0,0 @@-# Prompt 5: Execute SPL Token Transfer for Purchase--**Status:** - [ ] Not Started--## Objective-Implement the client-side logic to construct and send a Solana transaction to transfer SPL tokens (e.g., USDC) from the user's wallet to the creator's wallet when the "Confirm Purchase" button is clicked.--## Explanation-This is the core of the purchase transaction. When a user confirms they want to buy a skill, the frontend needs to create a transaction, have the user sign it with their wallet, and send it to the Solana network.--## Instructions-1. **Gather Transaction Details:**- * When the "Confirm Purchase" button is clicked, you need the following information:- * User's public key (from the connected wallet).- * Creator's public key (this should be part of the agent's data).- * The price (amount).- * The currency mint address (e.g., USDC mint address).--2. **Construct the Transaction:**- * Use `@solana/web3.js` to create a new `Transaction`.- * Add an instruction to the transaction to transfer the SPL token. You will need functions from `@solana/spl-token` to create the transfer instruction.- * The instruction will need the source token account, destination token account, amount, and the user's public key as the owner.- * **Important:** You'll need to find the user's and the creator's associated token accounts for the given mint.--3. **Sign and Send the Transaction:**- * Use the `sendTransaction` method provided by the wallet adapter, passing it the transaction you constructed.- * The wallet adapter will prompt the user to approve and sign the transaction.- * Await the confirmation of the transaction.--## Code Example (JavaScript in `src/marketplace.js`)--```javascript-// This assumes a wallet adapter that provides a `publicKey` and `sendTransaction` function.-import { Connection, PublicKey, Transaction } from '@solana/web3.js';-import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';--const connection = new Connection('your_rpc_url');--$('modal-confirm-purchase-btn').addEventListener('click', async () => {- const agent = window.currentAgent;- const skillName = $('modal-skill-name').textContent;- const priceInfo = agent.skill_prices[skillName];- const creatorPublicKey = new PublicKey(agent.creator_address);- const userPublicKey = wallet.publicKey;-- if (!priceInfo || !creatorPublicKey || !userPublicKey) {- console.error('Missing required info for transaction');- return;- }-- try {- const currencyMint = new PublicKey(priceInfo.currency_mint);-- // Get the associated token accounts- const userTokenAccount = await getAssociatedTokenAddress(currencyMint, userPublicKey);- const creatorTokenAccount = await getAssociatedTokenAddress(currencyMint, creatorPublicKey);-- const transaction = new Transaction().add(- createTransferInstruction(- userTokenAccount,- creatorTokenAccount,- userPublicKey,- priceInfo.amount,- [],- )- );-- const signature = await wallet.sendTransaction(transaction, connection);- await connection.confirmTransaction(signature, 'processed');-- console.log('Transaction successful with signature:', signature);- // Next step: Call backend to record the purchase-- } catch (error) {- console.error('Transaction failed:', error);- // Show error message to user- }-});-```diff --git a/docs/monetization-prompts/06-backend-purchase-endpoint.md b/docs/monetization-prompts/06-backend-purchase-endpoint.mddeleted file mode 100644index 1058faee7..000000000--- a/docs/monetization-prompts/06-backend-purchase-endpoint.md+++ /dev/null@@ -1,79 +0,0 @@-# Prompt 6: Create Backend Endpoint to Verify and Record Purchase--**Status:** - [ ] Not Started--## Objective-Create a backend API endpoint that the frontend can call after a Solana transaction is successfully confirmed. This endpoint will verify the transaction on-chain and record the skill ownership in the database.--## Explanation-Client-side confirmation of a transaction is not enough. For security and reliability, the backend must independently verify that the correct payment was made before granting the user access to the skill.--## Instructions-1. **Create a New API Endpoint:**- * Create a new file for the endpoint, e.g., `api/marketplace/purchase-skill.js`.- * This endpoint should accept the `agentId`, `skillName`, and the `transactionSignature` as input.- * It must be an authenticated endpoint, ensuring a user is logged in.--2. **Implement Transaction Verification:**- * In the endpoint's handler, use `@solana/web3.js` to connect to a Solana RPC node.- * Fetch the confirmed transaction using the provided signature.- * Parse the transaction details to verify:- * The transaction was successful.- * The source address matches the logged-in user's wallet address.- * The destination address matches the agent creator's wallet address.- * The transferred amount is correct for the skill being purchased.- * The mint of the transferred token is correct.--3. **Record Ownership in the Database:**- * If verification is successful, insert a new record into a table that tracks skill ownership. Let's call this table `user_agent_skills`.- * The table should store at least the `user_id`, `agent_id`, and `skill_name`.--## Code Example (Backend - `api/marketplace/purchase-skill.js`)--```javascript-import { Connection, PublicKey } from '@solana/web3.js';-import { getDB } from './_lib/db'; // Your database utility--export default async function handler(req, res) {- // Assume user is authenticated and user ID is available- const userId = req.user.id;- const { agentId, skillName, transactionSignature } = req.body;-- // Fetch agent and skill price details from your DB- const db = getDB();- const agent = await db.getAgent(agentId);- const skillPrice = await db.getSkillPrice(agentId, skillName);-- if (!agent || !skillPrice) {- return res.status(404).json({ error: 'Agent or skill not found.' });- }-- try {- const connection = new Connection('your_rpc_url');- const tx = await connection.getParsedTransaction(transactionSignature, 'confirmed');-- if (!tx) throw new Error('Transaction not found.');-- // Very simplified verification logic. In reality, this needs to be very robust.- const instruction = tx.transaction.message.instructions.find(- (ix) => ix.parsed?.type === 'transfer'- );-- const transferInfo = instruction.parsed.info;- const isCorrectAmount = BigInt(transferInfo.amount) === BigInt(skillPrice.amount);- const isCorrectDestination = new PublicKey(transferInfo.destination).equals(new PublicKey(agent.creator_address));-- if (isCorrectAmount && isCorrectDestination) {- // Record the purchase in the database- await db.recordSkillPurchase(userId, agentId, skillName);- return res.status(200).json({ success: true, message: 'Purchase successful!' });- } else {- throw new Error('Transaction verification failed.');- }-- } catch (error) {- console.error('Purchase verification failed:', error);- return res.status(500).json({ error: 'Purchase verification failed.' });- }-}-```diff --git a/docs/monetization-prompts/06-frontend-solana-pay-qr-code.md b/docs/monetization-prompts/06-frontend-solana-pay-qr-code.mddeleted file mode 100644index b383697f4..000000000--- a/docs/monetization-prompts/06-frontend-solana-pay-qr-code.md+++ /dev/null@@ -1,63 +0,0 @@-# Prompt 06: Solana Pay Integration for QR Code--## Objective-Integrate Solana Pay on the frontend to generate a payment QR code when a user decides to buy a skill.--## Explanation-Solana Pay provides a seamless mobile payment experience. After the backend creates a pending purchase and returns the transaction details, the frontend needs to use those details to construct a Solana Pay URL and display it as a QR code. This allows the user to approve the transaction from their mobile wallet.--## Instructions-1. **Add a QR Code Library:**- * Install a client-side QR code generation library. `qrcode` is a popular choice.- * `npm install qrcode`--2. **Create a Purchase Modal:**- * In `marketplace.html`, create a hidden modal element that will display the QR code.- * This modal should have a canvas element for the QR code and show the price and skill name.--3. **Implement QR Code Generation:**- * In `src/marketplace.js`, create a function, e.g., `showPurchaseModal(txDetails)`.- * This function will be called with the response from the `/api/marketplace/purchase` endpoint.- * **Construct Solana Pay URL:** Create a URL according to the Solana Pay spec. The URL will be `solana:<recipient>?amount=<amount>&spl-token=<splToken>&reference=<reference>&label=<label>`.- * **Render QR Code:** Use the `qrcode` library to render the Solana Pay URL into the modal's canvas.- * **Show the Modal:** Make the purchase modal visible to the user.--## Code Example (`src/marketplace.js`)--```javascript-import QRCode from 'qrcode';--// ... inside the event listener for a "Buy Skill" button--async function onBuySkill(agentId, skillId) {- // 1. Call the initiate purchase API- const res = await fetch('/api/marketplace/purchase', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ agent_id: agentId, skill_id: skillId }),- });- const txDetails = await res.json();-- // 2. Show the purchase modal- showPurchaseModal(txDetails);-}--function showPurchaseModal(txDetails) {- const modal = $('purchase-modal');- const canvas = $('qr-canvas');-- const url = new URL(`solana:${txDetails.recipient}`);- url.searchParams.set('amount', txDetails.amount);- url.searchParams.set('spl-token', txDetails.splToken);- url.searchParams.set('reference', txDetails.reference);- url.searchParams.set('label', txDetails.label);-- QRCode.toCanvas(canvas, url.toString(), (error) => {- if (error) console.error(error);- console.log('QR code generated!');- });-- modal.hidden = false;- // Start polling for transaction confirmation... (covered in next prompt)-}-```diff --git a/docs/monetization-prompts/06-transaction-status-polling.md b/docs/monetization-prompts/06-transaction-status-polling.mddeleted file mode 100644index 37bdb3d50..000000000--- a/docs/monetization-prompts/06-transaction-status-polling.md+++ /dev/null@@ -1,62 +0,0 @@-----status: not-started------# Prompt 06: Transaction Status Polling and Verification--## Objective-After a transaction is sent, reliably confirm its success by polling a Solana RPC endpoint and then verifying it on the backend.--## Explanation-Sending a transaction to the network doesn't guarantee its success. We must confirm it has been processed and finalized. The frontend will poll for initial confirmation to give the user quick feedback, and the backend will do a final verification before unlocking the skill.--## Instructions-- [ ] **Frontend: Poll for Confirmation:**- - [ ] After sending the transaction with `sendTransaction`, the wallet adapter returns a transaction signature (txid).- - [ ] Use the `Connection` object's `confirmTransaction` method. This will poll the RPC until the transaction reaches a certain commitment level (e.g., 'processed' or 'confirmed').- - [ ] While polling, update the UI to show a "Processing..." state in the purchase modal.--- [ ] **Backend: Create a Verification Endpoint:**- - [ ] Create a new backend endpoint, e.g., `POST /api/skills/purchase/verify`.- - [ ] This endpoint will receive the `transactionSignature`.- - [ ] On the backend, use the Solana SDK to fetch the transaction details using the signature.--- [ ] **Backend: Verify Transaction Details:**- - [ ] In the verification endpoint, inspect the fetched transaction.- - [ ] Confirm that the transaction involves the correct sender (buyer), receiver (creator), and amount (price). This is a critical security step to prevent users from submitting fake or incorrect transaction signatures.- - [ ] If the transaction is valid, proceed to record the skill ownership (covered in the next prompt).--## JavaScript Example (`src/marketplace.js` - inside confirm button handler)--```javascript-// ... after const signature = await wallet.sendTransaction(tx, connection);--// Show processing state in UI-setModalState('processing');--const { value: status } = await connection.confirmTransaction(signature, 'confirmed');--if (status.err) {- console.error('Transaction failed to confirm', status.err);- setModalState('error', 'Transaction Failed');- return;-}--// Now that frontend has confirmation, send signature to backend for final verification-try {- const verifyResponse = await fetch('/api/skills/purchase/verify', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ transactionSignature: signature, agentId: currentAgent.id, skillName }),- });-- if (!verifyResponse.ok) throw new Error('Backend verification failed');-- setModalState('success', 'Purchase Complete!');- // Update UI to show skill as unlocked (covered in next prompt)--} catch (error) {- console.error('Backend verification failed', error);- setModalState('error', 'Verification Failed');-}-```diff --git a/docs/monetization-prompts/07-api-webhook-confirm-purchase.md b/docs/monetization-prompts/07-api-webhook-confirm-purchase.mddeleted file mode 100644index 8e2a3f895..000000000--- a/docs/monetization-prompts/07-api-webhook-confirm-purchase.md+++ /dev/null@@ -1,72 +0,0 @@-# Prompt 07: API Webhook to Confirm Solana Pay Transactions--## Objective-Create a webhook to receive confirmation of successful Solana Pay transactions, find the corresponding purchase record, and update its status.--## Explanation-The Solana Pay workflow includes a server-to-server confirmation. After a user approves a transaction, the Solana Pay service (or a custom RPC listener) will post the transaction signature to a webhook we provide. This webhook is the definitive confirmation of payment. It needs to verify the transaction on-chain and update our database accordingly.--## Instructions-1. **Create the Webhook API File:**- * Create a new file: `api/webhooks/solana-pay.js`.--2. **Implement the Webhook Handler:**- * **`find` Method:** Solana Pay first sends a `GET` request to verify the endpoint exists. The handler should return a label and icon for the payment sheet.- * **`transaction` Method (`POST`):**- * The `POST` request contains the `transaction` (signature) and `reference` (our `purchaseId`).- * **Verify Transaction:** Use a Solana RPC connection (`@solana/web3.js`) to fetch the transaction details using the signature.- * **Validate Details:**- * Check that the transaction was successful.- * Confirm that the destination address, mint address, and amount match the details stored in our `user_skill_purchases` and `agent_skill_prices` tables. This is crucial to prevent spoofed transactions.- * **Update Purchase Status:** If validation passes, update the `user_skill_purchases` record's `status` to `'confirmed'` and store the `transaction_id`.- * Return a success message to the Solana Pay service.--## Code Example (`api/webhooks/solana-pay.js`)--```javascript-import { Connection, PublicKey } from '@solana/web3.js';-import { sql } from '../_lib/db.js';-import { error, json, wrap } from '../_lib/http.js';--const SOLANA_RPC_URL = process.env.RPC_URL_1399901; // Example for Solana Mainnet-const connection = new Connection(SOLANA_RPC_URL, 'confirmed');--export default wrap(async (req, res) => {- if (req.method === 'GET') {- // Solana Pay endpoint validation- return json(res, {- label: '3D-Agent Skill Marketplace',- icon: 'https://three.ws/assets/logo.png',- });- }-- if (req.method === 'POST') {- const { transaction, reference } = await req.json();-- // 1. Find the purchase record using the reference- const [purchase] = await sql`SELECT ... FROM user_skill_purchases WHERE id = ${reference}`;- // ... join with prices to get expected amount, mint, recipient ...- if (!purchase || purchase.status !== 'pending') {- return error(res, 404, 'purchase_not_found_or_completed');- }-- // 2. Verify the transaction on-chain- const tx = await connection.getParsedTransaction(transaction, 'confirmed');- // ... logic to parse tx and confirm amount, mint, and recipient ...-- const isValid = /* ... validation logic ... */ ;-- if (isValid) {- await sql`- UPDATE user_skill_purchases- SET status = 'confirmed', transaction_id = ${transaction}, updated_at = NOW()- WHERE id = ${reference}- `;- return json(res, { message: 'Transaction confirmed' });- } else {- await sql`UPDATE ... SET status = 'failed' ...`;- return error(res, 400, 'transaction_invalid');- }- }-});-```diff --git a/docs/monetization-prompts/07-ui-feedback-on-purchase.md b/docs/monetization-prompts/07-ui-feedback-on-purchase.mddeleted file mode 100644index 625809b0f..000000000--- a/docs/monetization-prompts/07-ui-feedback-on-purchase.md+++ /dev/null@@ -1,28 +0,0 @@-----status: not-started------# Prompt 07: UI Feedback for Purchase Flow--## Objective-Provide clear, real-time UI feedback to the user during the entire purchase process (e.g., processing, success, failure).--## Explanation-A good user experience requires keeping the user informed. We will enhance the purchase modal to reflect the current state of the transaction, from initiation to completion.--## Instructions-- [ ] **Enhance the Modal HTML:**- - [ ] Add elements to the purchase modal to display different states: a loading spinner for processing, a success message/icon, and an error message/icon.--- [ ] **Create a UI State Management Function:**- - [ ] In `src/marketplace.js`, create a function like `setModalState(state, message)`.- - [ ] This function will accept states like 'confirm', 'processing', 'success', and 'error'.- - [ ] Based on the state, it will show/hide the appropriate elements in the modal (e.g., hide confirm/cancel buttons, show spinner).--- [ ] **Integrate State Changes into Purchase Logic:**- - [ ] Call `setModalState` at key points in the purchase flow:- - [ ] When the confirm button is first clicked, before sending the transaction: `setModalState('processing')`.- - [ ] If the transaction is successfully confirmed on the frontend and verified on the backend: `setModalState('success', 'Purchase Complete!')`.- - [ ] If any step fails (user rejects, transaction fails, backend verification fails): `setModalState('error', 'Something went wrong.')`.--## HTML Example (Enhanced Modal)diff --git a/docs/monetization-prompts/08-creator-ui-set-prices.md b/docs/monetization-prompts/08-creator-ui-set-prices.mddeleted file mode 100644index 37995ced6..000000000--- a/docs/monetization-prompts/08-creator-ui-set-prices.md+++ /dev/null@@ -1,50 +0,0 @@-# Prompt 08: Creator UI to Set Skill Prices--## Objective-Implement a user interface in the agent editor or creator dashboard that allows creators to add, edit, and remove prices for their agent's skills.--## Explanation-Now that the backend API for price management exists, we need to provide a user-friendly frontend for creators to use it. This will involve adding a new section to the agent editing page (`agent-edit.html`) where a list of the agent's skills is displayed, each with an input field to set its price.--## Instructions-1. **Locate the Agent Editor Page:**- * Open `agent-edit.html` and its corresponding JavaScript file, likely `src/agent-edit.js`.--2. **Add a "Skill Monetization" Section:**- * In `agent-edit.html`, add a new section or card titled "Skill Prices".- * This section should fetch and display the list of skills from the agent's manifest.--3. **Implement the UI for Each Skill:**- * For each skill listed, display:- * The skill name.- * An input field for the price (e.g., in USDC).- * A "Set Price" or "Save" button.- * A "Remove Price" button if a price is already set.--4. **Wire Up the API Calls:**- * In `src/agent-edit.js`, add event listeners to the "Save" and "Remove" buttons.- * **On Save:**- * Read the price from the input.- * Convert it to the smallest unit (e.g., multiply by 1,000,000 for USDC).- * Call the `POST` or `PUT` endpoint from Prompt 03 (`/api/agents/[id]/skill-prices`) with the `skill_id`, `amount`, and `currency_mint`.- * **On Remove:**- * Call the `DELETE` endpoint from Prompt 03.- * Provide user feedback (e.g., a success message or an error toast).--## HTML Example (`agent-edit.html`)--```html-<!-- Inside the agent editor form -->-<div class="card">- <h3>Skill Prices</h3>- <div id="skill-prices-list">- <!-- Skills will be rendered here by JavaScript -->- <!-- Example of a single skill item -->- <div class="skill-price-item">- <span>weather-forecast</span>- <input type="number" step="0.01" placeholder="USDC Price">- <button class="btn-primary">Set Price</button>- </div>- </div>-</div>-```diff --git a/docs/monetization-prompts/08-database-schema-for-pricing.md b/docs/monetization-prompts/08-database-schema-for-pricing.mddeleted file mode 100644index 83ced80c6..000000000--- a/docs/monetization-prompts/08-database-schema-for-pricing.md+++ /dev/null@@ -1,69 +0,0 @@-# Prompt 8: Database Schema for Skill Pricing and Ownership--**Status:** - [ ] Not Started--## Objective-Design and create the necessary SQL table schemas to store skill prices and user skill ownership.--## Explanation-A robust backend requires a well-defined database structure. This prompt outlines the schemas for two key tables: one to define the prices of skills set by creators, and another to track which users have purchased which skills.--## Instructions-1. **Design `agent_skill_prices` Table:**- * This table will store the price for each monetized skill of an agent.- * **Columns:**- * `id`: Primary key (e.g., UUID or auto-incrementing integer).- * `agent_id`: Foreign key to the `agents` table.- * `skill_name`: The name of the skill (e.g., 'sentiment-analysis').- * `amount`: The price in the smallest denomination of the currency (e.g., lamports for SOL, or 10^-6 for USDC). Use a `bigint` for this.- * `currency_mint`: The public key of the SPL token mint used for the currency (e.g., USDC mint address).- * `creator_address`: The Solana address where funds should be sent.- * `created_at`, `updated_at`: Timestamps.- * Create a unique constraint on (`agent_id`, `skill_name`).--2. **Design `user_agent_skills` Table:**- * This table will link users to the skills they've purchased.- * **Columns:**- * `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_tx_signature`: The Solana transaction signature of the purchase.- * `created_at`: Timestamp.- * Create a unique constraint on (`user_id`, `agent_id`, `skill_name`).--3. **Create Migration File:**- * Write the SQL `CREATE TABLE` statements for both tables in a new migration file. The project seems to have a migration system in `scripts/apply-migrations.mjs`, so follow that pattern.--## SQL Example (for a PostgreSQL database)--```sql--- In a new migration file in your migrations directory--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,- creator_address VARCHAR(255) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- UNIQUE (agent_id, skill_name)-);--CREATE TABLE user_agent_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_tx_signature VARCHAR(255) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- UNIQUE (user_id, agent_id, skill_name)-);---- It's good practice to create indexes for foreign keys-CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);-CREATE INDEX idx_user_agent_skills_user_id ON user_agent_skills(user_id);-CREATE INDEX idx_user_agent_skills_agent_id ON user_agent_skills(agent_id);-```diff --git a/docs/monetization-prompts/08-purchase-skill-api-endpoint.md b/docs/monetization-prompts/08-purchase-skill-api-endpoint.mddeleted file mode 100644index 9455bd880..000000000--- a/docs/monetization-prompts/08-purchase-skill-api-endpoint.md+++ /dev/null@@ -1,79 +0,0 @@-----status: not-started------# Prompt 08: Backend Purchase API Endpoint--## Objective-Create the initial backend API endpoint that constructs and returns a Solana transaction for a skill purchase.--## Explanation-The frontend needs a secure way to get a valid transaction object. The backend is responsible for creating this transaction because it has secure access to critical information like the creator's payout wallet and the correct skill price, preventing tampering.--## Instructions-- [ ] **Create the API File and Route:**- - [ ] Create a new API file, e.g., `api/transactions/create-skill-purchase.js`.- - [ ] This file will handle `POST` requests. It should expect `agentId`, `skillName`, and `buyerPublicKey` in the request body.--- [ ] **Fetch Necessary Data:**- - [ ] Inside the endpoint logic, perform database lookups to get:- - [ ] The skill's price from the `agent_skill_prices` table.- - [ ] The agent creator's payout wallet address from the `users` or `agents` table.- - [ ] The platform's fee wallet address (can be a constant or from a config file).--- [ ] **Construct the Solana Transaction:**- - [ ] Use the `@solana/web3.js` SDK.- - [ ] You will be creating a SPL Token Transfer instruction. The currency is likely USDC, so you'll need its mint address.- - [ ] The transaction will transfer `X` amount of USDC from the `buyerPublicKey` to the creator's wallet. (Platform fees will be added in a later prompt).- - [ ] Set the `feePayer` to be the `buyerPublicKey`.- - [ ] Fetch a recent blockhash.--- [ ] **Serialize and Return the Transaction:**- - [ ] Serialize the transaction but **do not sign it**. The user's wallet must sign it.- - [ ] Return the serialized transaction as a base64-encoded string in the JSON response.--## Code Example (Node.js with Express-like framework)--```javascript-import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';-import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';--export default async function handler(req, res) {- if (req.method !== 'POST') return res.status(405).end();-- const { agentId, skillName, buyerPublicKey } = req.body;-- // 1. Fetch data from DB (pseudo-code)- const priceInfo = await db.getSkillPrice(agentId, skillName); // { amount: 1000000, currency_mint: '...' }- const creator = await db.getAgentCreator(agentId); // { payout_wallet: '...' }-- const connection = new Connection(clusterApiUrl('devnet'));- const buyer = new PublicKey(buyerPublicKey);- const creatorWallet = new PublicKey(creator.payout_wallet);- const usdcMint = new PublicKey(priceInfo.currency_mint);-- // 2. Get the buyer's and creator's token accounts- const buyerUsdcAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, usdcMint, buyer);- const creatorUsdcAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, usdcMint, creatorWallet);-- // 3. Create the transaction- const transaction = new Transaction().add(- createTransferInstruction(- buyerUsdcAccount.address,- creatorUsdcAccount.address,- buyer,- priceInfo.amount // Amount in smallest unit (lamports for SOL, etc.)- )- );-- transaction.feePayer = buyer;- transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;-- // 4. Serialize and return- const serializedTx = transaction.serialize({ requireAllSignatures: false });-- res.status(200).json({- transaction: serializedTx.toString('base64'),- });-}-```diff --git a/docs/monetization-prompts/09-admin-interface-for-prices.md b/docs/monetization-prompts/09-admin-interface-for-prices.mddeleted file mode 100644index 7a2ae97ef..000000000--- a/docs/monetization-prompts/09-admin-interface-for-prices.md+++ /dev/null@@ -1,92 +0,0 @@-# Prompt 9: Create an Admin Interface for Setting Skill Prices--**Status:** - [ ] Not Started--## Objective-Develop a UI for agent creators to set and manage prices for their agent's skills.--## Explanation-For creators to monetize their skills, they need an interface to specify which skills are for sale and at what price. This will likely be part of the agent editing page (`agent-edit.html`).--## Instructions-1. **Create UI for Price Management:**- * In `agent-edit.html`, add a new section for "Skill Monetization".- * This section should list all the skills available for the agent.- * For each skill, provide input fields for:- * Price (e.g., in USDC).- * Currency (a dropdown, initially just supporting USDC).- * A "Set Price" or "Save" button.- * Also display the current price if one is set.--2. **Develop Backend Endpoint for Setting Prices:**- * Create a new API endpoint, e.g., `api/agents/set-skill-price.js`.- * This must be an authenticated endpoint. Before processing, it must verify that the logged-in user is the creator of the agent.- * It should accept `agentId`, `skillName`, `amount`, and `currencyMint`.- * The handler will perform an `INSERT ... ON CONFLICT ... UPDATE` (or an "upsert") operation on the `agent_skill_prices` table for the given agent and skill.--3. **Connect Frontend to Backend:**- * In the JavaScript for the agent edit page, add an event listener to the "Set Price" button.- * When clicked, it should gather the data from the input fields and make a `POST` request to the new API endpoint.- * Provide feedback to the user on success or failure.--## Code Example (HTML for `agent-edit.html`)--```html-<!-- In agent-edit.html, inside the agent form -->-<div class="form-section">- <h3>Skill Monetization</h3>- <div id="skill-pricing-list">- <!-- Skills will be dynamically rendered here by JavaScript -->- </div>-</div>-```--## Code Example (JavaScript for the agent edit page)--```javascript-// Function to render the skill pricing interface-function renderSkillPricing(agent) {- const container = $('skill-pricing-list');- container.innerHTML = agent.skills.map(skill => `- <div class="skill-price-entry">- <label>${escapeHtml(skill.name)}</label>- <input type="number" placeholder="Price (USDC)" data-skill-name="${escapeHtml(skill.name)}" value="${(agent.skill_prices?.[skill.name]?.amount / 1e6) || ''}">- <button class="set-price-btn" data-skill-name="${escapeHtml(skill.name)}">Save</button>- </div>- `).join('');-}--// Event listener for the save buttons-$('skill-pricing-list').addEventListener('click', async (e) => {- if (e.target.classList.contains('set-price-btn')) {- const skillName = e.target.dataset.skillName;- const priceInput = document.querySelector(`input[data-skill-name="${skillName}"]`);- const priceInUSDC = parseFloat(priceInput.value);-- if (isNaN(priceInUSDC) || priceInUSDC <= 0) {- alert('Please enter a valid price.');- return;- }-- const amountInLamports = priceInUSDC * 1e6;-- // Call the backend- const response = await fetch('/api/agents/set-skill-price', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- agentId: currentAgentId,- skillName,- amount: amountInLamports,- currencyMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u1b', // USDC mint- }),- });-- if (response.ok) {- showToast('Price updated!', 'success');- } else {- showToast('Failed to update price.', 'error');- }- }-});-```diff --git a/docs/monetization-prompts/09-frontend-polling-confirmation.md b/docs/monetization-prompts/09-frontend-polling-confirmation.mddeleted file mode 100644index bd122331b..000000000--- a/docs/monetization-prompts/09-frontend-polling-confirmation.md+++ /dev/null@@ -1,55 +0,0 @@-# Prompt 09: Frontend Polling for Purchase Confirmation--## Objective-After displaying the Solana Pay QR code, implement a client-side polling mechanism to check the status of the purchase and update the UI upon confirmation.--## Explanation-While the webhook provides server-to-server confirmation, the user on the frontend is waiting for feedback. We need to poll a backend endpoint to check the status of the `user_skill_purchases` record. Once the status changes from 'pending' to 'confirmed', we can close the purchase modal and show a success message.--## Instructions-1. **Create a Status Check API Endpoint:**- * Create a new API endpoint, e.g., `api/marketplace/purchase-status.js`.- * It should accept a `purchaseId` as a query parameter.- * The endpoint will query the `user_skill_purchases` table for the given ID.- * It should return the current `status` of the purchase record.- * **Security:** Ensure the user making the request is the same user who initiated the purchase.--2. **Implement Frontend Polling:**- * In `src/marketplace.js`, within the `showPurchaseModal` function (from Prompt 06), start a polling loop after displaying the QR code.- * Use `setInterval` to call the `/api/marketplace/purchase-status?purchaseId=...` endpoint every few seconds (e.g., 2-3 seconds).- * **On Confirmation:** If the endpoint returns `{ status: 'confirmed' }`, clear the interval, hide the modal, and display a success message to the user.- * **On Failure:** If it returns `{ status: 'failed' }`, inform the user the payment failed.- * **Timeout:** Implement a timeout (e.g., 5 minutes) to stop polling if no confirmation is received.--## Code Example (`src/marketplace.js`)--```javascript-// In showPurchaseModal function, after showing the modal...--const purchaseId = txDetails.purchaseId;-const pollingId = setInterval(async () => {- try {- const res = await fetch(`/api/marketplace/purchase-status?purchaseId=${purchaseId}`);- if (!res.ok) return; // Continue polling on server error-- const { status } = await res.json();-- if (status === 'confirmed') {- clearInterval(pollingId);- $('purchase-modal').hidden = true;- // TODO: Show success message- // TODO: Update UI to show the skill as 'Owned'- } else if (status === 'failed') {- clearInterval(pollingId);- // TODO: Show failure message- }- } catch (e) {- console.error('Polling failed', e);- }-}, 2500);--// Set a timeout to stop polling after 5 minutes-setTimeout(() => {- clearInterval(pollingId);-}, 300000);-```diff --git a/docs/monetization-prompts/09-verify-solana-transaction-api.md b/docs/monetization-prompts/09-verify-solana-transaction-api.mddeleted file mode 100644index b600feba6..000000000--- a/docs/monetization-prompts/09-verify-solana-transaction-api.md+++ /dev/null@@ -1,78 +0,0 @@-----status: not-started------# Prompt 09: Backend Transaction Verification API--## Objective-Create the backend API endpoint that securely verifies a Solana transaction signature after it has been confirmed on the blockchain.--## Explanation-This is a critical security step. The frontend informs the backend that a transaction is complete by sending its signature. The backend must then independently fetch the transaction from the blockchain and verify that its contents (amount, sender, receiver) are correct before granting the user access to the skill. This prevents users from sending fake signatures or signatures for unrelated transactions.--## Instructions-- [ ] **Create the API File and Route:**- - [ ] Create a new API file, e.g., `api/skills/purchase/verify.js`.- - [ ] It will handle `POST` requests with `transactionSignature`, `agentId`, and `skillName` in the body.--- [ ] **Fetch the Transaction from the Blockchain:**- - [ ] Use the `@solana/web3.js` SDK's `connection.getParsedTransaction()` method with the provided signature. This method is useful as it parses the instruction data.--- [ ] **Perform Verification Checks:**- - [ ] Check if the transaction was successful (`err` field is null).- - [ ] Look up the expected price and creator wallet from your database for the given `agentId` and `skillName`.- - [ ] Parse the transaction's instructions to find the token transfer.- - [ ] **Crucially, verify:**- - [ ] The transfer `source` matches the buyer's public key (you might need to get this from the user's session or the transaction itself).- - [ ] The transfer `destination` matches the creator's expected payout wallet.- - [ ] The transfer `amount` matches the expected price from your database.- - [ ] The token `mint` matches the expected currency (e.g., USDC).--- [ ] **Handle Verification Outcome:**- - [ ] If all checks pass, proceed to the next step: recording the ownership in the database.- - [ ] If any check fails, return a `400 Bad Request` or `403 Forbidden` error with a message like "Transaction verification failed."--## Code Example (Node.js with Express-like framework)--```javascript-import { Connection, PublicKey } from '@solana/web3.js';--export default async function handler(req, res) {- const { transactionSignature, agentId, skillName } = req.body;-- // 1. Get expected data from DB (pseudo-code)- const expectedPrice = await db.getSkillPrice(agentId, skillName);- const creator = await db.getAgentCreator(agentId);- // Assume we get buyer public key from authenticated session- const expectedBuyer = new PublicKey(req.session.user.publicKey);-- const connection = new Connection(clusterApiUrl('devnet'));-- // 2. Fetch transaction- const tx = await connection.getParsedTransaction(transactionSignature, 'confirmed');- if (!tx || tx.meta.err) {- return res.status(400).json({ message: "Transaction not found or failed." });- }-- // 3. Find the transfer instruction and verify details- const transferInstruction = tx.transaction.message.instructions.find(ix => ix.parsed?.type === 'transferChecked');-- if (!transferInstruction) {- return res.status(400).json({ message: "No valid transfer instruction found." });- }-- const { source, destination, tokenAmount } = transferInstruction.parsed.info;- const isVerified = source === expectedBuyer.toBase58() &&- destination === creator.payout_wallet &&- parseInt(tokenAmount.amount) === expectedPrice.amount;-- // 4. Handle outcome- if (isVerified) {- // Ownership recording logic comes next- await recordSkillOwnership(req.session.user.id, agentId, skillName);- res.status(200).json({ message: "Verification successful." });- } else {- res.status(403).json({ message: "Transaction details do not match expected values." });- }-}-```diff --git a/docs/monetization-prompts/10-creator-dashboard-earnings-ui.md b/docs/monetization-prompts/10-creator-dashboard-earnings-ui.mddeleted file mode 100644index e799147c5..000000000--- a/docs/monetization-prompts/10-creator-dashboard-earnings-ui.md+++ /dev/null@@ -1,67 +0,0 @@-# Prompt 10: Creator Dashboard UI for Earnings--## Objective-Create a new page in the creator dashboard to display total earnings, a list of recent transactions, and other relevant monetization analytics.--## Explanation-To create a complete ecosystem, creators must be able to track their sales. This prompt outlines the creation of a new "Earnings" tab in the dashboard that provides an overview of their revenue from skill sales.--## Instructions-1. **Create New Dashboard Page:**- * Create a new HTML file: `dashboard/earnings.html`.- * Create a corresponding JavaScript file: `src/dashboard-earnings.js`.- * Add a link to this new page in the main dashboard navigation (`dashboard/index.html`).--2. **Design the Earnings UI:**- * The `earnings.html` page should contain placeholders for:- * A "Total Revenue" card.- * A "Withdrawable Balance" card.- * A table or list for "Recent Sales".- * (Optional) A chart to show earnings over time.--3. **Fetch Earnings Data:**- * In `src/dashboard-earnings.js`, make a request to a new API endpoint (to be created in the next prompt) that returns the creator's earnings data.- * Use the fetched data to populate the UI elements.--4. **Structure the "Recent Sales" Table:**- * The table should display information for each purchase of the creator's skills.- * Columns should include: Skill Name, Agent Name, Date, Price, and Status.--## HTML Example (`dashboard/earnings.html`)--```html-<!-- Main content area -->-<div class="dashboard-content">- <h2>Earnings</h2>-- <div class="stats-cards">- <div class="card">- <h4>Total Revenue</h4>- <p id="total-revenue">$0.00</p>- </div>- <div class="card">- <h4>Withdrawable Balance</h4>- <p id="withdrawable-balance">$0.00</p>- <button class="btn-secondary">Withdraw</button>- </div>- </div>-- <h3>Recent Sales</h3>- <table id="sales-table">- <thead>- <tr>- <th>Date</th>- <th>Skill</th>- <th>Agent</th>- <th>Price</th>- <th>Status</th>- </tr>- </thead>- <tbody>- <!-- Rows will be inserted by JS -->- </tbody>- </table>-</div>--<script src="/src/dashboard-earnings.js" type="module"></script>-```diff --git a/docs/monetization-prompts/10-creator-payout-logic.md b/docs/monetization-prompts/10-creator-payout-logic.mddeleted file mode 100644index a9f2ee30e..000000000--- a/docs/monetization-prompts/10-creator-payout-logic.md+++ /dev/null@@ -1,68 +0,0 @@-# Prompt 10: Logic for Creator Payouts and Platform Fees--**Status:** - [ ] Not Started--## Objective-Implement the logic, both on-chain and off-chain, for splitting payments between the agent creator and the platform.--## Explanation-To create a sustainable business model, the platform will likely take a small fee from each skill purchase. This requires a system to automatically split the incoming funds. This can be done either on-chain with a smart contract or off-chain by having payments go to a platform wallet which then distributes the funds. An on-chain approach is more transparent.--## Instructions-1. **Design the Payout Flow:**- * Decide on the fee structure (e.g., a 5% platform fee).- * Decide on the mechanism:- * **On-chain (preferred):** A smart contract (or a simple wallet acting as an escrow) receives the payment, then immediately splits it between the creator and the platform treasury.- * **Off-chain:** Payment goes to a platform-controlled wallet. A backend process then periodically calculates and sends the creator's share to their wallet.--2. **Implement On-Chain Split (if chosen):**- * This is a more advanced task involving Solana smart contract development (e.g., using Anchor).- * The frontend transaction would change to call this new smart contract instead of a direct SPL transfer.- * The smart contract would require two instructions in the transaction: one to transfer the total amount to the contract, and another to trigger the split.--3. **Implement Off-Chain Split (simpler alternative):**- * Modify the SPL transfer logic from Prompt 5. Instead of transferring to the creator's address, transfer to a platform-owned treasury address. This address should be configured per-skill or per-agent in the `agent_skill_prices` table.- * Create a backend cron job or batch process (`/api/cron/process-payouts.js`).- * This job runs periodically (e.g., daily), queries all purchase records since the last run, calculates the creator's share for each, and queues up the payout transactions.- * Use a secure backend wallet to sign and send these payout transactions.--## Code Example (Off-chain Payout Cron Job - `/api/cron/process-payouts.js`)--```javascript-// This is a conceptual example of a cron job for Vercel-import { getDB } from './_lib/db';-import { Connection, Keypair, SystemProgram, Transaction } from '@solana/web3.js';-// And SPL token transfer functions--const PLATFORM_FEE_PERCENT = 5;--export default async function handler(req, res) {- // Secure this endpoint, e.g., with a secret key-- const db = getDB();- const pendingPurchases = await db.getUnprocessedPurchases();-- const creatorPayouts = {}; // { [creator_address]: amount_to_pay }-- for (const purchase of pendingPurchases) {- const creatorShare = purchase.amount * (1 - PLATFORM_FEE_PERCENT / 100);- const creator = purchase.creator_address;- creatorPayouts[creator] = (creatorPayouts[creator] || 0) + creatorShare;- }-- // Use a secure way to load your backend wallet- const platformWallet = Keypair.fromSecretKey(...);- const connection = new Connection('your_rpc_url');-- for (const [creator, amount] of Object.entries(creatorPayouts)) {- // Construct and send transaction to pay out `amount` to `creator`- // This involves creating and sending an SPL token transfer from the platform's wallet- // ...- }-- // Mark purchases as processed in the DB- await db.markPurchasesAsProcessed(pendingPurchases.map(p => p.id));-- res.status(200).json({ success: true, message: 'Payouts processed.' });-}-```diff --git a/docs/monetization-prompts/10-record-skill-ownership.md b/docs/monetization-prompts/10-record-skill-ownership.mddeleted file mode 100644index d3ef9cbe2..000000000--- a/docs/monetization-prompts/10-record-skill-ownership.md+++ /dev/null@@ -1,66 +0,0 @@-----status: not-started------# Prompt 10: Record Skill Ownership in Database--## Objective-Create the database schema and logic to record that a user has successfully purchased and unlocked a skill.--## Explanation-After a transaction is successfully verified, the final step on the backend is to persist the user's ownership of the skill. This record will be the source of truth for all future checks, such as gating skill usage and updating the marketplace UI.--## Instructions-- [ ] **Design and Create a New Database Table:**- - [ ] Create a new table named `unlocked_skills` (or similar).- - [ ] It should contain, at a minimum, the following columns:- - [ ] `id` (Primary Key)- - [ ] `user_id` (Foreign Key to your `users` table)- - [ ] `agent_id` (Foreign Key to your `agents` table)- - [ ] `skill_name` (String)- - [ ] `purchase_transaction_signature` (String, for auditing)- - [ ] `created_at` (Timestamp)- - [ ] Consider adding a unique constraint on `(user_id, agent_id, skill_name)` to prevent duplicate entries.--- [ ] **Implement the Database Insertion Logic:**- - [ ] In your backend verification endpoint (`/api/skills/purchase/verify`), after all the checks have passed, add the code to insert a new row into the `unlocked_skills` table.- - [ ] Pass the authenticated user's ID, the agent ID, the skill name, and the transaction signature to the database query.--- [ ] **Update Agent Details API to Include Ownership:**- - [ ] Modify the main API that fetches agent details for the marketplace (`/api/marketplace/agents/:id`).- - [ ] When a user requests this endpoint, it should now also query the `unlocked_skills` table to see which skills that specific user owns for that agent.- - [ ] Include this ownership information in the API response, perhaps as an array of skill names: `unlocked_skills: ["skill1", "skill2"]`.--- [ ] **Update Frontend to Use Ownership Data:**- - [ ] In `src/marketplace.js`, when you receive the agent details, use the new `unlocked_skills` array.- - [ ] In your skill rendering loop, set the `isOwned` variable based on whether the current skill's name is in this array. This will now correctly show the "Purchase" or "Unlocked" button.--## SQL Schema Example--```sql-CREATE TABLE unlocked_skills (- id SERIAL PRIMARY KEY,- user_id INTEGER NOT NULL REFERENCES users(id),- agent_id INTEGER NOT NULL REFERENCES agents(id),- skill_name VARCHAR(255) NOT NULL,- purchase_transaction_signature VARCHAR(128) NOT NULL UNIQUE,- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- UNIQUE (user_id, agent_id, skill_name)-);-```--## Frontend Code Example (`src/marketplace.js`)--```javascript-// Inside renderDetail function, after fetching agent 'a'-const unlockedSkills = a.unlocked_skills || [];--// Inside the skillsArr.map loop-const name = s.name || '';-const price = a.skill_prices[name];--if (price) {- const isOwned = unlockedSkills.includes(name); // <-- This is the new logic- // ... rest of the button rendering logic-}-```diff --git a/docs/monetization-prompts/11-api-creator-earnings.md b/docs/monetization-prompts/11-api-creator-earnings.mddeleted file mode 100644index 14782cd21..000000000--- a/docs/monetization-prompts/11-api-creator-earnings.md+++ /dev/null@@ -1,75 +0,0 @@-# Prompt 11: API Endpoint for Creator Earnings Data--## Objective-Create a secure API endpoint that calculates and returns a creator's earnings data for their dashboard.--## Explanation-The creator dashboard needs data to display. This endpoint will query the database to aggregate sales data for the currently authenticated user, providing them with their total revenue, balance, and a list of recent transactions.--## Instructions-1. **Create the API Endpoint File:**- * Create a new file, e.g., `api/dashboard/earnings.js`.--2. **Implement the Endpoint Logic:**- * **Authentication:** Get the current user via `getSessionUser`.- * **Query for Total Revenue:**- * Write a SQL query that `SUM`s the `amount` from `user_skill_purchases` where the `creator_id` matches the current user and the `status` is `'confirmed'`.- * **Query for Recent Transactions:**- * Write a SQL query that fetches the last 50-100 confirmed purchases for the creator.- * Join with `agent_identities` and `agent_skill_prices` to get agent names, skill names, and prices.- * **Calculate Withdrawable Balance:**- * For now, this can be the same as total revenue. In a future prompt, this will be adjusted for payouts.- * **Return Data:** Combine all the data into a single JSON response.--## SQL Query Example--```sql--- Query to get recent sales for a specific creator-SELECT- p.created_at,- p.skill_id,- a.name as agent_name,- pr.amount,- pr.currency_mint,- p.status-FROM- user_skill_purchases p-JOIN- agent_skill_prices pr ON p.price_id = pr.id-JOIN- agent_identities a ON p.agent_id = a.id-WHERE- pr.creator_id = $1 -- creator's user_id- AND p.status = 'confirmed'-ORDER BY- p.created_at DESC-LIMIT 50;-```--## Code Example (`api/dashboard/earnings.js`)--```javascript-import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { error, json, wrap } from '../_lib/http.js';--export default wrap(async (req, res) => {- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized');-- const [total] = await sql`- SELECT SUM(pr.amount) as total_revenue- FROM user_skill_purchases p- JOIN agent_skill_prices pr ON p.price_id = pr.id- WHERE pr.creator_id = ${user.id} AND p.status = 'confirmed'- `;-- const sales = await sql` /* ... Use the SQL query from above ... */ `;-- return json(res, {- totalRevenue: total.total_revenue || 0,- withdrawableBalance: total.total_revenue || 0, // Placeholder for now- recentSales: sales,- });-});-```diff --git a/docs/monetization-prompts/11-api-security-for-purchase.md b/docs/monetization-prompts/11-api-security-for-purchase.mddeleted file mode 100644index 684c0ea9c..000000000--- a/docs/monetization-prompts/11-api-security-for-purchase.md+++ /dev/null@@ -1,74 +0,0 @@-----status: not-started------# Prompt 11: API Security for Purchase Flow--## Objective-Implement essential security measures, including user authentication and input validation, for all monetization-related API endpoints.--## Explanation-Monetization APIs handle real money and user entitlements, making them a prime target for abuse. It's critical to ensure that only authenticated users can make purchases for themselves and that all incoming data is sanitized and validated to prevent exploits.--## Instructions-- [ ] **Implement User Authentication Middleware:**- - [ ] Ensure all monetization endpoints (`/api/transactions/*`, `/api/skills/purchase/*`) are protected by an authentication middleware.- - [ ] This middleware should verify the user's session (e.g., via a JWT token, session cookie, or API key).- - [ ] If the user is not authenticated, the request should be rejected with a `401 Unauthorized` error.- - [ ] The authenticated user's data (especially `user_id` and `publicKey`) should be attached to the request object for later use.--- [ ] **Enforce Authorization:**- - [ ] A user should only be able to purchase skills for their own account. The `user_id` used when recording skill ownership should come from the secure session, *not* from the request body.--- [ ] **Implement Input Validation:**- - [ ] For every monetization endpoint, validate the request body.- - [ ] Use a library like `zod`, `joi`, or a simple custom validation function.- - [ ] **Checks for `/api/transactions/create-skill-purchase`:**- - [ ] `agentId`: should be a valid ID format.- - [ ] `skillName`: should be a non-empty string.- - [ ] `buyerPublicKey`: should be a valid Solana public key format.- - [ ] **Checks for `/api/skills/purchase/verify`:**- - [ ] `transactionSignature`: should be a valid Solana transaction signature format.- - [ ] `agentId` and `skillName`: same as above.- - [ ] If validation fails, return a `400 Bad Request` error with a clear message indicating the invalid field.--## Code Example (Express.js-style Middleware)--```javascript-// middleware/auth.js-export function requireAuth(req, res, next) {- // Logic to verify session token (e.g., from Authorization header)- const user = verifyToken(req.headers.authorization);-- if (!user) {- return res.status(401).json({ message: "Authentication required." });- }- req.user = user; // Attach user to the request- next();-}--// api/skills/purchase/verify.js-import { requireAuth } from 'middleware/auth';-import { z } from 'zod';--const purchaseSchema = z.object({- transactionSignature: z.string().min(80).max(100), // Basic validation- agentId: z.number().int(),- skillName: z.string().min(1),-});--// Apply middleware and validation-export default async function handler(req, res) {- requireAuth(req, res, () => {- const validation = purchaseSchema.safeParse(req.body);- if (!validation.success) {- return res.status(400).json({ message: "Invalid input", errors: validation.error.issues });- }-- // --- Main endpoint logic ---- // Use req.user.id instead of any user ID from the body- const userId = req.user.id;- // ...- });-}-```diff --git a/docs/monetization-prompts/11-user-purchased-skills.md b/docs/monetization-prompts/11-user-purchased-skills.mddeleted file mode 100644index e9b520bf3..000000000--- a/docs/monetization-prompts/11-user-purchased-skills.md+++ /dev/null@@ -1,93 +0,0 @@-# Prompt 11: Display User's Purchased Skills in Profile--**Status:** - [ ] Not Started--## Objective-Create a section in the user's profile or dashboard page (`profile.html` or a new dashboard page) where they can see all the agent skills they have purchased.--## Explanation-Users need a centralized place to view their digital assets. This enhances the sense of ownership and provides a useful overview of their collection of skills.--## Instructions-1. **Create a Backend Endpoint:**- * Develop an API endpoint, e.g., `/api/users/me/purchased-skills`.- * This endpoint should be authenticated.- * It should query the `user_agent_skills` table for all records matching the logged-in user's ID.- * To make the output more useful, it should join with the `agents` table to include details about the agent for each skill (e.g., agent name and image).- * The endpoint should return an array of objects, each containing skill name, agent details, and purchase date.--2. **Develop the Frontend UI:**- * On the user's profile page (`profile.html`), add a new tab or section for "My Purchased Skills".- * When the page loads (or this section is viewed), make a request to the new API endpoint.- * Render the list of purchased skills. Each item in the list should display:- * The skill name.- * The name of the agent it belongs to (and maybe a thumbnail).- * The date of purchase.- * A link to the agent's detail page in the marketplace.--## Code Example (Backend - `/api/users/me/purchased-skills.js`)--```javascript-import { getDB } from './_lib/db';--export default async function handler(req, res) {- // Assume user is authenticated- const userId = req.user.id;-- const db = getDB();- try {- // This query would join user_agent_skills with agents table- const skills = await db.query(- `SELECT uas.skill_name, uas.created_at, a.name as agent_name, a.slug as agent_slug, a.thumbnail_url as agent_thumbnail- FROM user_agent_skills uas- JOIN agents a ON uas.agent_id = a.id- WHERE uas.user_id = $1- ORDER BY uas.created_at DESC`,- [userId]- );-- res.status(200).json({ skills });- } catch (error) {- console.error('Failed to fetch purchased skills:', error);- res.status(500).json({ error: 'Failed to fetch skills.' });- }-}-```--## Code Example (JavaScript for `profile.html`)--```javascript-async function loadPurchasedSkills() {- const container = $('purchased-skills-list');- container.innerHTML = 'Loading...';-- try {- const response = await fetch('/api/users/me/purchased-skills');- if (!response.ok) throw new Error('Failed to load skills');-- const { skills } = await response.json();-- if (!skills.length) {- container.innerHTML = 'You have not purchased any skills yet.';- return;- }-- container.innerHTML = skills.map(skill => `- <div class="skill-item">- <img src="${skill.agent_thumbnail || '/placeholder.png'}" alt="${skill.agent_name}" class="agent-thumb">- <div>- <div class="skill-name">${skill.skill_name}</div>- <div class="agent-name">for <a href="/marketplace/${skill.agent_slug}">${skill.agent_name}</a></div>- <div class="purchase-date">Purchased on ${new Date(skill.created_at).toLocaleDateString()}</div>- </div>- </div>- `).join('');-- } catch (error) {- container.innerHTML = 'Error loading your skills.';- }-}--// Call this function when the page loads-loadPurchasedSkills();-```diff --git a/docs/monetization-prompts/12-backend-gate-skill-usage.md b/docs/monetization-prompts/12-backend-gate-skill-usage.mddeleted file mode 100644index 7567c9834..000000000--- a/docs/monetization-prompts/12-backend-gate-skill-usage.md+++ /dev/null@@ -1,58 +0,0 @@-# Prompt 12: Backend Logic to Gate Skill Usage--## Objective-Modify the agent's skill execution logic to check if a user is licensed to use a paid skill before running it.--## Explanation-Selling skills is only effective if their usage can be restricted to paying users. This requires adding a check in the agent's core runtime. Before executing any skill, the runtime must determine if the skill is priced and, if so, whether the current user has purchased it.--## Instructions-1. **Locate the Skill Execution Logic:**- * Find the part of the agent runtime where skills are called. This is likely in `src/runtime/index.js` or a related file that handles the LLM tool-loop.--2. **Add a Pre-Execution Check:**- * Before a skill's handler is invoked, insert a new check.- * **Is the skill priced?** Query the `agent_skill_prices` table for the current agent and the skill being called.- * **If it is priced, does the user have a license?**- * Get the current user's ID. Note: You'll need to pass user context into the runtime.- * Query the `user_skill_purchases` table to see if a `'confirmed'` purchase record exists for this `user_id`, `agent_id`, and `skill_id`.- * **Enforce the Gate:**- * If the skill is priced and the user has *not* purchased it, do not execute the skill.- * Instead, return a specific error message to the LLM (e.g., `tool_error: "User has not purchased this skill."`).--3. **Instruct the LLM on How to Respond:**- * Update the system prompt (e.g., in `api/chat.js`) to instruct the agent on what to do when it receives this specific error.- * It should inform the user that the skill is a premium feature and they need to purchase it to use it.--## Code Example (Conceptual - in agent runtime)--```javascript-// Before calling a skill's handler function...--async function canUseSkill(userId, agentId, skillId) {- // This check would be done via an API call from the client, or directly if on the server.- const isPriced = await db.checkIfSkillIsPriced(agentId, skillId);- if (!isPriced) {- return true; // Free skill, allow usage.- }-- if (!userId) {- return false; // Priced skill, but user is not logged in.- }-- const hasPurchased = await db.checkIfUserHasPurchased(userId, agentId, skillId);- return hasPurchased;-}--// In the tool-loop-const allowed = await canUseSkill(currentUser.id, agent.id, toolCall.name);-if (allowed) {- // Execute tool-} else {- // Return error to LLM- return {- tool_use_id: toolCall.id,- content: JSON.stringify({ error: "User has not purchased this skill." }),- };-}-```diff --git a/docs/monetization-prompts/12-creator-payout-setup.md b/docs/monetization-prompts/12-creator-payout-setup.mddeleted file mode 100644index b1a8a550d..000000000--- a/docs/monetization-prompts/12-creator-payout-setup.md+++ /dev/null@@ -1,59 +0,0 @@-----status: not-started------# Prompt 12: Creator Payout Wallet Setup--## Objective-Allow agent creators to specify and save a Solana wallet address for receiving payments.--## Explanation-To pay creators, we need to know where to send the funds. This involves adding a field to the database for their payout address and creating a UI and API for them to manage this setting.--## Instructions-- [ ] **Update Database Schema:**- - [ ] Add a new column to your `users` table (or whichever table represents your creators).- - [ ] The column should be named `payout_wallet_address` or similar.- - [ ] It should be a `VARCHAR` or `TEXT` field, capable of storing a Solana public key (e.g., up to 44 characters). It can be nullable, as a user might not be a creator.--- [ ] **Create API Endpoint for Saving Wallet Address:**- - [ ] Create a new API endpoint, e.g., `PUT /api/users/payout-settings`.- - [ ] This endpoint should be protected by authentication middleware.- - [ ] It will accept a new `payout_wallet_address` in the request body.- - [ ] Validate that the provided string is a valid Solana public key.- - [ ] Update the `payout_wallet_address` for the authenticated user in the database.--- [ ] **Update "Create Transaction" Endpoint:**- - [ ] Modify the `POST /api/transactions/create-skill-purchase` endpoint.- - [ ] When fetching creator details, retrieve the new `payout_wallet_address`.- - [ ] Use this address as the destination for the payment transfer in the Solana transaction. If the address is not set, the transaction should fail with an error indicating the creator has not configured their payouts.--## SQL Schema Example (Alter Table)--```sql-ALTER TABLE users-ADD COLUMN payout_wallet_address VARCHAR(44) NULL;-```--## API Validation Example (Node.js)--```javascript-import { PublicKey } from '@solana/web3.js';--function isValidSolanaAddress(address) {- try {- new PublicKey(address);- return true;- } catch (e) {- return false;- }-}--// In your PUT /api/users/payout-settings endpoint-const { payout_wallet_address } = req.body;-if (!isValidSolanaAddress(payout_wallet_address)) {- return res.status(400).json({ message: "Invalid Solana wallet address." });-}--// ... proceed to update database for req.user.id-```diff --git a/docs/monetization-prompts/12-on-chain-receipts-as-nfts.md b/docs/monetization-prompts/12-on-chain-receipts-as-nfts.mddeleted file mode 100644index 2455cb569..000000000--- a/docs/monetization-prompts/12-on-chain-receipts-as-nfts.md+++ /dev/null@@ -1,77 +0,0 @@-# Prompt 12: Generate On-Chain Receipts as NFTs--**Status:** - [ ] Not Started--## Objective-Issue a unique, non-transferable NFT to the user upon a successful skill purchase, serving as an on-chain receipt and proof of ownership.--## Explanation-Using NFTs as receipts provides a permanent, verifiable, and user-owned record of their purchase on the blockchain. This can unlock future possibilities like community-gated access or special privileges for skill owners. We can use a service like Metaplex for this.--## Instructions-1. **Set up NFT Minting Infrastructure:**- * This is a significant step. You can use Metaplex's Candy Machine or their newer Core standards. For simple receipts, a direct mint via the Metaplex Umi library might be sufficient.- * You'll need a backend wallet with SOL to pay for minting fees.--2. **Modify the Purchase Verification Endpoint:**- * In `/api/marketplace/purchase-skill.js`, after successfully verifying the transaction and recording the purchase in the database, trigger the NFT minting process.- * The metadata for the NFT should include:- * Name: e.g., "Skill Receipt: 'sentiment-analysis'"- * Symbol: e.g., "3WS-SKILL"- * Description: "This NFT represents ownership of the 'sentiment-analysis' skill for the agent 'AI Market Analyst'."- * Attributes: Agent Name, Skill Name, Purchase Date.- * Image: A custom image for skill receipts, or maybe the agent's thumbnail.--3. **Mint and Send the NFT:**- * The backend will construct and sign the transaction to create the mint account, create the token account for the user, and mint the NFT to that account.- * The NFT should ideally be non-transferable to act as a "soul-bound" token representing access, not a speculative asset. This can be set with Metaplex's standards.--4. **Update Database Record:**- * After minting, store the NFT's mint address in the `user_agent_skills` table. This links the off-chain record to the on-chain asset.--## Code Example (Conceptual Backend - adding to `purchase-skill.js`)--```javascript-import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';-import { mplCore, createV1, mintV1 } from '@metaplex-foundation/mpl-core';-import { keypairIdentity, Pda } from '@metaplex-foundation/umi';--// After successfully recording purchase in DB...-async function mintReceiptNFT(userAddress, agent, skillName) {- const umi = createUmi('your_rpc_url').use(mplCore());-- // Use a secure way to load your backend/minter wallet- const minterKeypair = ...;- umi.use(keypairIdentity(minterKeypair));-- const newMint = Pda.find(umi.context, 'core-mint', [minterKeypair.publicKey, 0]);-- await createV1(umi, {- mint: newMint,- name: `Skill: ${skillName}`,- uri: `https://your-api.com/api/nft-metadata/${agent.id}/${skillName}`,- plugins: [- // This is conceptual - the exact non-transferable implementation- // depends on the Metaplex standard you choose (e.g., locking delegates).- ]- }).sendAndConfirm(umi);-- await mintV1(umi, {- mint: newMint.publicKey,- authority: minterKeypair,- assetOwner: new PublicKey(userAddress),- }).sendAndConfirm(umi);-- return newMint.publicKey;-}--// In the main handler:-if (verificationSuccess) {- await db.recordSkillPurchase(userId, agentId, skillName);- const nftMintAddress = await mintReceiptNFT(userWalletAddress, agent, skillName);- await db.updatePurchaseWithNftAddress(purchaseId, nftMintAddress);-- return res.status(200).json({ success: true, message: 'Purchase successful!', receiptNft: nftMintAddress });-}-```-*Note: This is a highly simplified example. NFT minting with Metaplex requires careful setup and handling of accounts and authorities.*diff --git a/docs/monetization-prompts/13-allow-free-skills.md b/docs/monetization-prompts/13-allow-free-skills.mddeleted file mode 100644index f184f6036..000000000--- a/docs/monetization-prompts/13-allow-free-skills.md+++ /dev/null@@ -1,86 +0,0 @@-# Prompt 13: Allow Creators to List Skills for Free--**Status:** - [ ] Not Started--## Objective-Enhance the skill monetization interface to allow creators to explicitly list a skill as "Free" or remove its price, making it available to all users without a purchase.--## Explanation-Not all skills should require payment. Creators may want to offer some skills for free as a preview or for community-building. The system needs to support toggling a skill between a paid and free state.--## Instructions-1. **Update the UI for Price Management:**- * In the "Skill Monetization" section of `agent-edit.html`, for each skill, add a "Make Free" or "Remove Price" button next to the pricing inputs.- * If a skill currently has a price, this button should be active. If it's already free, the button can be disabled or hidden.- * The UI should visually indicate that a skill is free (e.g., by displaying "Free" instead of price inputs).--2. **Create a Backend Endpoint for Removing Prices:**- * Create a new API endpoint, e.g., `api/agents/remove-skill-price.js`.- * This endpoint must be authenticated and verify that the user is the agent's creator.- * It should accept `agentId` and `skillName`.- * The handler will `DELETE` the corresponding record from the `agent_skill_prices` table.--3. **Connect Frontend to Backend:**- * In the JavaScript for the agent edit page, add an event listener for the "Remove Price" button.- * When clicked, it should call the new `DELETE` endpoint.- * On success, update the UI for that skill to show it as free and clear the price input fields.--## Code Example (JavaScript for `agent-edit.html`)--```javascript-// Inside the event listener for the skill pricing list-$('skill-pricing-list').addEventListener('click', async (e) => {- // ... (handle 'set-price-btn' clicks)-- if (e.target.classList.contains('remove-price-btn')) {- const skillName = e.target.dataset.skillName;-- // Optional: Ask for confirmation- if (!confirm(`Are you sure you want to make the skill "${skillName}" free?`)) {- return;- }-- const response = await fetch('/api/agents/remove-skill-price', {- method: 'POST', // Or DELETE, depending on your API design- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- agentId: currentAgentId,- skillName,- }),- });-- if (response.ok) {- showToast('Skill is now free!', 'success');- // Re-render the pricing section to reflect the change- // Or dynamically update the specific row- const priceInput = document.querySelector(`input[data-skill-name="${skillName}"]`);- priceInput.value = '';- } else {- showToast('Failed to update skill.', 'error');- }- }-});-```--## Code Example (Backend - `api/agents/remove-skill-price.js`)--```javascript-import { getDB } from './_lib/db';--export default async function handler(req, res) {- // Assume user is authenticated and is the agent owner- const { agentId, skillName } = req.body;-- const db = getDB();- try {- await db.query(- 'DELETE FROM agent_skill_prices WHERE agent_id = $1 AND skill_name = $2',- [agentId, skillName]- );- res.status(200).json({ success: true, message: 'Skill price removed.' });- } catch (error) {- console.error('Failed to remove skill price:', error);- res.status(500).json({ error: 'Failed to update skill.' });- }-}-```diff --git a/docs/monetization-prompts/13-frontend-buy-skill-button.md b/docs/monetization-prompts/13-frontend-buy-skill-button.mddeleted file mode 100644index 920850e05..000000000--- a/docs/monetization-prompts/13-frontend-buy-skill-button.md+++ /dev/null@@ -1,53 +0,0 @@-# Prompt 13: "Buy Skill" Button on Agent Detail Page--## Objective-Add a "Buy" or "Unlock" button next to paid skills on the agent detail page in the marketplace.--## Explanation-Following Prompt 01 where we displayed the price, we now need to add a call-to-action button. This button will be the entry point for the user to initiate the purchase flow. It should only appear for skills that have a price and that the current user has not yet purchased.--## Instructions-1. **Fetch User's Purchased Skills:**- * The backend endpoint for the agent detail page (`/api/marketplace/agents/:id`) needs to know the current user to determine which skills they own.- * If a user is logged in, fetch their purchase history for the current agent from `user_skill_purchases`.- * Add a new field to the agent detail response, e.g., `owned_skills: ["skill_name1", "skill_name2"]`.--2. **Update Frontend Skill Rendering:**- * In `src/marketplace.js`, within the `renderDetail` function's skill-rendering loop:- * Check if the current skill is in the `owned_skills` array.- * Check if the skill has a price in the `skill_prices` object.- * **Conditional Rendering Logic:**- * If `price` exists AND the skill is NOT in `owned_skills`: Render a "Buy" button.- * If `price` exists AND the skill IS in `owned_skills`: Render an "Owned" badge or checkmark.- * If `price` does not exist: Render the "Free" badge.--3. **Add Event Listener:**- * Attach a click event listener to the "Buy" button.- * The listener should call the `onBuySkill(agentId, skillId)` function created in Prompt 06, which kicks off the purchase modal and QR code generation.--## Code Example (`src/marketplace.js`)--```javascript-// Inside renderDetail function--const skillPrices = a.skill_prices || {};-const ownedSkills = new Set(a.owned_skills || []);--$('d-skills').innerHTML = skillsArr.map((s) => {- const name = s.name || '';- const price = skillPrices[name];- let badge = '';-- if (price) {- if (ownedSkills.has(name)) {- badge = `<span class="badge owned">✓ Owned</span>`;- } else {- const priceStr = `${(price.amount / 1e6).toFixed(2)} USDC`;- badge = `<button class="btn-buy" data-agent-id="${a.id}" data-skill-id="${name}">Buy for ${priceStr}</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-prompts/13-platform-fee-logic.md b/docs/monetization-prompts/13-platform-fee-logic.mddeleted file mode 100644index 53d0297ee..000000000--- a/docs/monetization-prompts/13-platform-fee-logic.md+++ /dev/null@@ -1,70 +0,0 @@-----status: not-started------# Prompt 13: Platform Fee Logic--## Objective-Implement the logic to automatically take a platform fee from each skill purchase transaction.--## Explanation-A platform fee is a common monetization strategy. This involves splitting the payment from the buyer into two parts: one for the creator and one for the platform. This logic should be handled securely on the backend when the transaction is created.--## Instructions-- [ ] **Configure Platform Wallet:**- - [ ] Store the platform's fee-collecting wallet address in a secure configuration file or environment variable on your backend. Do not hardcode it in the API logic.--- [ ] **Define Platform Fee Rate:**- - [ ] Define the platform's fee percentage (e.g., `5%` or `0.05`) in the same configuration.--- [ ] **Update the "Create Transaction" Endpoint:**- - [ ] In your `POST /api/transactions/create-skill-purchase` endpoint:- - [ ] After fetching the skill price, calculate the fee amount (e.g., `feeAmount = price * platformFeeRate`).- - [ ] Calculate the creator's proceeds (`creatorAmount = price - feeAmount`). Ensure you are working with integers to avoid floating-point issues.- - [ ] Add a **second** SPL Token Transfer instruction to the Solana transaction.- - [ ] The first instruction will transfer `creatorAmount` from the buyer to the creator.- - [ ] The second instruction will transfer `feeAmount` from the buyer to the platform's wallet.- - [ ] The transaction will now contain two separate transfer instructions. The Solana runtime will execute them atomically.--- [ ] **Update the "Verify Transaction" Endpoint:**- - [ ] Your verification logic at `POST /api/skills/purchase/verify` must also be updated.- - [ ] It should now look for **two** transfer instructions in the fetched transaction.- - [ ] It must verify that both transfers are correct: the right amount to the right creator, and the right fee amount to the right platform wallet. Verification fails if either is incorrect.--## Code Example (Create Transaction Endpoint with Fee)--```javascript-// ... inside /api/transactions/create-skill-purchase--const PLATFORM_FEE_RATE = 0.05; // 5%-const PLATFORM_WALLET = new PublicKey(process.env.PLATFORM_WALLET_ADDRESS);--const price = priceInfo.amount;-const feeAmount = Math.round(price * PLATFORM_FEE_RATE);-const creatorAmount = price - feeAmount;--// ... get buyerUsdcAccount, creatorUsdcAccount, etc.-const platformUsdcAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, usdcMint, PLATFORM_WALLET);--const transaction = new Transaction()- .add(- // Instruction 1: Payment to Creator- createTransferInstruction(- buyerUsdcAccount.address,- creatorUsdcAccount.address,- buyer,- creatorAmount- )- )- .add(- // Instruction 2: Fee to Platform- createTransferInstruction(- buyerUsdcAccount.address,- platformUsdcAccount.address,- buyer,- feeAmount- )- );--// ... set feePayer, blockhash, and serialize-```diff --git a/docs/monetization-prompts/14-creator-dashboard-backend.md b/docs/monetization-prompts/14-creator-dashboard-backend.mddeleted file mode 100644index bc2c581b5..000000000--- a/docs/monetization-prompts/14-creator-dashboard-backend.md+++ /dev/null@@ -1,61 +0,0 @@-----status: not-started------# Prompt 14: Creator Dashboard - Backend--## Objective-Create the backend API endpoints required to power a dashboard for creators to track their sales and earnings.--## Explanation-To empower creators, we need to give them visibility into their performance. This involves creating secure, read-only endpoints that aggregate sales data from the database.--## Instructions-- [ ] **Design API Endpoints:**- - [ ] Plan a few key endpoints for the creator dashboard. For example:- - [ ] `GET /api/creator/dashboard/stats`: Returns key stats like total revenue, total sales, and average sale price.- - [ ] `GET /api/creator/dashboard/sales-history`: Returns a paginated list of individual sales, including skill name, date, and amount earned.- - [ ] `GET /api/creator/dashboard/sales-by-skill`: Returns an aggregate of sales grouped by skill name.--- [ ] **Implement `stats` Endpoint:**- - [ ] This endpoint should be protected by authentication.- - [ ] It needs to query your transaction or unlocked skills database.- - [ ] To get total revenue, you'll need to join your `unlocked_skills` table with `agent_skill_prices` and filter by the agents owned by the current user (`req.user.id`).- - [ ] Sum the prices of all skills sold. Remember to subtract the platform fee from the creator's view of revenue.- - [ ] Return the aggregated data as a JSON object.--- [ ] **Implement `sales-history` Endpoint:**- - [ ] This endpoint will also perform a join similar to the stats endpoint.- - [ ] Instead of aggregating, it will return a list of individual sales records.- - [ ] Implement pagination using `LIMIT` and `OFFSET` in your SQL query (or the equivalent in your ORM) to handle potentially large numbers of sales.- - [ ] Return the list and pagination metadata (e.g., `total_pages`, `current_page`).--## Database Query Example (PostgreSQL for Stats)--```sql--- This query calculates total revenue and sales for a specific creator (user_id = $1)-SELECT- -- Sum of prices, adjusted for platform fee (e.g., 5%)- SUM(prices.amount * (1 - 0.05)) AS total_revenue,- COUNT(unlocked.id) AS total_sales-FROM- unlocked_skills AS unlocked-JOIN- agents ON unlocked.agent_id = agents.id-JOIN- agent_skill_prices AS prices ON unlocked.agent_id = prices.agent_id AND unlocked.skill_name = prices.skill_name-WHERE- -- Filter for sales of agents owned by the logged-in creator- agents.creator_id = $1;-```--## API Response Example (`/stats`)--```json-{- "totalRevenue": 85500000,- "totalSales": 92,- "topSellingSkill": "AdvancedDataAnalysis",- "currency": "USDC"-}-```diff --git a/docs/monetization-prompts/14-frontend-ui-update-post-purchase.md b/docs/monetization-prompts/14-frontend-ui-update-post-purchase.mddeleted file mode 100644index 689bffa24..000000000--- a/docs/monetization-prompts/14-frontend-ui-update-post-purchase.md+++ /dev/null@@ -1,59 +0,0 @@-# Prompt 14: UI Update After Successful Purchase--## Objective-After a skill purchase is successfully confirmed, dynamically update the agent detail UI to reflect the user's new ownership status without requiring a page reload.--## Explanation-A seamless user experience requires immediate feedback. Once the frontend polling (from Prompt 09) confirms a successful purchase, the UI should change instantly. The "Buy" button for the skill should be replaced with an "Owned" indicator, and any related UI elements should be updated.--## Instructions-1. **Identify the Skill Element:**- * Ensure the HTML element for each skill in the list has a unique and predictable ID or class that includes the skill name, e.g., `<span class="skill-entry" id="skill-entry-weather-forecast">...</span>`.--2. **Modify the Polling Success Callback:**- * In `src/marketplace.js`, locate the success block within the purchase confirmation polling loop (`if (status === 'confirmed')`).- * When a purchase is confirmed, you will have the `agentId` and `skillId`.- * **Find the UI Element:** Use the `skillId` to select the specific skill's UI element in the DOM.- * **Replace the Button:** Find the "Buy" button within that element and replace it with the "Owned" badge HTML.- * For example: `<span class="badge owned">✓ Owned</span>`.--3. **Show a Success Notification:**- * Use a toast notification or a simple alert to explicitly tell the user their purchase was successful and they can now use the skill.--## Code Example (`src/marketplace.js`)--```javascript-// In the polling success callback, you have access to the skillId.-// Let's assume you stored it from when the "Buy" button was clicked.-const currentSkillId = 'weather-forecast'; // The skill being purchased--function onPurchaseSuccess(skillId) {- // 1. Hide the modal and stop polling (already done).-- // 2. Find the skill entry in the DOM.- const skillEntry = document.getElementById(`skill-entry-${skillId}`);- if (!skillEntry) return;-- // 3. Find the buy button within it.- const buyButton = skillEntry.querySelector('.btn-buy');-- // 4. Create and insert the "Owned" badge.- const ownedBadge = document.createElement('span');- ownedBadge.className = 'badge owned';- ownedBadge.innerHTML = '✓ Owned';-- if (buyButton) {- buyButton.replaceWith(ownedBadge);- }-- // 5. Show a success notification.- showToast('Purchase successful! You can now use the skill.');-}--// Inside the polling loop:-if (status === 'confirmed') {- clearInterval(pollingId);- $('purchase-modal').hidden = true;- onPurchaseSuccess(currentSkillId);-}-```diff --git a/docs/monetization-prompts/14-skill-gating-logic.md b/docs/monetization-prompts/14-skill-gating-logic.mddeleted file mode 100644index 0077c6ac0..000000000--- a/docs/monetization-prompts/14-skill-gating-logic.md+++ /dev/null@@ -1,77 +0,0 @@-# Prompt 14: Implement Skill Gating Logic--**Status:** - [ ] Not Started--## Objective-Enforce access control for skills, preventing users from using or executing a paid skill unless they have purchased it.--## Explanation-Skill gating is the core of the monetization feature. Once a skill is marked as paid, the system must check for ownership before allowing it to be executed. This check should happen both on the backend (for security) and frontend (for a better user experience).--## Instructions-1. **Backend Gating:**- * Identify the API endpoint that executes or "performs" a skill (e.g., `/api/agent-actions.js` or a similar handler for `perform-skill`).- * Before executing a skill, this endpoint must perform a check:- * Is the skill a paid skill for this agent? (Query `agent_skill_prices`).- * If it is paid, does the logged-in user own it? (Query `user_agent_skills`).- * If the user does not own the paid skill, return a `403 Forbidden` error with a clear message like "You must purchase this skill to use it."--2. **Frontend UI Gating:**- * The UI should visually indicate that a skill is locked if it's paid and not owned.- * For example, on the agent detail page or in a chat interface where skills can be triggered, the button or control for a locked skill should be disabled or styled differently.- * When a user tries to interact with a locked skill, the UI should guide them to purchase it (e.g., by showing a tooltip or popping up the purchase modal).--## Code Example (Backend - e.g., in `/api/agent-actions.js`)--```javascript-// Inside the handler for performing a skill-export default async function handler(req, res) {- // Assume user is authenticated- const userId = req.user.id;- const { agentId, skillName, args } = req.body;-- const db = getDB();-- // Check if the skill is priced- const skillPrice = await db.getSkillPrice(agentId, skillName);-- if (skillPrice) {- // It's a paid skill, so check for ownership- const hasOwnership = await db.checkSkillOwnership(userId, agentId, skillName);- if (!hasOwnership) {- return res.status(403).json({- error: 'Access Denied',- message: 'You must purchase this skill to use it.'- });- }- }-- // If we get here, the user has access. Proceed with skill execution.- // ... (rest of the skill execution logic)-}-```--## Code Example (Frontend UI - Conceptual)--```javascript-// When rendering a list of skill buttons for an agent to use-function renderSkillButtons(agent, purchasedSkills) {- const container = document.getElementById('agent-skill-buttons');-- container.innerHTML = agent.skills.map(skill => {- const isPaid = !!agent.skill_prices[skill.name];- const isOwned = purchasedSkills.includes(skill.name);- const isLocked = isPaid && !isOwned;-- if (isLocked) {- return `<button class="skill-btn locked" title="Purchase this skill to use it.">- ${escapeHtml(skill.name)} (Locked)- </button>`;- } else {- return `<button class="skill-btn" data-skill-name="${skill.name}">- ${escapeHtml(skill.name)}- </button>`;- }- }).join('');-}-```diff --git a/docs/monetization-prompts/15-creator-earnings-dashboard.md b/docs/monetization-prompts/15-creator-earnings-dashboard.mddeleted file mode 100644index c95b8a372..000000000--- a/docs/monetization-prompts/15-creator-earnings-dashboard.md+++ /dev/null@@ -1,84 +0,0 @@-# Prompt 15: Create a Creator Dashboard for Earnings--**Status:** - [ ] Not Started--## Objective-Develop a dashboard page for creators to track their sales and earnings from the skills they've monetized.--## Explanation-To create a healthy ecosystem, creators need visibility into how their paid skills are performing. A dedicated dashboard provides them with key metrics like total revenue, number of sales, and a breakdown of earnings per skill.--## Instructions-1. **Design the Dashboard UI:**- * Create a new page, e.g., `creator-dashboard.html`.- * This page should be accessible to logged-in users.- * Design sections for:- * **Key Metrics:** Total revenue, total sales, number of monetized skills.- * **Earnings Breakdown:** A table or list showing each monetized skill, its price, number of sales, and total revenue generated.- * **Transaction History:** A list of recent sales, including the skill, date, and amount.--2. **Create Backend Endpoints for Dashboard Data:**- * Create an endpoint `/api/creators/me/dashboard-stats`.- * This authenticated endpoint will fetch and aggregate data for the logged-in user:- * Query the `agent_skill_prices` table for all skills priced by the creator.- * For each priced skill, query the `user_agent_skills` table to count the number of sales.- * Calculate total revenue and other key metrics.- * The endpoint should return a JSON object with all the data needed to populate the dashboard.- * You might want a separate, paginated endpoint for the detailed transaction history.--3. **Connect Frontend to Backend:**- * In the JavaScript for `creator-dashboard.html`, make a request to the new dashboard endpoint when the page loads.- * Use the returned data to populate the different sections of the dashboard.- * Use a library for charts (e.g., Chart.js) to visualize earnings over time if desired.--## Code Example (Backend - `/api/creators/me/dashboard-stats.js`)--```javascript-import { getDB } from './_lib/db';--export default async function handler(req, res) {- // Assume user is authenticated and we have their user_id and wallet address- const creatorId = req.user.id;-- const db = getDB();- try {- // Get all agents owned by the creator- const creatorAgents = await db.query('SELECT id FROM agents WHERE creator_id = $1', [creatorId]);- const agentIds = creatorAgents.map(a => a.id);-- // Get all sales for those agents- const sales = await db.query(- `SELECT asp.skill_name, asp.amount, a.name as agent_name- FROM user_agent_skills uas- JOIN agent_skill_prices asp ON uas.agent_id = asp.agent_id AND uas.skill_name = asp.skill_name- JOIN agents a ON uas.agent_id = a.id- WHERE uas.agent_id = ANY($1::uuid[])`,- [agentIds]- );-- let totalRevenue = 0;- let totalSales = sales.length;- const skillBreakdown = {};-- for (const sale of sales) {- totalRevenue += parseInt(sale.amount, 10);- const key = `${sale.agent_name} - ${sale.skill_name}`;- if (!skillBreakdown[key]) {- skillBreakdown[key] = { sales: 0, revenue: 0 };- }- skillBreakdown[key].sales++;- skillBreakdown[key].revenue += parseInt(sale.amount, 10);- }-- res.status(200).json({- totalRevenue,- totalSales,- skillBreakdown,- });-- } catch (error) {- console.error('Failed to fetch dashboard stats:', error);- res.status(500).json({ error: 'Failed to fetch stats.' });- }-}-```diff --git a/docs/monetization-prompts/15-skill-pricing-management-ui.md b/docs/monetization-prompts/15-skill-pricing-management-ui.mddeleted file mode 100644index 98523de5c..000000000--- a/docs/monetization-prompts/15-skill-pricing-management-ui.md+++ /dev/null@@ -1,74 +0,0 @@-----status: not-started------# Prompt 15: Skill Pricing Management - UI--## Objective-Create a user interface on the agent creation/editing page that allows creators to set and update prices for their skills.--## Explanation-Creators need a simple and intuitive way to manage the prices of their skills. This involves adding new form elements to the page where they configure their agents.--## Instructions-- [ ] **Design the UI:**- - [ ] On the page where a creator edits their agent (e.g., `agent-edit.html`), locate the section where skills are listed or added.- - [ ] For each skill listed, add a price input field and a currency selector (for now, this can be a disabled dropdown showing "USDC").- - [ ] If a skill is meant to be free, the creator should be able to leave the price field blank or set it to 0.- - [ ] Add a "Save Prices" or "Update Agent" button to submit the changes.--- [ ] **Implement Frontend Logic:**- - [ ] When the agent edit page loads, it should fetch the agent's details, including the existing `skill_prices` map.- - [ ] Use this data to populate the price input fields for each skill.- - [ ] When the "Save" button is clicked, gather all the skill names and their new prices from the input fields.- - [ ] Structure this data into a map, e.g., `{ "skill_one": 10.50, "skill_two": 0 }`.- - [ ] Make a `PUT` request to a new backend API endpoint to save these prices.--## HTML Example (Inside an agent edit form)--```html-<div id="skill-pricing-section">- <h3>Manage Skill Prices</h3>-- <!-- This would be dynamically generated -->- <div class="skill-price-entry">- <label for="price-skill_one">Skill One</label>- <input type="number" id="price-skill_one" name="skill_prices[skill_one]" placeholder="e.g., 5.00">- <span>USDC</span>- </div>-- <div class="skill-price-entry">- <label for="price-skill_two">Skill Two</label>- <input type="number" id="price-skill_two" name="skill_prices[skill_two]" placeholder="Leave blank for Free">- <span>USDC</span>- </div>-- <button id="save-prices-btn">Save Prices</button>-</div>-```--## JavaScript Example (on Save button click)--```javascript-document.getElementById('save-prices-btn').addEventListener('click', async () => {- const prices = {};- const agentId = /* get agent ID from page */;-- document.querySelectorAll('.skill-price-entry').forEach(entry => {- const input = entry.querySelector('input[type="number"]');- const skillName = input.name.match(/\[(.*?)\]/)[1]; // Extracts "skill_one"- const price = parseFloat(input.value) || 0;-- // Convert to smallest unit (e.g., 1 USDC = 1,000,000)- prices[skillName] = price * 1e6;- });-- await fetch(`/api/agents/${agentId}/prices`, {- method: 'PUT',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ prices })- });-- // Show success message-});-```diff --git a/docs/monetization-prompts/15-user-dashboard-purchased-skills.md b/docs/monetization-prompts/15-user-dashboard-purchased-skills.mddeleted file mode 100644index 0ab6774ec..000000000--- a/docs/monetization-prompts/15-user-dashboard-purchased-skills.md+++ /dev/null@@ -1,49 +0,0 @@-# Prompt 15: User Profile Page to Show Purchased Skills--## Objective-Create a section or a new page in the user's profile/dashboard where they can see a list of all the premium skills they have purchased across all agents.--## Explanation-Users need a central place to view their entitlements. This feature adds transparency and value to their account by aggregating all their purchased skills in one place. It acts as a digital inventory of their premium agent capabilities.--## Instructions-1. **Create an API Endpoint for All Purchased Skills:**- * Create a new endpoint, e.g., `api/users/me/purchased-skills.js`.- * **Authentication:** Get the logged-in user.- * **Database Query:** Query the `user_skill_purchases` table for all records matching the `user_id` where `status` is `'confirmed'`.- * Join with `agent_identities` and `agent_skill_prices` to retrieve details like agent name, skill name, and the price they paid.- * Return the list of purchased skills as a JSON array.--2. **Create the Frontend Page:**- * Add a new tab or section to the user dashboard, e.g., `dashboard/my-skills.html`.- * Create a corresponding JS file, `src/dashboard-my-skills.js`.--3. **Render the List:**- * In the new JS file, fetch the data from the API endpoint.- * Render the data in a table or a list format.- * Include columns for: Purchase Date, Skill Name, Agent Name, and a link to the agent's page.--## HTML Example (`dashboard/my-skills.html`)--```html-<div class="dashboard-content">- <h2>My Purchased Skills</h2>- <p>This is a list of all the premium skills you have unlocked.</p>-- <table id="my-skills-table">- <thead>- <tr>- <th>Purchase Date</th>- <th>Skill</th>- <th>Agent</th>- <th></th>- </tr>- </thead>- <tbody>- <!-- JS will render rows here -->- </tbody>- </table>-</div>--<script src="/src/dashboard-my-skills.js" type="module"></script>-```diff --git a/docs/monetization-prompts/16-on-chain-nft-license.md b/docs/monetization-prompts/16-on-chain-nft-license.mddeleted file mode 100644index 767349e6a..000000000--- a/docs/monetization-prompts/16-on-chain-nft-license.md+++ /dev/null@@ -1,32 +0,0 @@-# Prompt 16: On-Chain License as an NFT (Optional)--## Objective-Optionally, extend the purchase flow to mint an NFT (Non-Fungible Token) that represents the user's license to use a skill, and store the mint address in the purchase record.--## Explanation-Minting a skill license as an NFT provides true on-chain ownership for the user. They can hold it, trade it, or use it as a verifiable credential. This transforms a simple database entry into a persistent, user-owned digital asset, aligning with Web3 principles. This would likely use the Metaplex standard on Solana.--## Instructions-1. **Design the NFT Metadata:**- * Define a metadata standard for the skill license NFT. It should include attributes for the `agent_id`, `skill_id`, `purchase_date`, etc.--2. **Create a Server-Side Minting Service:**- * This is a complex task that requires a secure backend wallet (a "minter") with funds to pay for transaction fees.- * Create a new API endpoint, e.g., `api/minter/mint-skill-license.js`.- * This endpoint will be called *after* a purchase is confirmed by the webhook.- * **Logic:**- * Take a `purchaseId` as input.- * Load the secure minter keypair.- * Use the Metaplex Umi or Helio SDK to create and mint a new NFT to the purchaser's wallet address.- * Use the metadata standard defined in step 1.- * The user's wallet address should be stored in your `users` table.--3. **Update Purchase Table:**- * Add a new nullable column to the `user_skill_purchases` table: `license_nft_mint` (TEXT).- * After successfully minting the NFT, save the NFT's mint address to this column for the corresponding purchase record.--4. **Display NFT on Frontend:**- * On the "My Purchased Skills" page, if a `license_nft_mint` exists, provide a link to a Solana explorer (like Solscan or X-Ray) to view the NFT.--## Note-This is an advanced feature. It requires secure key management on the backend, knowledge of a Solana SDK like Umi, and handling of on-chain transaction statuses.diff --git a/docs/monetization-prompts/16-skill-pricing-management-api.md b/docs/monetization-prompts/16-skill-pricing-management-api.mddeleted file mode 100644index 6e83ad457..000000000--- a/docs/monetization-prompts/16-skill-pricing-management-api.md+++ /dev/null@@ -1,85 +0,0 @@-----status: not-started------# Prompt 16: Skill Pricing Management - API--## Objective-Create the backend API endpoint to allow creators to save the prices they set for their skills.--## Explanation-This endpoint will receive the pricing information from the UI and persist it in the `agent_skill_prices` database table. It needs to be secure and handle updates efficiently.--## Instructions-- [ ] **Create the Database Table (if not exists):**- - [ ] You should have a table `agent_skill_prices`. If not, create it.- - [ ] Columns: `id`, `agent_id`, `skill_name`, `amount` (use a numeric type that can handle large integers, like `BIGINT`), `currency_mint`.- - [ ] Create a unique constraint on `(agent_id, skill_name)`.--- [ ] **Create the API Endpoint:**- - [ ] Create a new endpoint, e.g., `PUT /api/agents/:id/prices`.- - [ ] The `:id` parameter will be the agent's ID.- - [ ] Protect this endpoint with authentication middleware.--- [ ] **Implement Authorization and Validation:**- - [ ] Verify that the authenticated user (`req.user.id`) is the actual creator of the agent with the given `:id`. If not, return `403 Forbidden`.- - [ ] The request body will contain a `prices` object (a map of skill names to amounts).- - [ ] Validate this object: ensure it's a map, keys are strings, and values are non-negative integers.--- [ ] **Implement Database Logic (Upsert):**- - [ ] Iterate through the `prices` map from the request body.- - [ ] For each skill, perform an "upsert" operation in the `agent_skill_prices` table:- - [ ] If a row already exists for that `agent_id` and `skill_name`, `UPDATE` its `amount`.- - [ ] If it doesn't exist, `INSERT` a new row.- - [ ] If a skill's price is set to 0, you can either store it as 0 or `DELETE` the corresponding row, effectively making it a free skill. Deleting is often cleaner.--## SQL Upsert Example (PostgreSQL)--```sql-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;-```--## API Logic Example (Node.js)--```javascript-// PUT /api/agents/:id/prices-export default async function handler(req, res) {- // Assume auth middleware has run- const agentId = parseInt(req.query.id);- const creatorId = req.user.id;-- // 1. Authorization- const agent = await db.getAgent(agentId);- if (agent.creator_id !== creatorId) {- return res.status(403).json({ message: "You are not the creator of this agent." });- }-- const { prices } = req.body; // e.g., { "skill_one": 5000000 }-- // 2. Database updates in a transaction- const dbClient = await db.getClient();- try {- await dbClient.query('BEGIN');- for (const skillName in prices) {- const amount = prices[skillName];- if (amount > 0) {- // Perform UPSERT- await dbClient.query(upsertSql, [agentId, skillName, amount, 'USDC_MINT_ADDRESS']);- } else {- // Perform DELETE for skills set to 0- await dbClient.query(deleteSql, [agentId, skillName]);- }- }- await dbClient.query('COMMIT');- res.status(200).json({ message: "Prices updated successfully." });- } catch (e) {- await dbClient.query('ROLLBACK');- res.status(500).json({ message: "Failed to update prices." });- } finally {- dbClient.release();- }-}-```diff --git a/docs/monetization-prompts/16-support-multiple-currencies.md b/docs/monetization-prompts/16-support-multiple-currencies.mddeleted file mode 100644index be86ea30f..000000000--- a/docs/monetization-prompts/16-support-multiple-currencies.md+++ /dev/null@@ -1,64 +0,0 @@-# Prompt 16: Implement Different Currencies (SOL, etc.)--**Status:** - [ ] Not Started--## Objective-Extend the skill monetization feature to support payments in different SPL tokens, starting with SOL (as Wrapped SOL).--## Explanation-Currently, the system is hardcoded for USDC. To provide more flexibility for creators and users, the platform should support a selection of popular SPL tokens for pricing and payment.--## Instructions-1. **Update Database Schema:**- * The `agent_skill_prices` table already has a `currency_mint` column, which is great. Ensure your database queries and API responses handle this correctly.--2. **Modify Creator UI for Pricing:**- * In the "Skill Monetization" section of `agent-edit.html`, change the currency selector from a static element to a dropdown menu.- * Populate this dropdown with a list of supported currencies (e.g., "USDC", "SOL", "BONK"). This list can be hardcoded for now.- * When a creator selects a currency, store the corresponding mint address along with the price.--3. **Update Frontend Purchase Logic:**- * In `src/marketplace.js`, when constructing the purchase transaction, the mint address should not be hardcoded. It should be read from the `skillPrice.currency_mint` property.- * The UI in the purchase modal should also dynamically display the correct currency symbol and amount.- * **Special Handling for SOL:** Since SOL is the native token, payments in SOL are not standard SPL token transfers. The easiest way to handle this is to use Wrapped SOL (WSOL). The user's wallet will need to wrap SOL into WSOL before transferring. The `@solana/spl-token` library provides functions for this, and it can be done in the same transaction as the transfer.--## Code Example (Frontend - `spl-token-transfer.js` logic update)--```javascript-// Inside the purchase confirmation logic-import { NATIVE_MINT } from '@solana/spl-token'; // The mint address for WSOL--// ...-const currencyMint = new PublicKey(priceInfo.currency_mint);--const transaction = new Transaction();-let userTokenAccount = await getAssociatedTokenAddress(currencyMint, userPublicKey);--// Special handling if the currency is SOL (i.e., WSOL)-if (currencyMint.equals(NATIVE_MINT)) {- const userWsolAccountInfo = await connection.getAccountInfo(userTokenAccount);-- // If the user doesn't have a WSOL account, or not enough WSOL,- // we need to create one and/or wrap some SOL.- if (!userWsolAccountInfo || userWsolAccountInfo.data.length === 0) {- // Add instruction to create the associated token account for WSOL- }-- // You might need to check the user's SOL balance and add an instruction- // to wrap the required amount of SOL into WSOL.- // This involves transferring SOL to the WSOL account and calling a sync instruction.-}--// The transfer instruction remains the same, but now works with any currency mint-transaction.add(- createTransferInstruction(- userTokenAccount,- creatorTokenAccount,- userPublicKey,- priceInfo.amount- )-);--// ... send and confirm transaction-```-*Note: Handling Wrapped SOL adds significant complexity. You need to manage account creation and wrapping SOL within the same transaction, which requires careful balance management and instruction ordering.*diff --git a/docs/monetization-prompts/17-affiliate-program.md b/docs/monetization-prompts/17-affiliate-program.mddeleted file mode 100644index 01f52a1db..000000000--- a/docs/monetization-prompts/17-affiliate-program.md+++ /dev/null@@ -1,77 +0,0 @@-# Prompt 17: Affiliate and Referral Program--**Status:** - [ ] Not Started--## Objective-Design and implement an affiliate program where users can earn a commission for referring new customers who purchase skills.--## Explanation-A referral program can be a powerful growth engine. By rewarding users for promoting agents and skills, you can incentivize word-of-mouth marketing and expand the platform's reach.--## Instructions-1. **Database Schema Changes:**- * Create a `referrals` table to track referral relationships.- * Columns: `id`, `referrer_user_id`, `referred_user_id`, `created_at`.- * Add a `referrer_user_id` column to the `user_agent_skills` table to link a purchase to a specific referral. This can be nullable.--2. **Generate Unique Referral Links:**- * In the user's profile, provide a unique referral link (e.g., `three.ws/marketplace?ref=user_id`).- * When a new user signs up after visiting a referral link, store the referrer's ID in a cookie.- * When the new user signs up, read the cookie and create a record in the `referrals` table.--3. **Attribute Purchases to Referrers:**- * When a user makes a purchase, the backend should check if they were referred.- * If so, populate the `referrer_user_id` in the `user_agent_skills` record.--4. **Payout Logic for Referrers:**- * Modify the creator payout cron job (`/api/cron/process-payouts.js`) or smart contract.- * When processing a sale that has a referrer, the payment needs to be split three ways: creator, platform, and referrer.- * Define the commission rates (e.g., 5% for the referrer).--5. **Referral Dashboard for Users:**- * Create a section in the user's dashboard to track their referrals.- * Display stats like number of sign-ups from their link, number of purchases made by their referrals, and total commission earned.--## Code Example (Conceptual - Purchase Endpoint Modification)--```javascript-// In /api/marketplace/purchase-skill.js-export default async function handler(req, res) {- const userId = req.user.id;- // ...-- // Check for a referrer ID, which might be stored in the user's session- // or looked up from the 'referrals' table.- const referrerId = await db.findReferrerForUser(userId);-- // ... (Transaction verification logic)-- if (verificationSuccess) {- // Pass referrerId when recording the purchase- await db.recordSkillPurchase(userId, agentId, skillName, referrerId);- // ...- }-}-```--## Code Example (Conceptual - Payout Logic Modification)--```javascript-// In the payout cron job-for (const purchase of pendingPurchases) {- const creatorBase = purchase.amount * (1 - PLATFORM_FEE_PERCENT / 100);- let creatorShare = creatorBase;-- if (purchase.referrer_id) {- const referrerCommission = purchase.amount * (REFERRAL_COMMISSION_PERCENT / 100);- creatorShare -= referrerCommission;-- // Add to referrer's payout- const referrer = await db.getUser(purchase.referrer_id);- payouts[referrer.wallet_address] = (payouts[referrer.wallet_address] || 0) + referrerCommission;- }-- // Add to creator's payout- payouts[purchase.creator_address] = (payouts[purchase.creator_address] || 0) + creatorShare;-}-```diff --git a/docs/monetization-prompts/17-creator-payout-settings-ui.md b/docs/monetization-prompts/17-creator-payout-settings-ui.mddeleted file mode 100644index 89bcc63bb..000000000--- a/docs/monetization-prompts/17-creator-payout-settings-ui.md+++ /dev/null@@ -1,81 +0,0 @@-----status: not-started------# Prompt 17: Creator Payout Settings - UI--## Objective-Create a user interface in the user's settings or profile page for them to manage their payout wallet address.--## Explanation-To receive payments, creators need a secure and simple way to input and update their Solana wallet address. This UI should provide clear instructions and validation.--## Instructions-- [ ] **Design the UI:**- - [ ] Choose a suitable location for this setting, such as a "Payouts" or "Monetization" tab in the user's main profile/settings page.- - [ ] Add a new section titled "Payout Wallet".- - [ ] Include an input field for the Solana wallet address.- - [ ] Add a "Save" button.- - [ ] Display the currently saved address (if any) and provide clear helper text, e.g., "This is the Solana wallet where you will receive payments for skill purchases."- - [ ] Add a warning about the importance of using the correct address.--- [ ] **Implement Frontend Logic:**- - [ ] When the page loads, fetch the user's current settings, including their `payout_wallet_address`, and populate the input field.- - [ ] When the user clicks "Save":- - [ ] Get the value from the input field.- - [ ] Perform client-side validation to check if it looks like a valid Solana address (e.g., check length and characters). A full validation on the backend is still required.- - [ ] Make a `PUT` request to the backend endpoint (`/api/users/payout-settings`) with the new address.- - [ ] Display a success or error message to the user based on the API response.--## HTML Example (in a user settings page)--```html-<div class="settings-section">- <h3>Payout Wallet</h3>- <p class="helper-text">Enter the Solana wallet address where you want 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 Solana public key">- <small>Warning: Ensure this address is correct. Payments sent to a wrong address cannot be recovered.</small>- </div>-- <button id="save-payout-btn">Save Wallet Address</button>- <div id="payout-status-message"></div>-</div>-```--## JavaScript Example (on Save button click)--```javascript-document.getElementById('save-payout-btn').addEventListener('click', async () => {- const walletAddress = document.getElementById('payout-wallet').value;- const statusEl = document.getElementById('payout-status-message');-- // Basic client-side check- if (walletAddress.length < 32 || walletAddress.length > 44) {- statusEl.textContent = 'Please enter a valid Solana address.';- statusEl.style.color = 'red';- return;- }-- try {- const response = await fetch('/api/users/payout-settings', {- method: 'PUT',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ payout_wallet_address: walletAddress }),- });-- if (!response.ok) {- const error = await response.json();- throw new Error(error.message);- }-- statusEl.textContent = 'Payout address updated successfully!';- statusEl.style.color = 'green';- } catch (error) {- statusEl.textContent = `Error: ${error.message}`;- statusEl.style.color = 'red';- }-});-```diff --git a/docs/monetization-prompts/17-database-schema-creator-payouts.md b/docs/monetization-prompts/17-database-schema-creator-payouts.mddeleted file mode 100644index ebbf599d6..000000000--- a/docs/monetization-prompts/17-database-schema-creator-payouts.md+++ /dev/null@@ -1,60 +0,0 @@-# Prompt 17: Database Schema for Creator Payouts--## Objective-Create database tables to manage creator earnings and track payout (withdrawal) transactions.--## Explanation-Creators need a way to withdraw their earnings. This requires a system to track their current balance, record each payout request, and log the status of the transaction. This prompt sets up the database foundation for the creator payout system.--## Instructions-1. **Locate the Schema File:**- * Open `api/_lib/schema.sql`.--2. **Add a `creator_balances` Table:**- * This table will hold the current withdrawable balance for each creator. It acts as a ledger.- * Columns:- * `user_id` (PRIMARY KEY, Foreign key to `users(id)`).- * `balance` (BIGINT, the current balance in the smallest currency unit).- * `currency_mint` (TEXT).- * `updated_at`.--3. **Add a `creator_payouts` Table:**- * This table will log every withdrawal attempt.- * Columns:- * `id` (UUID PRIMARY KEY).- * `user_id` (Foreign key to `users(id)`).- * `amount` (BIGINT).- * `currency_mint` (TEXT).- * `destination_address` (TEXT, the creator's wallet address for the payout).- * `status` (ENUM: 'requested', 'processing', 'completed', 'failed').- * `transaction_id` (TEXT, the on-chain transaction signature of the payout).- * `created_at`, `updated_at`.--## SQL Example--```sql--- In api/_lib/schema.sql--CREATE TABLE creator_balances (- user_id UUID PRIMARY KEY REFERENCES users(id),- balance BIGINT NOT NULL DEFAULT 0,- currency_mint TEXT NOT NULL,- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);--CREATE TYPE payout_status AS ENUM ('requested', 'processing', 'completed', 'failed');--CREATE TABLE creator_payouts (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL REFERENCES users(id),- amount BIGINT NOT NULL,- currency_mint TEXT NOT NULL,- destination_address TEXT NOT NULL,- status payout_status NOT NULL DEFAULT 'requested',- transaction_id TEXT,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);--CREATE INDEX idx_creator_payouts_user_id ON creator_payouts(user_id);-```diff --git a/docs/monetization-prompts/18-api-creator-withdrawal.md b/docs/monetization-prompts/18-api-creator-withdrawal.mddeleted file mode 100644index 24818514b..000000000--- a/docs/monetization-prompts/18-api-creator-withdrawal.md+++ /dev/null@@ -1,69 +0,0 @@-# Prompt 18: API Endpoint for Creator Withdrawal Request--## Objective-Create a secure API endpoint that allows a creator to request a withdrawal of their available earnings balance.--## Explanation-This endpoint is the first step in the payout process. It allows a creator to formally request a withdrawal. The system will validate the request, create a payout record with a 'requested' status, and deduct the amount from their withdrawable balance. A separate background process will handle the actual on-chain transaction.--## Instructions-1. **Create the API File:**- * Create a new API endpoint, e.g., `api/dashboard/request-withdrawal.js`.--2. **Implement the `POST` Handler:**- * **Authentication:** Get the logged-in user.- * **Input Validation:** Expect an `amount` in the request body.- * **Fetch Balance:** Get the creator's current balance from the `creator_balances` table.- * **Validate Request:**- * Ensure the requested `amount` is greater than zero and not more than their available balance.- * Ensure the user has a destination wallet address configured in their profile.- * **Database Transaction:**- * Start a database transaction to ensure atomicity.- * **Decrement Balance:** Subtract the `amount` from the `creator_balances` table.- * **Create Payout Record:** Insert a new row into the `creator_payouts` table with `status = 'requested'`.- * Commit the transaction.- * **Return Success:** Respond with a success message.--## Code Example (`api/dashboard/request-withdrawal.js`)--```javascript-import { sql } from '../_lib/db.js';-import { getSessionUser } from '../_lib/auth.js';-import { error, json, wrap } from '../_lib/http.js';--export default wrap(async (req, res) => {- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized');-- const { amount } = await req.json();- // TODO: Fetch user's configured destination wallet- const destinationAddress = '...';-- if (!amount || amount <= 0) return error(res, 400, 'invalid_amount');-- try {- await sql.begin(async sql => {- const [balance] = await sql`- SELECT balance, currency_mint FROM creator_balances WHERE user_id = ${user.id} FOR UPDATE- `;-- if (!balance || balance.balance < amount) {- throw new Error('Insufficient funds');- }-- await sql`- UPDATE creator_balances SET balance = balance - ${amount} WHERE user_id = ${user.id}- `;-- await sql`- INSERT INTO creator_payouts (user_id, amount, currency_mint, destination_address, status)- VALUES (${user.id}, ${amount}, ${balance.currency_mint}, ${destinationAddress}, 'requested')- `;- });- } catch (e) {- return error(res, 400, 'transaction_failed', e.message);- }-- return json(res, { success: true, message: 'Withdrawal requested.' });-});-```diff --git a/docs/monetization-prompts/18-creator-dashboard-ui.md b/docs/monetization-prompts/18-creator-dashboard-ui.mddeleted file mode 100644index 9a85a31a6..000000000--- a/docs/monetization-prompts/18-creator-dashboard-ui.md+++ /dev/null@@ -1,97 +0,0 @@-----status: not-started------# Prompt 18: Creator Dashboard - UI--## Objective-Build the frontend for the creator dashboard, visualizing the sales and earnings data provided by the backend APIs.--## Explanation-A visual dashboard is essential for creators to understand their performance at a glance. We will create a new page that consumes the creator dashboard APIs and presents the data using charts and tables.--## Instructions-- [ ] **Create the Dashboard Page:**- - [ ] Create a new HTML file, e.g., `creator-dashboard.html`.- - [ ] Create a corresponding JavaScript file, e.g., `src/creator-dashboard.js`.--- [ ] **Fetch and Display Key Stats:**- - [ ] On page load, make a request to the `GET /api/creator/dashboard/stats` endpoint.- - [ ] Display the returned stats (total revenue, total sales) in prominent "stat cards" at the top of the page.- - [ ] Remember to format the revenue from the smallest unit to a human-readable number.--- [ ] **Display Sales History:**- - [ ] Make a request to the `GET /api/creator/dashboard/sales-history` endpoint.- - [ ] Render the returned list of sales in a table. The table should include columns like "Date", "Skill Name", "Agent", "Price", and "Earnings".--- [ ] **Add a Chart (Optional but recommended):**- - [ ] Include a charting library like Chart.js or D3.- - [ ] Make a request to an endpoint that provides time-series data (e.g., `GET /api/creator/dashboard/revenue-over-time`). You may need to create this endpoint.- - [ ] Render a line or bar chart showing daily or weekly earnings.--## HTML Structure Example (`creator-dashboard.html`)--```html-<body>- <h1>Creator Dashboard</h1>-- <div id="stats-grid">- <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>-- <div id="sales-chart-container">- <canvas id="sales-chart"></canvas>- </div>-- <div id="sales-history-container">- <h3>Recent Sales</h3>- <table id="sales-history-table">- <thead>- <tr>- <th>Date</th>- <th>Skill</th>- <th>Earnings</th>- </tr>- </thead>- <tbody>- <!-- Rows will be injected by JavaScript -->- </tbody>- </table>- </div>-</body>-```--## JavaScript Example (`src/creator-dashboard.js`)--```javascript-async function initDashboard() {- // Fetch and display stats- const statsRes = await fetch('/api/creator/dashboard/stats');- const stats = await statsRes.json();- document.getElementById('total-revenue-stat').textContent = `$${(stats.totalRevenue / 1e6).toFixed(2)}`;- document.getElementById('total-sales-stat').textContent = stats.totalSales;-- // Fetch and render sales history table- const historyRes = await fetch('/api/creator/dashboard/sales-history');- const history = await historyRes.json();- const tableBody = document.querySelector('#sales-history-table tbody');- tableBody.innerHTML = history.sales.map(sale => `- <tr>- <td>${new Date(sale.date).toLocaleDateString()}</td>- <td>${escapeHtml(sale.skillName)}</td>- <td>$${(sale.earnings / 1e6).toFixed(2)}</td>- </tr>- `).join('');-- // Logic to initialize chart would go here-}--initDashboard();-```diff --git a/docs/monetization-prompts/18-subscription-model.md b/docs/monetization-prompts/18-subscription-model.mddeleted file mode 100644index 7aeec68d1..000000000--- a/docs/monetization-prompts/18-subscription-model.md+++ /dev/null@@ -1,56 +0,0 @@-# Prompt 18: Skill Subscription Model--**Status:** - [ ] Not Started--## Objective-Implement a subscription model where users can pay a recurring fee for access to a set of skills from a creator, or all skills on the platform.--## Explanation-Subscriptions provide a predictable revenue stream for creators and the platform. This model can be attractive to power users who want access to a wide range of premium skills without making individual purchases. This could be implemented using a system like Solana Pay or by integrating with a dedicated NFT subscription service.--## Instructions-1. **Database Schema for Subscriptions:**- * Create a `subscriptions` table:- * Columns: `id`, `user_id`, `subscription_tier_id`, `start_date`, `end_date`, `status` (e.g., 'active', 'cancelled').- * Create a `subscription_tiers` table:- * Columns: `id`, `creator_id` (nullable, for creator-specific tiers), `name`, `price`, `currency_mint`, `duration_days`.--2. **UI for Subscribing:**- * Create a new "Subscriptions" page.- * Display available subscription tiers (e.g., "Pro Tier - All Skills", "Creator X's All-Access Pass").- * Add a "Subscribe" button for each tier.--3. **Handle Recurring Payments:**- * This is the most complex part. On-chain recurring payments on Solana are not as straightforward as with traditional payment systems.- * **Option 1: Solana Pay.** Integrate with Solana Pay to allow users to approve recurring transactions. This still requires user action for each payment period.- * **Option 2: Subscription-as-an-NFT.** A user mints an NFT that represents their subscription. The NFT has an expiration date. The dApp checks for a valid (non-expired) subscription NFT in the user's wallet. The user has to manually "renew" by purchasing a new subscription NFT.- * **Option 3: Off-chain with Credit Card.** For a hybrid model, use a service like Stripe for recurring billing and then have the backend airdrop a subscription NFT to the user.--4. **Update Skill Gating Logic:**- * Modify the skill gating logic from Prompt 14.- * Before denying access to a paid skill, the system must also check if the user has an active subscription that grants access to that skill.- * This check involves looking for a valid record in the `subscriptions` table or a valid subscription NFT in the user's wallet.--## Code Example (Conceptual - Skill Gating Update)--```javascript-// In the backend skill execution endpoint-// ... (after checking for a price)--if (skillPrice) {- // Check for direct ownership first- const hasOwnership = await db.checkSkillOwnership(userId, agentId, skillName);-- if (!hasOwnership) {- // If not owned directly, check for an active subscription- const hasActiveSub = await db.checkActiveSubscription(userId, agentId, skillName);-- if (!hasActiveSub) {- return res.status(403).json({ error: 'Subscription or purchase required.' });- }- }-}--// Proceed with execution-// ...-```diff --git a/docs/monetization-prompts/19-skill-bundling.md b/docs/monetization-prompts/19-skill-bundling.mddeleted file mode 100644index f1dcf89e3..000000000--- a/docs/monetization-prompts/19-skill-bundling.md+++ /dev/null@@ -1,63 +0,0 @@-# Prompt 19: Skill Bundles and Packages--**Status:** - [ ] Not Started--## Objective-Allow creators to bundle multiple skills together and sell them as a package, often at a discounted price compared to buying each skill individually.--## Explanation-Bundling is a common and effective marketing strategy. It increases the perceived value for customers and can lead to larger average transaction sizes. For example, a creator could offer a "starter pack" of their three most popular skills.--## Instructions-1. **Database Schema for Bundles:**- * Create a `skill_bundles` table:- * Columns: `id`, `creator_id`, `name`, `description`, `price`, `currency_mint`.- * Create a `skill_bundle_items` table to link skills to bundles:- * Columns: `id`, `bundle_id`, `skill_name`, `agent_id`.--2. **UI for Creating Bundles:**- * In the creator's dashboard or agent edit page, add an interface for "Create a Skill Bundle".- * The creator should be able to:- * Give the bundle a name and description.- * Select which of their skills to include.- * Set a single price for the entire bundle.--3. **Display Bundles in the Marketplace:**- * On the agent detail page, in addition to individual skills, display any bundles offered by the creator.- * Each bundle listing should show the included skills and the bundle price.- * The UI should clearly show the savings compared to buying the skills individually.--4. **Handle Bundle Purchases:**- * The purchase flow for a bundle is similar to a single skill.- * When the backend's `purchase-skill` endpoint is adapted to handle bundles (e.g., a new `purchase-bundle` endpoint), it must:- * Verify the single payment for the bundle.- * Add a record to the `user_agent_skills` table for *each* skill included in the bundle.--## Code Example (Conceptual - `purchase-bundle` backend endpoint)--```javascript-export default async function handler(req, res) {- const userId = req.user.id;- const { bundleId, transactionSignature } = req.body;-- const db = getDB();- const bundle = await db.getBundle(bundleId);-- // 1. Verify the transaction for the bundle's price- // ... (similar to single skill verification)-- if (verificationSuccess) {- // 2. Get all skills included in the bundle- const skillsInBundle = await db.getSkillsInBundle(bundleId);-- // 3. Record ownership for each skill in the bundle- for (const item of skillsInBundle) {- await db.recordSkillPurchase(userId, item.agent_id, item.skill_name);- }-- res.status(200).json({ success: true, message: 'Bundle purchased!' });- } else {- // ... handle error- }-}-```diff --git a/docs/monetization-prompts/19-skill-gating-logic.md b/docs/monetization-prompts/19-skill-gating-logic.mddeleted file mode 100644index db0a84a3c..000000000--- a/docs/monetization-prompts/19-skill-gating-logic.md+++ /dev/null@@ -1,62 +0,0 @@-----status: not-started------# Prompt 19: Skill Usage Gating--## Objective-Implement the core logic that prevents users from using a paid skill unless they have successfully purchased it.--## Explanation-This is where monetization becomes functional. So far, we can sell skills, but there's nothing stopping a user from trying to use them anyway. This "gating" logic must be enforced on the backend to be secure.--## Instructions-- [ ] **Locate the Skill Execution Logic:**- - [ ] Find the part of your backend code that is responsible for executing an agent's skill. This might be in a chat API, a general agent interaction endpoint, or a dedicated skill execution endpoint.--- [ ] **Add a Pre-Execution Check:**- - [ ] Before the skill's code is run, insert a new checking mechanism.- - [ ] This check needs to know which user is making the request, which agent is being used, and which skill is being invoked.--- [ ] **Perform Ownership Verification:**- - [ ] Inside the check, first determine if the skill in question is a paid skill. Query the `agent_skill_prices` table for the agent and skill name.- - [ ] If the skill is **not** in the prices table, it's free. Allow execution to proceed.- - [ ] If the skill **is** in the prices table, it's a paid skill. You must now query the `unlocked_skills` table.- - [ ] Check if a row exists in `unlocked_skills` for the current `user_id`, `agent_id`, and `skill_name`.- - [ ] **If a row exists**, the user owns the skill. Allow execution to proceed.- - [ ] **If no row exists**, the user does not own the skill. Block the execution and return an error message to the user, e.g., `402 Payment Required`, with a message like "You must purchase this skill to use it."--## Code Example (Backend Skill Execution Endpoint)--```javascript-// Example of an endpoint that runs a skill-export default async function handler(req, res) {- // Assume auth middleware has run and req.user is available- const { agentId, skillName, skillInputs } = req.body;- const userId = req.user.id;-- // --- NEW GATING LOGIC ---- // 1. Check if the skill is priced- const price = await db.getSkillPrice(agentId, skillName);-- if (price) {- // It's a paid skill, so check for ownership- const isOwned = await db.checkSkillOwnership(userId, agentId, skillName);- if (!isOwned) {- return res.status(402).json({- message: `This is a paid skill. Please purchase it from the marketplace to use it.`- });- }- }- // --- END OF GATING LOGIC ----- // If the logic reaches here, the user is allowed to proceed.- // Original skill execution logic follows:- try {- const result = await executeSkill(agentId, skillName, skillInputs);- res.status(200).json({ result });- } catch (error) {- res.status(500).json({ message: "Skill execution failed." });- }-}-```diff --git a/docs/monetization-prompts/19-worker-payout-processing.md b/docs/monetization-prompts/19-worker-payout-processing.mddeleted file mode 100644index f8d34be36..000000000--- a/docs/monetization-prompts/19-worker-payout-processing.md+++ /dev/null@@ -1,40 +0,0 @@-# Prompt 19: Background Worker for Payout Processing--## Objective-Create a background worker or cron job that processes pending withdrawal requests, executes the on-chain transaction, and updates the payout record.--## Explanation-Sending crypto assets requires a secure, asynchronous process. A withdrawal request should not be processed within a user-facing API call. A background worker will periodically scan for 'requested' payouts, use a secure hot wallet to send the funds, and update the database with the transaction signature and final status.--## Instructions-1. **Create a Worker File:**- * In the `workers/` directory, create a new file, e.g., `payout-processor.js`.--2. **Implement the Worker Logic:**- * **Fetch Pending Payouts:** Write a query to select all records from `creator_payouts` where `status` is `'requested'`.- * **Loop and Process:** Iterate through each requested payout.- * **Securely Load Hot Wallet:** Load the private key for the platform's treasury/hot wallet from a secure secret manager (e.g., Vercel environment variables). **Never hardcode private keys.**- * **Execute Transaction:**- * Use the `@solana/web3.js` and `@solana/spl-token` libraries to build and send the SPL token transfer transaction from the hot wallet to the creator's `destination_address`.- * Update the payout record's `status` to `'processing'`.- * **Handle Confirmation:**- * Await confirmation of the transaction.- * On success, update the `creator_payouts` record with `status = 'completed'` and the `transaction_id`.- * On failure, update the status to `'failed'` and *revert the balance deduction* in a compensating transaction or log for manual review.--3. **Schedule the Worker:**- * Configure this script to run on a schedule. If using Vercel, you can define it as a Cron Job in `vercel.json`.--## Vercel Cron Job Example (`vercel.json`)--```json-{- "crons": [- {- "path": "/api/cron/process-payouts",- "schedule": "0 * * * *" // Run every hour- }- ]-}-```-*(This requires creating an API endpoint that triggers the worker logic)*.diff --git a/docs/monetization-prompts/20-batch-skill-purchase.md b/docs/monetization-prompts/20-batch-skill-purchase.mddeleted file mode 100644index 0e8efd4fd..000000000--- a/docs/monetization-prompts/20-batch-skill-purchase.md+++ /dev/null@@ -1,48 +0,0 @@-----status: not-started------# Prompt 20: Batch Skill Purchase (Shopping Cart)--## Objective-Allow users to add multiple skills to a "cart" and purchase them all in a single transaction.--## Explanation-Purchasing skills one by one can be tedious and costly in terms of transaction fees. A shopping cart feature improves the user experience by allowing a single, consolidated purchase for multiple items.--## Instructions-- [ ] **Frontend: Cart UI:**- - [ ] Instead of a "Purchase" button, have an "Add to Cart" button.- - [ ] Add a cart icon to the site header that shows the number of items.- - [ ] Clicking the icon opens a cart modal/sidebar, listing the selected skills and the total price.- - [ ] The cart should have a "Checkout" button.--- [ ] **Frontend: Cart State Management:**- - [ ] Use `localStorage` or a simple in-memory object to manage the cart's state (the list of skills to be purchased).- - [ ] When "Add to Cart" is clicked, add the skill's details (`agentId`, `skillName`) to the cart.- - [ ] When "Checkout" is clicked, pass the list of items in the cart to the backend.--- [ ] **Backend: Update "Create Transaction" Endpoint:**- - [ ] Modify `POST /api/transactions/create-skill-purchase` to accept an **array** of skills instead of a single skill.- - [ ] The endpoint will now loop through the array of skills.- - [ ] For each skill, it calculates the payment due to the respective creator.- - [ ] It will add a separate `SPL Token Transfer` instruction **for each skill** to the transaction. If a user buys 3 skills from 3 different creators, the transaction will contain 3 transfers (plus 3 platform fee transfers).- - [ ] The backend returns a single transaction that bundles all these transfers.--- [ ] **Backend: Update "Verify Transaction" Endpoint:**- - [ ] The verification logic must also be updated to handle multiple items.- - [ ] It will receive an array of skills that were supposed to be in the transaction.- - [ ] It must parse the transaction from the blockchain and verify that **all** the expected transfers (to creators and platform) are present and correct.- - [ ] If verification is successful, it should add a row to the `unlocked_skills` table for **each** purchased skill. This should be done in a database transaction.--## API Request Body Example (for Create Transaction)--```json-{- "buyerPublicKey": "USER_WALLET_ADDRESS",- "items": [- { "agentId": 123, "skillName": "AdvancedAnalysis" },- { "agentId": 456, "skillName": "ImageGeneration" }- ]-}-```diff --git a/docs/monetization-prompts/20-email-notifications.md b/docs/monetization-prompts/20-email-notifications.mddeleted file mode 100644index 8d9ed6cdd..000000000--- a/docs/monetization-prompts/20-email-notifications.md+++ /dev/null@@ -1,52 +0,0 @@-# Prompt 20: Email Notifications for Monetization Events--## Objective-Implement email notifications for creators and users for key monetization events like "Skill Sold" and "Payout Processed".--## Explanation-Communication is key to a good user experience. Automated emails build trust and keep users informed. We should notify creators when they make a sale and when their withdrawal has been successfully processed.--## Instructions-1. **Choose an Email Service Provider:**- * Select and configure an email sending service like Resend, SendGrid, or Postmark.- * Add the necessary API keys and sender email addresses to your environment variables.--2. **Create Email Sending Utilities:**- * In `api/_lib/`, create a new file, e.g., `email.js`.- * This file should contain helper functions to send transactional emails using your chosen provider's SDK.- * Create templates for each notification type.--3. **Integrate "Skill Sold" Notification:**- * In the purchase confirmation webhook (`api/webhooks/solana-pay.js`), after successfully updating the purchase status to `'confirmed'`:- * Call your email helper to send a "You've made a sale!" email to the skill creator.- * Include details like the skill name, agent name, and amount earned.--4. **Integrate "Payout Processed" Notification:**- * In the payout processing worker (`workers/payout-processor.js`), after a payout transaction is successfully confirmed:- * Call your email helper to send a "Your payout is on its way" email to the creator.- * Include the amount, destination wallet, and a link to the transaction on a block explorer.--## Code Example (Conceptual - in `solana-pay.js` webhook)--```javascript-import { sendSaleNotification } from '../_lib/email.js';--// ... after validating transaction and updating DB ...--if (isValid) {- await sql`- UPDATE user_skill_purchases SET status = 'confirmed' ...- `;-- // Fetch creator's email and send notification- const [creator] = await sql`SELECT email FROM users WHERE id = ${purchase.creator_id}`;- if (creator.email) {- await sendSaleNotification(creator.email, {- skillName: purchase.skill_id,- amount: purchase.amount,- });- }-- return json(res, { message: 'Transaction confirmed' });-}-```diff --git a/docs/monetization-prompts/20-skill-reviews-and-ratings.md b/docs/monetization-prompts/20-skill-reviews-and-ratings.mddeleted file mode 100644index fb3e9106f..000000000--- a/docs/monetization-prompts/20-skill-reviews-and-ratings.md+++ /dev/null@@ -1,52 +0,0 @@-# Prompt 20: User Reviews and Ratings for Skills--**Status:** - [ ] Not Started--## Objective-Implement a system for users to leave reviews and ratings for purchased skills, and display these on the agent detail page.--## Explanation-Social proof is a powerful driver for purchasing decisions. Allowing users to rate and review skills helps other users make informed decisions and provides valuable feedback to creators.--## Instructions-1. **Database Schema for Reviews:**- * Create a `skill_reviews` table:- * Columns: `id`, `user_id`, `agent_id`, `skill_name`, `rating` (1-5), `review_text`, `created_at`.--2. **UI for Submitting a Review:**- * On the "My Purchased Skills" page (from Prompt 11), add a "Leave a Review" button next to each skill the user has not yet reviewed.- * Clicking this button should open a modal or form with a star rating system (1-5) and a textarea for the review text.--3. **Backend for Submitting Reviews:**- * Create an endpoint `/api/skills/submit-review`.- * This endpoint must verify that the user owns the skill they are reviewing before accepting the review.- * It will insert the new review into the `skill_reviews` table.--4. **Display Reviews and Average Rating:**- * Modify the agent detail endpoint (`/api/marketplace/agents/:id`) to also fetch and aggregate review data for the agent's skills.- * For each skill, calculate the average rating and the total number of reviews.- * On the `marketplace.html` detail page, display the average star rating next to each skill.- * Consider adding a new tab or section on the detail page to display all written reviews for the agent's skills.--## Code Example (UI for displaying rating)--```javascript-// In the marketplace.js skill rendering loop-const averageRating = skill.average_rating || 0;-const reviewCount = skill.review_count || 0;--let ratingDisplay = '';-if (reviewCount > 0) {- ratingDisplay = `<span class="skill-rating">- ${'★'.repeat(Math.round(averageRating))}${'☆'.repeat(5 - Math.round(averageRating))}- (${reviewCount})- </span>`;-}--// Add ratingDisplay to the skill entry HTML-return `<div class="skill-entry">- <span class="skill-name">${escapeHtml(name)}</span>- ${ratingDisplay}- ${badgeOrButton}- </div>`;-```diff --git a/docs/monetization-prompts/21-gifting-skills.md b/docs/monetization-prompts/21-gifting-skills.mddeleted file mode 100644index 7aa3d9529..000000000--- a/docs/monetization-prompts/21-gifting-skills.md+++ /dev/null@@ -1,62 +0,0 @@-# Prompt 21: Gifting Skills to Other Users--**Status:** - [ ] Not Started--## Objective-Allow users to purchase a skill as a gift for another user on the platform.--## Explanation-Gifting is a great way to introduce new users to the platform and can be a fun social feature. It allows users to share their favorite skills with friends.--## Instructions-1. **Modify the Purchase Flow:**- * In the purchase confirmation modal, add a checkbox or button: "Purchase as a gift?".- * If checked, reveal an input field for the recipient's username or wallet address.--2. **Backend Logic for Gifting:**- * Modify the `purchase-skill` backend endpoint to handle an optional `recipient_user_id`.- * If a recipient is specified, the transaction verification remains the same (the buyer pays).- * However, when recording the ownership in the `user_agent_skills` table, the record should be created for the `recipient_user_id`, not the buyer's ID.- * You may want to add a `gifted_by_user_id` column to the table to track this.--3. **Notifications:**- * Implement a notification system (if one doesn't exist) to inform the recipient that they have received a gift.- * The notification should specify the skill, the agent, and who sent the gift.--4. **On-Chain Receipt (NFT):**- * If you are minting NFTs as receipts (Prompt 12), the NFT should be minted to the recipient's wallet, not the buyer's. The metadata could include a "Gifted By" attribute.--## Code Example (Conceptual - Backend `purchase-skill` modification)--```javascript-export default async function handler(req, res) {- const buyerUserId = req.user.id;- const { agentId, skillName, transactionSignature, recipientUsername } = req.body;- let finalOwnerId = buyerUserId;-- const db = getDB();-- if (recipientUsername) {- const recipient = await db.findUserByUsername(recipientUsername);- if (!recipient) {- return res.status(404).json({ error: 'Recipient not found.' });- }- finalOwnerId = recipient.id;- }-- // ... (Verify transaction was paid by buyerUserId)-- if (verificationSuccess) {- // Record purchase for the final owner (recipient or buyer)- await db.recordSkillPurchase(finalOwnerId, agentId, skillName, buyerUserId); // buyerUserId is the gifter-- // Trigger a notification to the recipient- if (recipientUsername) {- await sendNotification(finalOwnerId, `You received the skill ${skillName} as a gift!`);- }-- res.status(200).json({ success: true, message: 'Gift purchase successful!' });- }- // ...-}-```diff --git a/docs/monetization-prompts/21-refactor-monetization-service.md b/docs/monetization-prompts/21-refactor-monetization-service.mddeleted file mode 100644index 628c330f7..000000000--- a/docs/monetization-prompts/21-refactor-monetization-service.md+++ /dev/null@@ -1,64 +0,0 @@-# Prompt 21: Refactor Monetization Logic into a Service Class--## Objective-Organize all backend monetization logic (price checks, purchase creation, balance updates) into a dedicated, reusable `MonetizationService` class to improve code structure and maintainability.--## Explanation-As the monetization feature grows, its logic becomes scattered across different API endpoints and workers. Consolidating this logic into a single service class makes the code cleaner, easier to test, and reduces duplication. The service will act as the single source of truth for all monetization-related database interactions.--## Instructions-1. **Create the Service File:**- * In `api/_lib/`, create a new file named `monetization-service.js`.--2. **Define the `MonetizationService` Class:**- * The class constructor can accept a database connection object.- * **Methods to Create:**- * `setSkillPrice({ agentId, skillId, amount, ... })`- * `removeSkillPrice({ agentId, skillId })`- * `initiatePurchase({ userId, agentId, skillId })`- * `confirmPurchase({ purchaseId, transactionId })`- * `gateSkillAccess({ userId, agentId, skillId })`- * `getCreatorEarnings({ userId })`- * `requestWithdrawal({ userId, amount })`- * `processPayout({ payoutId, transactionId })`--3. **Implement Method Logic:**- * Move the corresponding SQL queries and business logic from the various API endpoints (e.g., `purchase.js`, `earnings.js`) into the methods of this class.- * The API endpoints will become much thinner, primarily responsible for handling HTTP requests/responses and calling the service methods.--4. **Refactor API Endpoints:**- * Go back to the API files (`purchase.js`, `skill-prices.js`, etc.).- * Instantiate the `MonetizationService` at the top of each file.- * Replace the raw `sql` calls with calls to the service's methods.--## Code Example (`monetization-service.js`)--```javascript-import { sql } from './db.js';--export class MonetizationService {- constructor(db) {- this.db = db;- }-- async initiatePurchase({ userId, agentId, skillId }) {- // ... logic from 'api/marketplace/purchase.js' goes here ...- const [priceInfo] = await this.db`...`;- // ...- const [purchase] = await this.db`- INSERT INTO user_skill_purchases (...) VALUES (...) RETURNING id- `;- return { purchaseId: purchase.id, ... };- }-- // ... other methods ...-}--// In an API file like `api/marketplace/purchase.js`-import { MonetizationService } from '../_lib/monetization-service.js';-const monetizationService = new MonetizationService(sql);--// ... in the handler-const result = await monetizationService.initiatePurchase({ userId: user.id, ...body });-return json(res, result);-```diff --git a/docs/monetization-prompts/21-skill-subscription-model-backend.md b/docs/monetization-prompts/21-skill-subscription-model-backend.mddeleted file mode 100644index cd7909db5..000000000--- a/docs/monetization-prompts/21-skill-subscription-model-backend.md+++ /dev/null@@ -1,68 +0,0 @@-----status: not-started------# Prompt 21: Skill Subscription Model - Backend--## Objective-Implement the backend infrastructure for a subscription model, where users pay a recurring fee for access to all of an agent's paid skills.--## Explanation-Subscriptions provide predictable revenue for creators and value for active users. This is a significant feature requiring new database tables and logic for managing subscription status and recurring payments. We'll focus on the backend setup first. For payments, we could use a service like Helio to manage recurring Solana payments.--## Instructions-- [ ] **Database Schema Changes:**- - [ ] Create a new table: `agent_subscriptions`.- - [ ] Columns: `id`, `user_id`, `agent_id`, `status` (e.g., 'active', 'cancelled', 'past_due'), `expires_at` (Timestamp), `payment_provider_subscription_id` (String).- - [ ] Add a new table `agent_subscription_plans`: `id`, `agent_id`, `amount`, `currency_mint`, `interval` (e.g., 'month', 'year').--- [ ] **API for Subscription Plans:**- - [ ] Create CRUD APIs for creators to manage their subscription plans (`/api/agents/:id/subscription-plans`). A creator might offer monthly and yearly tiers.--- [ ] **API for Creating a Subscription:**- - [ ] Create an endpoint `POST /api/subscriptions/create`.- - [ ] This endpoint would interact with a recurring payment provider (e.g., Helio). It would create a payment link or subscription plan with the provider and return it to the frontend.--- [ ] **Webhook for Payment Events:**- - [ ] Create a webhook endpoint `POST /api/webhooks/payments`.- - [ ] The payment provider will call this webhook to notify your app of events like `subscription.created`, `subscription.payment_succeeded`, `subscription.payment_failed`.- - [ ] When a `payment_succeeded` event is received, you should:- - [ ] Find the corresponding subscription in your `agent_subscriptions` table.- - [ ] Update its `status` to 'active'.- - [ ] Set the `expires_at` to the end of the new billing period (e.g., now + 30 days).--- [ ] **Update Skill Gating Logic:**- - [ ] Modify the skill gating logic from Prompt 19.- - [ ] Before checking for individual skill ownership in `unlocked_skills`, it should first check for an active subscription.- - [ ] Query the `agent_subscriptions` table for the `user_id` and `agent_id`. If an active subscription exists (`status` = 'active' and `expires_at` > now), allow skill execution.--## Webhook Logic Example--```javascript-// POST /api/webhooks/payments-export default async function handler(req, res) {- // 1. Verify the webhook signature to ensure it's from the payment provider- if (!isSignatureValid(req)) {- return res.status(403).send('Invalid signature');- }-- const event = req.body;-- // 2. Handle the event- switch (event.type) {- case 'subscription.payment_succeeded':- const subId = event.data.subscription_id;- const newExpiry = new Date(event.data.new_expiry_timestamp);-- // Find subscription in DB by payment_provider_subscription_id- await db.updateSubscriptionStatus(subId, 'active', newExpiry);- break;- case 'subscription.payment_failed':- // ... handle failed payments, maybe set status to 'past_due'- break;- }-- // 3. Acknowledge receipt- res.status(200).send('Acknowledged');-}-```diff --git a/docs/monetization-prompts/22-skill-subscription-model-frontend.md b/docs/monetization-prompts/22-skill-subscription-model-frontend.mddeleted file mode 100644index 0c2f19a36..000000000--- a/docs/monetization-prompts/22-skill-subscription-model-frontend.md+++ /dev/null@@ -1,61 +0,0 @@-----status: not-started------# Prompt 22: Skill Subscription Model - Frontend--## Objective-Create the user interface for users to discover, purchase, and manage subscriptions to agents.--## Explanation-Following the backend setup, the frontend needs to present subscription options to users on the agent detail page and provide a way for them to manage their active subscriptions.--## Instructions-- [ ] **Display Subscription Plans on Agent Page:**- - [ ] On the agent detail page (`marketplace.html`), add a new section for subscriptions.- - [ ] Fetch the agent's available subscription plans from the API (`GET /api/agents/:id/subscription-plans`).- - [ ] Display the plans with their price and billing interval (e.g., "$10 / month").- - [ ] Add a "Subscribe" button for each plan.--- [ ] **Subscription Purchase Flow:**- - [ ] When a user clicks "Subscribe", make a request to the backend `POST /api/subscriptions/create` endpoint.- - [ ] The backend will respond with a URL to the payment provider's checkout page (e.g., a Helio payment link).- - [ ] Redirect the user to this URL to complete the payment and set up the recurring transaction.- - [ ] The payment provider will handle the redirect back to your site.--- [ ] **UI State for Subscribed Users:**- - [ ] When viewing an agent to whom the user is subscribed, the UI should reflect this.- - [ ] Instead of "Subscribe", show "You are Subscribed".- - [ ] All paid skills for that agent should automatically appear as "Unlocked". The skill gating logic on the backend will already handle access.--- [ ] **Subscription Management Page:**- - [ ] Create a new "My Subscriptions" page for logged-in users.- - [ ] This page will list all their active subscriptions.- - [ ] For each subscription, it should show the agent, the price, and the next renewal date.- - [ ] Include a "Manage" or "Cancel" button. This would typically link to the customer portal provided by the payment service (like Helio or Stripe) where users can manage their payment methods and cancellations.--## JavaScript Example (Subscribe Button Click)--```javascript-// On agent detail page, for a "Subscribe" button-subscribeButton.addEventListener('click', async () => {- try {- const response = await fetch('/api/subscriptions/create', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ planId: selectedPlan.id })- });-- if (!response.ok) throw new Error('Could not create subscription.');-- const { checkoutUrl } = await response.json();-- // Redirect user to the payment page- window.location.href = checkoutUrl;-- } catch (error) {- console.error('Subscription failed:', error);- alert('Failed to initiate subscription.');- }-});-```diff --git a/docs/monetization-prompts/22-unit-tests-monetization-service.md b/docs/monetization-prompts/22-unit-tests-monetization-service.mddeleted file mode 100644index f3185ea02..000000000--- a/docs/monetization-prompts/22-unit-tests-monetization-service.md+++ /dev/null@@ -1,71 +0,0 @@-# Prompt 22: Unit Tests for Monetization Service--## Objective-Write unit tests for the `MonetizationService` class to ensure its logic is correct, robust, and reliable.--## Explanation-The `MonetizationService` will contain critical business logic related to user purchases and creator payouts. Unit tests are essential to verify that this logic works as expected, especially for edge cases like insufficient funds or duplicate purchases. This prevents bugs and provides confidence when refactoring.--## Instructions-1. **Set Up Testing Environment:**- * The project appears to use `vitest`. Ensure it's configured to work with your database. You may need a separate test database and a library for mocking database calls (like `pg-mem`).--2. **Create a Test File:**- * Create a new test file: `tests/monetization-service.test.js`.--3. **Write Test Cases for Each Method:**- * Import the `MonetizationService`.- * For each public method in the service, write one or more `it` blocks.- * **Test Scenarios:**- * **`initiatePurchase`:** Test the successful creation of a pending purchase. Test that it fails if the skill is not priced. Test that it fails if the user has already bought the skill.- * **`confirmPurchase`:** Test that a 'pending' purchase moves to 'confirmed'.- * **`requestWithdrawal`:** Test a successful request. Test that it fails if the creator's balance is too low.- * **`gateSkillAccess`:** Test that it returns `true` for free skills, `true` for purchased skills, and `false` for un-purchased paid skills.--4. **Run the Tests:**- * Use the `npm test` command to run the test suite.--## Code Example (`tests/monetization-service.test.js`)--```javascript-import { it, expect, describe, beforeEach } from 'vitest';-import { MonetizationService } from '../api/_lib/monetization-service.js';-// You'll need a way to mock your database, e.g., using an in-memory postgres instance-import { getMockDb } from './test-helpers.js';--describe('MonetizationService', () => {- let service;- let db;-- beforeEach(async () => {- db = await getMockDb(); // Resets the mock db for each test- service = new MonetizationService(db);- // Seed the mock db with necessary data (users, agents, etc.)- });-- it('should initiate a purchase successfully', async () => {- // Setup: create a priced skill in the mock db-- const result = await service.initiatePurchase({- userId: 'user-1',- agentId: 'agent-1',- skillId: 'skill-1'- });-- expect(result.purchaseId).toBeDefined();-- // Verify that a 'pending' record was created in the mock db- const purchase = await db.findPurchaseById(result.purchaseId);- expect(purchase.status).toBe('pending');- });-- it('should fail to request a withdrawal with insufficient funds', async () => {- // Setup: set a creator's balance to 50 in the mock db-- await expect(service.requestWithdrawal({- userId: 'creator-1',- amount: 100- })).rejects.toThrow('Insufficient funds');- });-});-```diff --git a/docs/monetization-prompts/23-e2e-test-purchase-flow.md b/docs/monetization-prompts/23-e2e-test-purchase-flow.mddeleted file mode 100644index 45f5b26e7..000000000--- a/docs/monetization-prompts/23-e2e-test-purchase-flow.md+++ /dev/null@@ -1,65 +0,0 @@-# Prompt 23: E2E Playwright Test for Skill Purchase Flow--## Objective-Create an end-to-end (E2E) test using Playwright that simulates a user purchasing a skill, to ensure the entire flow works correctly from the user's perspective.--## Explanation-While unit tests verify individual pieces of logic, E2E tests validate the complete user journey. This test will automate a browser to navigate the marketplace, click a "Buy" button, and verify that the UI updates correctly after a simulated successful purchase. This is the highest level of automated testing and catches integration issues between frontend and backend.--## Instructions-1. **Set Up Playwright:**- * Ensure Playwright is installed (`npm install -D @playwright/test`).- * The project may already have a `tests/e2e` directory.--2. **Create a New Test File:**- * Create `tests/e2e/monetization.spec.js`.--3. **Write the Test Script:**- * **Setup:** Before the test, you'll need to seed your test database with a user, an agent, and a priced skill.- * **Test Steps:**- 1. **Login:** Programmatically log in as the test user.- 2. **Navigate:** Go to the marketplace and find the agent's detail page.- 3. **Find the Skill:** Locate the priced skill and the "Buy" button.- 4. **Click Buy:** Click the button to open the purchase modal.- 5. **Assert Modal:** Verify that the QR code modal is visible.- 6. **Simulate Confirmation:** Since we can't scan a QR code in a test, we need a way to bypass it. You can either:- * Make a direct API call to a special test-only endpoint that confirms the purchase.- * Have the frontend polling check a mock endpoint during tests.- 7. **Assert UI Update:** After the simulated confirmation, verify that the "Buy" button is replaced by an "Owned" badge on the page.--## Code Example (`tests/e2e/monetization.spec.js`)--```javascript-import { test, expect } from '@playwright/test';--test.describe('Skill Purchase Flow', () => {- test.beforeEach(async ({ page }) => {- // 1. Programmatically log in the user- await page.goto('/login');- // ... fill in login form ...- });-- test('should allow a user to purchase a skill and see the UI update', async ({ page }) => {- // 2. Navigate to the agent's page- await page.goto('/marketplace/agents/test-agent-with-paid-skill');-- // 3. Find and click the buy button- const buyButton = page.locator('[data-skill-id="test-skill"] .btn-buy');- await expect(buyButton).toBeVisible();- await buyButton.click();-- // 4. Assert that the purchase modal appears- await expect(page.locator('#purchase-modal')).toBeVisible();-- // 5. Simulate the purchase confirmation (e.g., by calling a test API)- await page.request.post('/api/testing/confirm-purchase', {- data: { userId: 'test-user', skillId: 'test-skill' }- });-- // 6. Assert that the UI updates to "Owned"- const ownedBadge = page.locator('[data-skill-id="test-skill"] .badge.owned');- await expect(ownedBadge).toBeVisible({ timeout: 10000 }); // Wait for polling- await expect(buyButton).not.toBeVisible();- });-});-```diff --git a/docs/monetization-prompts/23-email-receipts.md b/docs/monetization-prompts/23-email-receipts.mddeleted file mode 100644index 492be2f47..000000000--- a/docs/monetization-prompts/23-email-receipts.md+++ /dev/null@@ -1,70 +0,0 @@-----status: not-started------# Prompt 23: Email Receipts and Notifications--## Objective-Integrate an email service to send users receipts for their purchases and notifications for subscription events.--## Explanation-Professional platforms communicate with users via email for important events. Sending a receipt after a purchase confirms the transaction and provides a record for the user. Email notifications are also crucial for managing subscriptions.--## Instructions-- [ ] **Choose and Integrate an Email Service Provider:**- - [ ] Sign up for a transactional email service like SendGrid, Postmark, or Resend.- - [ ] Obtain an API key and configure it securely on your backend (using environment variables).- - [ ] Install the provider's SDK in your backend service.--- [ ] **Send One-Time Purchase Receipts:**- - [ ] In your backend's transaction verification endpoint (`/api/skills/purchase/verify`), after successfully recording the skill ownership:- - [ ] Call a new function, e.g., `sendPurchaseReceiptEmail`.- - [ ] This function should use the email service's SDK to send an email to the user.- - [ ] The email should be based on a template and include details like the user's name, skill name, agent name, price paid, and transaction signature.--- [ ] **Send Subscription-Related Emails:**- - [ ] In your payments webhook (`/api/webhooks/payments`), trigger emails for key events:- - [ ] **`subscription.created`**: Send a "Welcome" email confirming the subscription start.- - [ ] **`subscription.payment_succeeded`**: Send a monthly/yearly receipt for the renewal payment.- - [ ] **`subscription.payment_failed`**: Send a notification that the payment failed and they need to update their payment information.- - [ ] **Upcoming Renewal Reminder**: Set up a scheduled job (e.g., a cron job) that runs daily to find subscriptions expiring in a few days and send a reminder email.--## Code Example (Sending a receipt with Resend)--```javascript-// utils/email.js-import { Resend } from 'resend';--const resend = new Resend(process.env.RESEND_API_KEY);--export async function sendPurchaseReceiptEmail(user, purchaseDetails) {- try {- await resend.emails.send({- from: 'Your App <[email protected]>',- to: user.email,- subject: 'Your Skill Purchase Receipt',- html: `- <h1>Receipt</h1>- <p>Hi ${user.name},</p>- <p>Thank you for purchasing the skill: <strong>${purchaseDetails.skillName}</strong>.</p>- <p>Price: ${purchaseDetails.price} USDC</p>- <p>Transaction: ${purchaseDetails.signature}</p>- `,- });- } catch (error) {- console.error('Failed to send email:', error);- }-}---// In the /api/skills/purchase/verify endpoint after success-import { sendPurchaseReceiptEmail } from 'utils/email';--// ...-if (isVerified) {- await recordSkillOwnership(...);- await sendPurchaseReceiptEmail(req.user, { ... }); // Fire-and-forget- res.status(200).json({ message: "Verification successful." });-}-// ...-```diff --git a/docs/monetization-prompts/24-admin-monetization-dashboard.md b/docs/monetization-prompts/24-admin-monetization-dashboard.mddeleted file mode 100644index 79b20cde8..000000000--- a/docs/monetization-prompts/24-admin-monetization-dashboard.md+++ /dev/null@@ -1,66 +0,0 @@-----status: not-started------# Prompt 24: Admin Monetization Dashboard--## Objective-Create a secure, internal dashboard for platform administrators to monitor the health and performance of the entire marketplace economy.--## Explanation-While creators have their own dashboards, platform admins need a high-level view to understand overall trends, spot potential issues, and manage the ecosystem. This is an internal tool, not for public users.--## Instructions-- [ ] **Create a Secure Admin Area:**- - [ ] Build a new section of the application that is only accessible to users with an 'admin' role. This requires role-based access control (RBAC) in your user authentication system.--- [ ] **Backend API for Admin Stats:**- - [ ] Create a new set of protected API endpoints, e.g., under `/api/admin/stats/`.- - [ ] These endpoints will perform platform-wide aggregations.- - [ ] **Key metrics to expose:**- - [ ] **Gross Transaction Volume (GTV):** Total value of all transactions processed.- - [ ] **Platform Revenue:** Total fees collected by the platform.- - [ ] **Top Earning Creators:** A list of creators ranked by their total earnings.- - [ ] **Top Selling Skills/Agents:** A list of the most purchased skills and agents.- - [ ] **New Subscriptions/Cancellations:** A time-series chart showing subscription growth.--- [ ] **Frontend UI for Admin Dashboard:**- - [ ] Create a new UI for the admin area.- - [ ] Use data visualization components (charts, tables, stat cards) to present the data fetched from the admin APIs.- - [ ] The UI should allow filtering by date ranges to analyze performance over time.--- [ ] **Add Management Tools (Advanced):**- - [ ] Beyond just viewing data, an admin dashboard can include tools for:- - [ ] **Refunding a purchase:** A button to trigger a refund process (this is complex and involves on-chain transactions and database updates).- - [ ] **Disabling a skill from sale:** A toggle to remove a problematic skill from the marketplace.- - [ ] **Managing user roles.**--## Admin API Response Example (`/api/admin/stats/overview`)--```json-{- "dateRange": {- "start": "2026-01-01T00:00:00.000Z",- "end": "2026-05-04T23:59:59.999Z"- },- "grossTransactionVolume": 12500000000,- "platformRevenue": 625000000,- "activeSubscriptions": 1240,- "newUsers": 5300-}-```--## Database Query Example (PostgreSQL for GTV)--```sql--- Calculates Gross Transaction Volume and Platform Revenue between two dates-SELECT- SUM(prices.amount) AS gross_transaction_volume,- SUM(prices.amount * 0.05) AS platform_revenue -- Assuming 5% fee-FROM- unlocked_skills AS unlocked-JOIN- agent_skill_prices AS prices ON unlocked.agent_id = prices.agent_id AND unlocked.skill_name = prices.skill_name-WHERE- unlocked.created_at BETWEEN $1 AND $2; -- $1 and $2 are date range parameters-```diff --git a/docs/monetization-prompts/24-analytics-and-tracking.md b/docs/monetization-prompts/24-analytics-and-tracking.mddeleted file mode 100644index 95985d9fa..000000000--- a/docs/monetization-prompts/24-analytics-and-tracking.md+++ /dev/null@@ -1,57 +0,0 @@-# Prompt 24: Add Analytics and Tracking for Monetization--## Objective-Integrate analytics events to track key user actions in the monetization funnel, such as viewing a paid skill, starting a purchase, and completing a purchase.--## Explanation-To understand user behavior and optimize the monetization feature, we need data. By firing analytics events at each step of the purchase flow, we can build funnels in analytics tools (like Google Analytics, Vercel Analytics, or PostHog) to see where users drop off and identify areas for improvement.--## Instructions-1. **Choose an Analytics Provider:**- * If the project doesn't already have one, select an analytics provider. Let's assume Vercel Analytics is being used.--2. **Create a Tracking Utility:**- * In a frontend utility file (e.g., `src/analytics.js`), create a simple wrapper function for sending events. This makes it easy to swap providers later.-- ```javascript- // src/analytics.js- import { track } from '@vercel/analytics';-- export function trackEvent(name, properties) {- try {- track(name, properties);- } catch (e) {- console.warn('Analytics tracking failed', e);- }- }- ```--3. **Instrument the Frontend Code:**- * Import and call `trackEvent` at key moments:- * **View Agent with Priced Skill:** In `src/marketplace.js`, when `renderDetail` is called for an agent with paid skills.- * `trackEvent('ViewPricedSkill', { agentId, skillId, price });`- * **Click "Buy" Button:** In the `onBuySkill` event handler.- * `trackEvent('StartPurchase', { agentId, skillId });`- * **Purchase Succeeded:** In the `onPurchaseSuccess` callback after polling confirms the purchase.- * `trackEvent('CompletePurchase', { agentId, skillId, price });`- * **Purchase Failed/Cancelled:** If the user closes the modal or the polling times out.- * `trackEvent('CancelPurchase', { agentId, skillId });`--## Example Integration--```javascript-// In src/marketplace.js-import { trackEvent } from './analytics.js';--// When "Buy" is clicked-function onBuySkill(agentId, skillId) {- trackEvent('StartPurchase', { agentId, skillId });- // ... rest of the function-}--// When purchase is confirmed-function onPurchaseSuccess(skillId) {- trackEvent('CompletePurchase', { skillId });- // ... rest of the function-}-```diff --git a/docs/monetization-prompts/25-update-documentation.md b/docs/monetization-prompts/25-update-documentation.mddeleted file mode 100644index fb6cd22a7..000000000--- a/docs/monetization-prompts/25-update-documentation.md+++ /dev/null@@ -1,41 +0,0 @@-# Prompt 25: Update Documentation for Monetization Feature--## Objective-Update the project's main `README.md` and create a new document in `docs/` to explain the skill monetization feature to both users and new developers.--## Explanation-A feature is not complete until it's documented. We need to explain how the monetization system works, how creators can sell their skills, and how users can buy them. This makes the feature discoverable and understandable.--## Instructions-1. **Create a New Monetization Document:**- * Create a new file: `docs/monetization.md`.- * In this file, provide a detailed overview of the feature:- * **For Creators:** Explain how to set a price for a skill, the fee structure (if any), and how to withdraw earnings.- * **For Users:** Explain how to buy skills, what on-chain ownership means (if NFTs are implemented), and where to view their purchases.- * **Technical Details:** Briefly describe the Solana Pay integration and the role of the database tables.--2. **Update the Main `README.md`:**- * Open `README.md`.- * Add a new section, perhaps under "Key Features", titled "Skill Monetization".- * Write a brief, exciting paragraph summarizing the feature.- * Link to the new `docs/monetization.md` file for more details.--3. **Update Table of Contents:**- * Add "Skill Monetization" to the table of contents in the `README.md`.--## Example Text for `README.md`--```markdown------## Key Features--...--**Skill Monetization**-Creators can now earn revenue by selling their custom agent skills directly in the marketplace. Using a seamless Solana Pay integration, users can purchase skills with USDC, unlocking new capabilities for their agents. This creates a vibrant economy where developers are rewarded for building powerful extensions to the 3D-Agent ecosystem. [Learn more in our monetization guide...](docs/monetization.md)--...------```diff --git a/docs/monetization-prompts/25-user-experience-onboarding.md b/docs/monetization-prompts/25-user-experience-onboarding.mddeleted file mode 100644index 3fcce46ae..000000000--- a/docs/monetization-prompts/25-user-experience-onboarding.md+++ /dev/null@@ -1,63 +0,0 @@-----status: not-started------# Prompt 25: User Experience & Onboarding--## Objective-Refine the overall user experience for the monetization features and create clear onboarding materials for creators.--## Explanation-A powerful system is only effective if people understand how to use it. This final step focuses on documentation, in-app guidance, and polishing the user interface to make the monetization features intuitive for both buyers and sellers.--## Instructions-- [ ] **Create a Creator Onboarding Guide:**- - [ ] Write a clear, concise guide in your `docs` folder that explains how a creator can start monetizing their skills.- - [ ] **Topics to cover:**- - [ ] How to set up their payout wallet.- - [ ] How to set prices for their skills.- - [ ] How subscriptions work.- - [ ] An explanation of the platform fee.- - [ ] A link to their creator dashboard and an explanation of the metrics.--- [ ] **Add In-App Guidance (Tooltips & Helpers):**- - [ ] Go through the creator-facing UIs (payout settings, skill pricing) and add tooltips or helper text to explain complex concepts.- - [ ] For example, next to the payout wallet input, add a tooltip explaining what a Solana wallet is and where to get one.- - [ ] On the skill pricing page, explain the units (e.g., "Enter price in USDC").--- [ ] **Refine the Buyer Experience:**- - [ ] Review the entire purchase flow from the buyer's perspective. Is it clear and smooth?- - [ ] Ensure error messages are helpful. Instead of a generic "Transaction Failed", provide more context if possible (e.g., "Transaction failed. You may not have enough USDC in your wallet.").- - [ ] Add a section to the user's profile where they can see a history of all the skills they've purchased.--- [ ] **Create a Marketing/Landing Page:**- - [ ] Design a section on your main landing page that advertises the new creator monetization features.- - [ ] Highlight the benefits for creators (earn revenue) and for users (access powerful new capabilities).- - [ ] This will help attract new creators to your platform.--## Example: Onboarding Doc Snippet (`/docs/monetizing-your-agent.md`)--```markdown-----title: Monetizing Your Agent------## Introduction--Welcome to the creator monetization program! This guide will walk you through setting up your account to sell your agent's skills on the marketplace.--### Step 1: Set Up Your Payout Wallet--Before you can earn, you need to tell us where to send your funds.--1. Navigate to your **Settings > Payouts** page.-2. You will need a Solana wallet. If you don't have one, we recommend Phantom or Solflare.-3. Copy your public wallet address and paste it into the "Payout Wallet Address" field.-4. Click "Save". All your earnings will now be sent to this address.--**Important**: Double-check this address. Payments sent to an incorrect address are irreversible.--### Step 2: Pricing Your Skills--...-```