Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: Implement revenue stats API and UI for creators to view earnings
nirholasef0ff34df3a0
diff --git a/api/agents.js b/api/agents.jsindex 28ab6a6b9..0f13b4b4c 100644--- a/api/agents.js+++ b/api/agents.js@@ -187,6 +187,15 @@ export async function handleGetOne(req, res, id) {`;if (!row) return error(res, 404, 'not_found', 'agent not found');+ const prices = await sql`+ SELECT skill, amount, currency_mint FROM agent_skill_prices WHERE agent_id = ${id}+ `;+ const skill_prices = prices.reduce((acc, p) => {+ acc[p.skill] = { amount: p.amount, currency_mint: p.currency_mint };+ return acc;+ }, {});+ row.skill_prices = skill_prices;+await healStaleAvatarId(row);// Public fields if not owner; full record if ownerdiff --git a/docs/monetization-prompts/01-display-priced-skills.md b/docs/monetization-prompts/01-display-priced-skills.mdnew file mode 100644index 000000000..83cdb6daf--- /dev/null+++ b/docs/monetization-prompts/01-display-priced-skills.md@@ -0,0 +1,68 @@+# 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-database-schema-skill-prices.md b/docs/monetization-prompts/02-database-schema-skill-prices.mdnew file mode 100644index 000000000..e4e7ca435--- /dev/null+++ b/docs/monetization-prompts/02-database-schema-skill-prices.md@@ -0,0 +1,49 @@+# 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/03-creator-api-set-skill-prices.md b/docs/monetization-prompts/03-creator-api-set-skill-prices.mdnew file mode 100644index 000000000..2f8017bfb--- /dev/null+++ b/docs/monetization-prompts/03-creator-api-set-skill-prices.md@@ -0,0 +1,68 @@+# 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/04-database-schema-user-purchases.md b/docs/monetization-prompts/04-database-schema-user-purchases.mdnew file mode 100644index 000000000..36eda9ea9--- /dev/null+++ b/docs/monetization-prompts/04-database-schema-user-purchases.md@@ -0,0 +1,52 @@+# 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/05-api-initiate-purchase.md b/docs/monetization-prompts/05-api-initiate-purchase.mdnew file mode 100644index 000000000..9807f7792--- /dev/null+++ b/docs/monetization-prompts/05-api-initiate-purchase.md@@ -0,0 +1,74 @@+# 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-spl-token-transfer.md b/docs/monetization-prompts/05-spl-token-transfer.mdnew file mode 100644index 000000000..53ed602b6--- /dev/null+++ b/docs/monetization-prompts/05-spl-token-transfer.md@@ -0,0 +1,79 @@+# 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.mdnew file mode 100644index 000000000..1058faee7--- /dev/null+++ b/docs/monetization-prompts/06-backend-purchase-endpoint.md@@ -0,0 +1,79 @@+# 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.mdnew file mode 100644index 000000000..b383697f4--- /dev/null+++ b/docs/monetization-prompts/06-frontend-solana-pay-qr-code.md@@ -0,0 +1,63 @@+# 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/07-api-webhook-confirm-purchase.md b/docs/monetization-prompts/07-api-webhook-confirm-purchase.mdnew file mode 100644index 000000000..8e2a3f895--- /dev/null+++ b/docs/monetization-prompts/07-api-webhook-confirm-purchase.md@@ -0,0 +1,72 @@+# 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.mdnew file mode 100644index 000000000..035b10aa0--- /dev/null+++ b/docs/monetization-prompts/07-ui-feedback-on-purchase.md@@ -0,0 +1,72 @@+# Prompt 7: Update UI with Purchase Status (Loading, Success, Error)++**Status:** - [ ] Not Started++## Objective+Provide real-time feedback to the user during and after the purchase process by updating the UI to show loading, success, and error states.++## Explanation+A good user experience requires clear communication about the status of an action. After a user confirms a purchase, they should see a loading indicator. Once the transaction is processed and verified, the UI should update to show either a success message and reflect the new ownership status, or an error message if something went wrong.++## Instructions+1. **Add Loading State:**+ * In `src/marketplace.js`, when the "Confirm Purchase" button is clicked, disable the button and show a loading indicator within the modal.++2. **Handle Success State:**+ * After the backend verification endpoint returns a success response:+ * Close the purchase modal.+ * Re-render the skills list for the agent, or dynamically update the specific skill entry that was just purchased. It should now show the "Owned" badge instead of the "Purchase" button.+ * Show a success toast message (e.g., "Purchase successful!").++3. **Handle Error State:**+ * If the Solana transaction fails on the client-side, or if the backend verification endpoint returns an error:+ * Display a clear error message to the user, either in the modal or as a toast.+ * Re-enable the "Confirm Purchase" button so the user can try again.++## Code Example (JavaScript in `src/marketplace.js`)++```javascript+// Inside the 'click' event listener for modal-confirm-purchase-btn+const confirmBtn = $('modal-confirm-purchase-btn');++confirmBtn.disabled = true;+confirmBtn.textContent = 'Processing...';++try {+ // 1. Send Solana Transaction+ const signature = await wallet.sendTransaction(transaction, connection);+ await connection.confirmTransaction(signature, 'processed');++ // 2. Call Backend for Verification+ const response = await fetch('/api/marketplace/purchase-skill', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ agentId, skillName, transactionSignature: signature }),+ });++ if (!response.ok) {+ throw new Error('Backend verification failed.');+ }++ // 3. Handle Success+ showToast('Purchase successful!', 'success');+ purchaseModal.style.display = 'none';+ // You would need to re-fetch the user's skills and re-render the detail view+ // to show the 'Owned' status.+ // For simplicity, we can just reload the agent details.+ const agentId = window.currentAgent.id;+ loadAgentDetail(agentId);++} catch (error) {+ // 4. Handle Error+ console.error('Purchase failed:', error);+ showToast(`Purchase failed: ${error.message}`, 'error');+ confirmBtn.disabled = false;+ confirmBtn.textContent = 'Confirm Purchase';+}++// A simple toast function+function showToast(message, type = 'info') {+ // Implementation of a toast notification system+}+```diff --git a/docs/monetization-prompts/08-creator-ui-set-prices.md b/docs/monetization-prompts/08-creator-ui-set-prices.mdnew file mode 100644index 000000000..37995ced6--- /dev/null+++ b/docs/monetization-prompts/08-creator-ui-set-prices.md@@ -0,0 +1,50 @@+# 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.mdnew file mode 100644index 000000000..83ced80c6--- /dev/null+++ b/docs/monetization-prompts/08-database-schema-for-pricing.md@@ -0,0 +1,69 @@+# 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/09-admin-interface-for-prices.md b/docs/monetization-prompts/09-admin-interface-for-prices.mdnew file mode 100644index 000000000..7a2ae97ef--- /dev/null+++ b/docs/monetization-prompts/09-admin-interface-for-prices.md@@ -0,0 +1,92 @@+# 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.mdnew file mode 100644index 000000000..bd122331b--- /dev/null+++ b/docs/monetization-prompts/09-frontend-polling-confirmation.md@@ -0,0 +1,55 @@+# 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/10-creator-dashboard-earnings-ui.md b/docs/monetization-prompts/10-creator-dashboard-earnings-ui.mdnew file mode 100644index 000000000..e799147c5--- /dev/null+++ b/docs/monetization-prompts/10-creator-dashboard-earnings-ui.md@@ -0,0 +1,67 @@+# 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/11-api-creator-earnings.md b/docs/monetization-prompts/11-api-creator-earnings.mdnew file mode 100644index 000000000..14782cd21--- /dev/null+++ b/docs/monetization-prompts/11-api-creator-earnings.md@@ -0,0 +1,75 @@+# 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/12-backend-gate-skill-usage.md b/docs/monetization-prompts/12-backend-gate-skill-usage.mdnew file mode 100644index 000000000..7567c9834--- /dev/null+++ b/docs/monetization-prompts/12-backend-gate-skill-usage.md@@ -0,0 +1,58 @@+# 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/13-frontend-buy-skill-button.md b/docs/monetization-prompts/13-frontend-buy-skill-button.mdnew file mode 100644index 000000000..920850e05--- /dev/null+++ b/docs/monetization-prompts/13-frontend-buy-skill-button.md@@ -0,0 +1,53 @@+# 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/14-frontend-ui-update-post-purchase.md b/docs/monetization-prompts/14-frontend-ui-update-post-purchase.mdnew file mode 100644index 000000000..689bffa24--- /dev/null+++ b/docs/monetization-prompts/14-frontend-ui-update-post-purchase.md@@ -0,0 +1,59 @@+# 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/15-user-dashboard-purchased-skills.md b/docs/monetization-prompts/15-user-dashboard-purchased-skills.mdnew file mode 100644index 000000000..0ab6774ec--- /dev/null+++ b/docs/monetization-prompts/15-user-dashboard-purchased-skills.md@@ -0,0 +1,49 @@+# 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.mdnew file mode 100644index 000000000..767349e6a--- /dev/null+++ b/docs/monetization-prompts/16-on-chain-nft-license.md@@ -0,0 +1,32 @@+# 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/17-database-schema-creator-payouts.md b/docs/monetization-prompts/17-database-schema-creator-payouts.mdnew file mode 100644index 000000000..ebbf599d6--- /dev/null+++ b/docs/monetization-prompts/17-database-schema-creator-payouts.md@@ -0,0 +1,60 @@+# 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.mdnew file mode 100644index 000000000..24818514b--- /dev/null+++ b/docs/monetization-prompts/18-api-creator-withdrawal.md@@ -0,0 +1,69 @@+# 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/19-worker-payout-processing.md b/docs/monetization-prompts/19-worker-payout-processing.mdnew file mode 100644index 000000000..f8d34be36--- /dev/null+++ b/docs/monetization-prompts/19-worker-payout-processing.md@@ -0,0 +1,40 @@+# 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-email-notifications.md b/docs/monetization-prompts/20-email-notifications.mdnew file mode 100644index 000000000..8d9ed6cdd--- /dev/null+++ b/docs/monetization-prompts/20-email-notifications.md@@ -0,0 +1,52 @@+# 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/21-refactor-monetization-service.md b/docs/monetization-prompts/21-refactor-monetization-service.mdnew file mode 100644index 000000000..628c330f7--- /dev/null+++ b/docs/monetization-prompts/21-refactor-monetization-service.md@@ -0,0 +1,64 @@+# 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/22-unit-tests-monetization-service.md b/docs/monetization-prompts/22-unit-tests-monetization-service.mdnew file mode 100644index 000000000..f3185ea02--- /dev/null+++ b/docs/monetization-prompts/22-unit-tests-monetization-service.md@@ -0,0 +1,71 @@+# 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.mdnew file mode 100644index 000000000..45f5b26e7--- /dev/null+++ b/docs/monetization-prompts/23-e2e-test-purchase-flow.md@@ -0,0 +1,65 @@+# 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/24-analytics-and-tracking.md b/docs/monetization-prompts/24-analytics-and-tracking.mdnew file mode 100644index 000000000..95985d9fa--- /dev/null+++ b/docs/monetization-prompts/24-analytics-and-tracking.md@@ -0,0 +1,57 @@+# 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.mdnew file mode 100644index 000000000..fb6cd22a7--- /dev/null+++ b/docs/monetization-prompts/25-update-documentation.md@@ -0,0 +1,41 @@+# 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/02-skill-purchase-button.md b/docs/monetization/02-skill-purchase-button.mdnew file mode 100644index 000000000..980daf83a--- /dev/null+++ b/docs/monetization/02-skill-purchase-button.md@@ -0,0 +1,55 @@+# Prompt 2: Add Purchase Button for Paid Skills++## Objective+Add an "Unlock" or "Purchase" button next to paid skills on the agent detail page in the marketplace.++## Explanation+With prices now visible, the next logical step is to provide a clear call-to-action for users to initiate a purchase. This button will be the entry point into the skill acquisition flow.++## Instructions+1. **Update Frontend UI (`src/marketplace.js`):**+ * In the `renderDetail` function, modify the loop that renders each skill.+ * For skills that have a price, render a `<button>` element next to the price badge.+ * The button should be labeled "Unlock" or "Purchase."+ * Assign a `data-skill-name` attribute to the button, containing the name of the skill, to identify it in event listeners.+ * Attach a click event listener to these buttons. For now, this listener can log to the console. It will be wired up to open a purchase modal in a later step.++2. **Add CSS for the Button:**+ * In `/marketplace.css`, add styling for the new purchase button to make it visually distinct and interactive.++## Code Example (Frontend - `src/marketplace.js`)+```javascript+// Inside renderDetail's map function for skills...+const skillPrices = a.skill_prices || {};+const name = typeof s === 'string' ? s : (s.name || '');+const price = skillPrices[name];+let badge;+let actionButton = '';++if (price) {+ badge = `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`;+ actionButton = `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}">Unlock</button>`;+} else {+ badge = `<span class="price-badge price-free">Free</span>`;+}+return `<span class="skill-entry">${escapeHtml(name)}${badge}${actionButton}</span>`;+```++## CSS Example (`/marketplace.css`)+```css+.purchase-btn {+ margin-left: 8px;+ padding: 4px 10px;+ background-color: #4f46e5;+ color: white;+ border: none;+ border-radius: 4px;+ cursor: pointer;+ font-size: 12px;+ font-weight: 600;+ transition: background-color 0.2s;+}+.purchase-btn:hover {+ background-color: #4338ca;+}+```diff --git a/docs/monetization/03-purchase-flow-ui.md b/docs/monetization/03-purchase-flow-ui.mdnew file mode 100644index 000000000..13d55fe60--- /dev/null+++ b/docs/monetization/03-purchase-flow-ui.md@@ -0,0 +1,63 @@+# Prompt 3: Implement Purchase Flow UI Modal++## Objective+Create a modal dialog that appears when a user clicks the "Unlock" button for a paid skill, presenting the details of the purchase and asking for confirmation.++## Explanation+A modal is a standard and effective way to handle a confirmation flow without navigating the user away from the current page. This modal will serve as the main interface for the skill purchase process, containing all necessary information for the user to make a decision.++## Instructions+1. **Create Modal HTML:**+ * In `marketplace.html`, add the HTML structure for a hidden modal.+ * The modal should include a title, a section to display the skill name and price, a "Confirm Purchase" button, and a "Cancel" button or close icon.++2. **Implement Modal Logic (`src/marketplace.js`):**+ * Create functions to `showModal()` and `hideModal()`.+ * Modify the event listener for the `.purchase-btn` clicks.+ * When a purchase button is clicked, extract the skill name and price from the agent data.+ * Populate the modal with the specific skill's details.+ * Call `showModal()` to display it.+ * Add event listeners to the "Cancel" and "Confirm Purchase" buttons within the modal.++## Code Example (HTML - `marketplace.html`)+```html+<!-- Add this inside the <body> tag -->+<div id="purchase-modal" class="modal-hidden">+ <div class="modal-content">+ <span class="close-button">×</span>+ <h2>Unlock Skill</h2>+ <p>You are about to purchase:</p>+ <p><strong>Skill:</strong> <span id="modal-skill-name"></span></p>+ <p><strong>Price:</strong> <span id="modal-skill-price"></span></p>+ <button id="modal-confirm-purchase">Confirm Purchase</button>+ </div>+</div>+```++## Code Example (JavaScript - `src/marketplace.js`)+```javascript+// Add event listener for purchase buttons (delegated)+document.addEventListener('click', (e) => {+ if (e.target.matches('.purchase-btn')) {+ const skillName = e.target.dataset.skillName;+ const agent = getCurrentAgentData(); // Assume this function gets the current agent's full data+ const price = agent.skill_prices[skillName];++ // Populate and show the modal+ document.getElementById('modal-skill-name').textContent = skillName;+ document.getElementById('modal-skill-price').textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;+ document.getElementById('purchase-modal').classList.remove('modal-hidden');+ }+});++// Logic to hide modal+document.querySelector('.close-button').addEventListener('click', () => {+ document.getElementById('purchase-modal').classList.add('modal-hidden');+});+```++## CSS Example (`/marketplace.css`)+```css+.modal-hidden { display: none; }+/* Add styles for modal backdrop, content, etc. */+```diff --git a/docs/monetization/04-connect-wallet-integration.md b/docs/monetization/04-connect-wallet-integration.mdnew file mode 100644index 000000000..c07fe9e75--- /dev/null+++ b/docs/monetization/04-connect-wallet-integration.md@@ -0,0 +1,48 @@+# Prompt 4: Wallet Integration for Payments++## Objective+Integrate a Solana wallet adapter to allow users to connect their crypto wallets to the platform, a prerequisite for making payments.++## Explanation+To interact with the Solana blockchain for payments, users must first connect their own wallet (like Phantom, Solflare, etc.). We will use the official Solana Wallet Adapter libraries to provide a standardized, user-friendly way for users to connect.++## Instructions+1. **Add Dependencies:**+ * Install the necessary Solana Wallet Adapter packages (`@solana/wallet-adapter-base`, `@solana/wallet-adapter-react`, `@solana/wallet-adapter-wallets`, etc., and their peer dependencies like `@solana/web3.js`).+ * This might require refactoring parts of the frontend into a framework like React if not already done, or using the adapter with vanilla JS. For this prompt, assume a vanilla JS setup is possible.++2. **Initialize Wallet Adapter:**+ * In a core JavaScript file (e.g., `src/app.js` or `src/wallet.js`), import and initialize the wallet adapter providers.+ * Create a "Connect Wallet" button in the main UI (e.g., the header).++3. **Implement Connect/Disconnect Logic:**+ * When the "Connect Wallet" button is clicked, present the user with a list of available wallets.+ * Once a wallet is selected and approved by the user, the application should store the connection state and public key.+ * The UI should update to show the user's connected wallet address and change the button to "Disconnect."++## Code Example (JavaScript - `src/wallet.js`)+```javascript+// This is a simplified example. Refer to official @solana/wallet-adapter docs for a full implementation.+import { Connection, PublicKey } from '@solana/web3.js';+import { WalletAdapter, PhantomWalletAdapter } from '@solana/wallet-adapter-wallets';++// Setup+const connection = new Connection('https://api.mainnet-beta.solana.com');+const wallets = [new PhantomWalletAdapter()];++let wallet;++// UI Connection+document.getElementById('connect-wallet-btn').addEventListener('click', async () => {+ const selectedWallet = await showWalletChoice(); // UI function to let user pick from `wallets`+ wallet = selectedWallet;+ await wallet.connect();+ console.log('Wallet connected:', wallet.publicKey.toBase58());+ updateUIForConnectedState(wallet.publicKey);+});++wallet.on('connect', (publicKey) => {+ console.log('Connected to ' + publicKey.toBase58());+});+```+This is a complex task. The prompt provides the user with the high-level steps and concepts, guiding them through the official documentation.diff --git a/docs/monetization/05-creator-ui-for-pricing.md b/docs/monetization/05-creator-ui-for-pricing.mdnew file mode 100644index 000000000..04fd964a1--- /dev/null+++ b/docs/monetization/05-creator-ui-for-pricing.md@@ -0,0 +1,97 @@+---+status: not-started+completed_at: null+---+# Prompt 5: Creator Dashboard UI for Pricing Skills++## Objective+Create a user interface in the Creator Dashboard that allows an agent creator to view their agent's skills and set prices for them.++## Explanation+To enable creators to monetize their work, they need a simple and intuitive interface. This task involves building a new section in the agent editing page of the Creator Dashboard. This section will list all of the agent's skills and provide input fields for creators to set a price for each one. The interface will use the API created in Prompt #3 to save these prices.++## Instructions+1. **Locate the Creator Dashboard Page:**+ * Find the HTML file for the agent editor in the Creator Dashboard (e.g., `agent-edit.html`).++2. **Create the Skill Pricing Section:**+ * Add a new section to the page titled "Skill Monetization" or "Skill Pricing".+ * This section should only be visible to the agent's owner.+ * Fetch the agent's details, including their list of skills and any existing `skill_prices`.++3. **Render the Skill List:**+ * Iterate through the agent's skills. For each skill, render:+ * The skill name (read-only).+ * An input field for the `amount`.+ * A dropdown/select for the `currency_mint` (initially, this can be hardcoded to just show USDC, but it should be designed to be extensible).+ * A "Save" or "Update" button for each skill.+ * A "Make Free" or "Remove Price" button.++4. **Implement the API Interaction:**+ * When the creator clicks "Save", make a `POST` request to the `/api/creator/agents/:agentId/skills/price` endpoint.+ * The request body should include the `skill_name`, `amount` (converted to the smallest unit), and `currency_mint`.+ * When the "Make Free" button is clicked, make a similar `POST` request, but set the `amount` to `0` or `null`.+ * Provide feedback to the user on success (e.g., a "Saved!" message) or failure (e.g., an error message).+ * Use a debounce on the input fields to prevent excessive API calls if you choose to save on input change.++## UI Mockup Idea++```++------------------------------------------------------++| Skill Pricing |++------------------------------------------------------++| |+| translate [ 1.00 ] [ USDC ▼ ] [ Save ] |+| |+| summarize-document [ 0.00 ] [ USDC ▼ ] [ Set Price ] |+| |+| generate-image [ 5.00 ] [ USDC ▼ ] [ Save ] [ Make Free ] |+| |++------------------------------------------------------++```++## Code Example (Frontend JavaScript)++```javascript+// This is a conceptual example for the event handling++async function saveSkillPrice(agentId, skillName, amount, currency) {+ // Note: Convert amount to smallest unit, e.g., amount * 1e6 for USDC+ const amountInSmallestUnit = Math.round(parseFloat(amount) * 1e6);++ const response = await fetch(`/api/creator/agents/${agentId}/skills/price`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ skill_name: skillName,+ amount: amountInSmallestUnit,+ currency_mint: currency,+ }),+ });++ if (response.ok) {+ // Show success feedback+ console.log(`Price for ${skillName} saved successfully!`);+ } else {+ // Show error feedback+ const err = await response.json();+ console.error(`Failed to save price:`, err.error);+ }+}++// Attach this function to the 'click' event of the save buttons+// e.g., saveButton.addEventListener('click', () => {+// const amount = amountInput.value;+// const currency = currencySelect.value;+// saveSkillPrice('agent-123', 'translate', amount, currency);+// });+```++## Definition of Done+- A new "Skill Pricing" section is visible on the agent editing page for agent owners.+- The section lists all the agent's skills.+- Each skill has corresponding input fields for price and currency.+- The "Save" button correctly calls the API to set/update the price.+- The "Make Free" button correctly calls the API to remove the price.+- The UI provides clear feedback to the user upon success or failure of the operation.+- Existing prices are correctly populated into the input fields when the page loads.diff --git a/docs/monetization/05-initiate-solana-transaction.md b/docs/monetization/05-initiate-solana-transaction.mdnew file mode 100644index 000000000..aebe08381--- /dev/null+++ b/docs/monetization/05-initiate-solana-transaction.md@@ -0,0 +1,57 @@+# Prompt 5: Initiate Solana Transaction on Purchase++## Objective+Wire up the "Confirm Purchase" button in the modal to construct and request the user to sign a Solana transaction that transfers the specified amount to the creator's wallet.++## Explanation+This is where the user's action translates into an on-chain event. After connecting their wallet, clicking "Confirm" should prompt them, via their wallet extension, to approve a transaction that pays for the skill.++## Instructions+1. **Fetch Creator Wallet:**+ * The agent data from the backend must include the creator's public key (wallet address) where funds should be sent.+ * Modify the `/api/marketplace/agents/:id` endpoint to include `creator_wallet_address`.++2. **Construct Transaction (`src/marketplace.js`):**+ * In the event listener for the `#modal-confirm-purchase` button:+ * Get the connected wallet object from the wallet adapter.+ * Fetch the skill price (amount) and the creator's wallet address.+ * Use `@solana/web3.js` to create a new `Transaction` object.+ * Add a `SystemProgram.transfer` instruction to the transaction, specifying the sender (user's public key), recipient (creator's public key), and amount in lamports.++3. **Send and Confirm Transaction:**+ * Use the wallet adapter's `sendTransaction` method to send the transaction to the network.+ * Await the confirmation of the transaction.+ * Provide feedback to the user based on whether the transaction succeeds or fails.++## Code Example (JavaScript - `src/marketplace.js`)+```javascript+import { Connection, SystemProgram, Transaction, PublicKey } from '@solana/web3.js';+// Assume `wallet` is the connected wallet adapter object and `connection` is a Connection object.++document.getElementById('modal-confirm-purchase').addEventListener('click', async () => {+ const agent = getCurrentAgentData();+ const skillName = document.getElementById('modal-skill-name').textContent;+ const price = agent.skill_prices[skillName];++ const recipient = new PublicKey(agent.creator_wallet_address);+ const lamports = price.amount;++ const transaction = new Transaction().add(+ SystemProgram.transfer({+ fromPubkey: wallet.publicKey,+ toPubkey: recipient,+ lamports: lamports,+ })+ );++ try {+ const signature = await wallet.sendTransaction(transaction, connection);+ await connection.confirmTransaction(signature, 'processed');+ console.log('Transaction successful with signature:', signature);+ // Next step: Mint an NFT to prove ownership.+ } catch (error) {+ console.error('Transaction failed:', error);+ // Show an error message to the user.+ }+});+```diff --git a/docs/monetization/05-wallet-integration.md b/docs/monetization/05-wallet-integration.mdnew file mode 100644index 000000000..31e2ef9ed--- /dev/null+++ b/docs/monetization/05-wallet-integration.md@@ -0,0 +1,69 @@+---+status: not-started+---++# Prompt 5: Wallet Integration++## Objective+Integrate a Solana wallet adapter to allow users to connect their wallets (e.g., Phantom, Solflare) to the web application.++## Explanation+To enable on-chain payments, the first step is allowing users to connect their cryptocurrency wallets. We will use the official Solana wallet-adapter libraries to provide a smooth, standardized connection experience for users. This will add a "Connect Wallet" button to the application's header and make the user's public key available to the frontend.++## Instructions+1. **Install Dependencies:**+ * Add the required Solana wallet-adapter libraries to your project's `package.json`. You'll need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-react`, `@solana/wallet-adapter-wallets`, and potentially UI components for your framework (e.g., `@solana/wallet-adapter-react-ui`).+ * Run `npm install` or `yarn` to install them.++2. **Set up the Wallet Provider:**+ * In your main application component (e.g., `app.js` or a root-level layout component), wrap your application with the `ConnectionProvider`, `WalletProvider`, and `WalletModalProvider`.+ * The `ConnectionProvider` needs an RPC endpoint for the Solana cluster you're targeting (e.g., mainnet-beta or devnet).+ * The `WalletProvider` needs a list of the wallet adapters you want to support (e.g., `PhantomWalletAdapter`, `SolflareWalletAdapter`).++3. **Add the Connect Button:**+ * In your site's header component (e.g., `nav.js` or `header.html`), add the `WalletMultiButton` component from the UI library. This single component handles all connection states (Connect, Connected, Disconnect).+ * Ensure you style the button to match your site's aesthetic. You will need to import the adapter's CSS file (`@solana/wallet-adapter-react-ui/styles.css`).++4. **Access Wallet State:**+ * Use the `useWallet` hook in your components to access the user's wallet state, such as `publicKey`, `connected`, `signTransaction`, etc.+ * For example, you can now show or hide certain UI elements based on whether `connected` is true or false.++## Code Example (React-like, for `app.js` or similar)++```javascript+import React, { useMemo } from 'react';+import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';+import { WalletAdapterNetwork } from '@solana/wallet-adapter-base';+import { PhantomWalletAdapter, SolflareWalletAdapter } from '@solana/wallet-adapter-wallets';+import { WalletModalProvider, WalletMultiButton } from '@solana/wallet-adapter-react-ui';+import { clusterApiUrl } from '@solana/web3.js';++// Default styles that can be overridden+require('@solana/wallet-adapter-react-ui/styles.css');++export const App = () => {+ const network = WalletAdapterNetwork.Mainnet;+ const endpoint = useMemo(() => clusterApiUrl(network), [network]);+ const wallets = useMemo(() => [+ new PhantomWalletAdapter(),+ new SolflareWalletAdapter(),+ ], [network]);++ return (+ <ConnectionProvider endpoint={endpoint}>+ <WalletProvider wallets={wallets} autoConnect>+ <WalletModalProvider>+ {/* Your existing app layout */}+ <header>+ {/* ... other header items ... */}+ <WalletMultiButton />+ </header>+ <main>+ {/* ... rest of your app ... */}+ </main>+ </WalletModalProvider>+ </WalletProvider>+ </ConnectionProvider>+ );+};+```diff --git a/docs/monetization/06-backend-payment-transaction-api.md b/docs/monetization/06-backend-payment-transaction-api.mdnew file mode 100644index 000000000..d528843f5--- /dev/null+++ b/docs/monetization/06-backend-payment-transaction-api.md@@ -0,0 +1,99 @@+---+status: not-started+---++# Prompt 6: Backend - Payment Transaction API++## Objective+Create a backend API endpoint that generates a Solana transaction for a specific skill purchase and returns it to the frontend for signing.++## Explanation+To securely handle payments, the backend must be responsible for creating the transaction. The frontend will request a transaction for a specific skill, and this API will construct it, including the correct recipient address (the creator), the currency (e.g., USDC), and the amount. Returning the unsigned transaction to the frontend allows the user to sign it with their wallet without ever exposing their private key to our server.++## Instructions+1. **Create the API Endpoint:**+ * Create a new API file, e.g., `api/payments/create-transaction.js`.+ * This endpoint will accept `POST` requests at `/api/payments/create-transaction`.++2. **Request Body and Validation:**+ * The request body from the frontend must include:+ * `agentId`: The ID of the agent whose skill is being purchased.+ * `skillName`: The name of the skill.+ * `buyerPublicKey`: The public key of the user who is buying the skill.+ * Validate this input.++3. **Fetch Skill and Creator Data:**+ * From your database, fetch the price (`amount`, `currency_mint`) for the given `skillName` and `agentId` from the `agent_skill_prices` table.+ * Fetch the agent creator's payout wallet address from the `creator_payout_wallets` table (or `agent_identities` if stored there). Let's call this `creatorPublicKey`.++4. **Construct the Solana Transaction:**+ * Use the `@solana/web3.js` library.+ * You will create a **Token Transfer** instruction using the `@solana/spl-token` library.+ * The instruction needs:+ * The buyer's associated token account for the currency (`source`).+ * The creator's associated token account for the currency (`destination`).+ * The buyer's main wallet address as the authority (`owner`).+ * The `amount` from the database.+ * The `currency_mint` from the database.+ * **Important:** You may need to create the creator's associated token account if it doesn't exist. Your transaction might need to include the `createAssociatedTokenAccountInstruction`.+ * Create a new `Transaction` and add the transfer instruction(s) to it.+ * Set the `feePayer` to the `buyerPublicKey`.+ * Set a `recentBlockhash`. You can get this from your Solana `Connection` object.++5. **Serialize and Return:**+ * Serialize the transaction *without signing it*.+ * Return the serialized transaction to the frontend, base64-encoded.++## Code Example (`api/payments/create-transaction.js`)++```javascript+import { Connection, PublicKey, Transaction, SystemProgram } from '@solana/web3.js';+import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';+import { json, wrap } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+// ... other imports++const SOLANA_RPC_ENDPOINT = process.env.SOLANA_RPC_ENDPOINT;+const connection = new Connection(SOLANA_RPC_ENDPOINT);++export default wrap(async (req, res) => {+ // ... authentication and input validation ...+ const { agentId, skillName, buyerPublicKey } = req.body;+ const buyer = new PublicKey(buyerPublicKey);++ // 1. Fetch price and creator wallet from DB+ const [priceInfo] = await sql`...`; // Get amount and currency_mint+ const [creatorInfo] = await sql`...`; // Get creator's payout wallet+ if (!priceInfo || !creatorInfo) {+ return json(res, 404, { error: 'Skill or creator wallet not found' });+ }++ const creator = new PublicKey(creatorInfo.wallet_address);+ const currencyMint = new PublicKey(priceInfo.currency_mint);+ const amount = BigInt(priceInfo.amount);++ // 2. Get the buyer's and creator's token accounts+ const buyerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, currencyMint, buyer);+ const creatorTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, currencyMint, creator);++ // 3. Create the transaction+ const transaction = new Transaction();+ transaction.add(+ createTransferInstruction(+ buyerTokenAccount.address, // from+ creatorTokenAccount.address, // to+ buyer, // owner+ amount+ )+ );++ transaction.feePayer = buyer;+ transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;++ // 4. Serialize and encode+ const serializedTransaction = transaction.serialize({ requireAllSignatures: false });+ const base64Transaction = serializedTransaction.toString('base64');++ return json(res, 200, { transaction: base64Transaction });+});+```diff --git a/docs/monetization/06-create-backend-api-for-payments.md b/docs/monetization/06-create-backend-api-for-payments.mdnew file mode 100644index 000000000..a30171a24--- /dev/null+++ b/docs/monetization/06-create-backend-api-for-payments.md@@ -0,0 +1,81 @@+# Prompt 6: Create Backend API for Payment Transactions++## Status+- [ ] Not Started++## Objective+Create a backend API endpoint that prepares a Solana transaction for a skill purchase and sends it to the frontend for signing.++## Explanation+For security and reliability, the transaction should be constructed on the backend. The backend will determine the correct accounts (buyer, seller, mint) and amounts, create an unsigned transaction, serialize it, and send it to the frontend. The frontend's only job is to get the user's signature.++## Instructions+1. **Create a New API Endpoint:**+ * Create a new API route, for example, `POST /api/payments/prepare-transaction`.+ * This endpoint will require authentication to ensure only logged-in users can make purchases.++2. **Implement the Endpoint Logic:**+ * The endpoint should accept a payload containing the `skill_name`, `agent_id`, and the buyer's public key.+ * On the backend, retrieve the skill's price and currency mint from the `agent_skill_prices` table.+ * Fetch the agent creator's wallet address (the seller).+ * Construct a Solana transaction using `@solana/web3.js`. The transaction will be a simple SPL token transfer from the buyer's wallet to the seller's wallet.+ * The transaction should be recent and have a recent blockhash.+ * Serialize the transaction and send it back to the frontend in a base64-encoded format.++## Code Example (Backend - `/api/payments/prepare-transaction.js`)+```javascript+// /api/payments/prepare-transaction.js+import { Connection, PublicKey, Transaction, SystemProgram } from '@solana/web3.js';+import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';+import { getSkillPrice, getAgentCreatorWallet } from './_db.js'; // Placeholder for DB functions++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ return res.status(405).json({ error: 'Method Not Allowed' });+ }++ const { skillName, agentId, buyerPublicKey } = req.body;++ // 1. Fetch skill price and seller's address+ const priceInfo = await getSkillPrice(agentId, skillName);+ const sellerPublicKey = await getAgentCreatorWallet(agentId);++ if (!priceInfo || !sellerPublicKey) {+ return res.status(404).json({ error: 'Skill or seller not found' });+ }++ // 2. Setup Solana connection+ const connection = new Connection(process.env.SOLANA_RPC_URL, 'confirmed');+ const buyer = new PublicKey(buyerPublicKey);+ const seller = new PublicKey(sellerPublicKey);+ const mint = new PublicKey(priceInfo.currency_mint);++ // 3. Get or create token accounts+ const buyerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, buyer);+ const sellerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, seller);++ // 4. Create the transaction+ const transaction = new Transaction();+ transaction.add(+ createTransferInstruction(+ buyerTokenAccount.address,+ sellerTokenAccount.address,+ buyer,+ priceInfo.amount+ )+ );++ // 5. Set recent blockhash and fee payer+ transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;+ transaction.feePayer = buyer;++ // 6. Serialize and send to frontend+ const serializedTransaction = transaction.serialize({+ requireAllSignatures: false, // The buyer's signature is still needed+ });++ res.status(200).json({+ transaction: serializedTransaction.toString('base64'),+ });+}+```diff --git a/docs/monetization/06-create-skill-nft-collection.md b/docs/monetization/06-create-skill-nft-collection.mdnew file mode 100644index 000000000..05685ec03--- /dev/null+++ b/docs/monetization/06-create-skill-nft-collection.md@@ -0,0 +1,56 @@+# Prompt 6: Create Skill NFT Collection++## Objective+Develop a script or backend process to create a unique NFT collection for each agent. This collection will be used to mint "skill ownership" NFTs to users who purchase them.++## Explanation+Using NFTs to represent ownership provides a verifiable, on-chain record that a user has paid for a skill. The first step is to create a "collection" NFT, which acts as a master identifier for all the skill NFTs belonging to a specific agent. This ensures authenticity and allows for easy verification.++## Instructions+1. **Use Metaplex Umi:**+ * The backend will need to interact with the Solana network. Use the Metaplex Umi library, which simplifies creating and managing NFTs.+ * Set up a backend wallet (the "collection authority") that will pay the fees for creating the collection.++2. **Create Collection Script/Endpoint:**+ * Develop a script (`scripts/create-agent-collection.mjs`) or a secure backend endpoint.+ * This function should take an agent ID as input.+ * It should generate a new keypair for the collection NFT's mint address.+ * Using Umi, it will build and send a transaction to create:+ 1. The collection mint account.+ 2. The associated token account.+ 3. The collection's metadata account (with name, symbol, etc., tied to the agent).+ 4. The master edition account.++3. **Store Collection Address:**+ * After the collection is created, its mint address must be stored in the database, associated with the agent. Add a `collection_mint` column to the `agents` table.++## Code Example (Backend Script using Umi)+```javascript+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';+import { createNft, mplTokenMetadata } from '@metaplex-foundation/mpl-token-metadata';+import { generateSigner, percentAmount } from '@metaplex-foundation/umi';++// 1. Setup Umi+const umi = createUmi('https://api.devnet.solana.com').use(mplTokenMetadata());+// Add your backend keypair to umi++// 2. Define the collection details+const collectionMint = generateSigner(umi);++// 3. Create the Collection NFT+async function createCollection() {+ await createNft(umi, {+ mint: collectionMint,+ name: "Agent 'X' Skills",+ symbol: 'AGENTX',+ uri: 'URL_TO_JSON_METADATA', // Link to a JSON file with image, description, etc.+ sellerFeeBasisPoints: percentAmount(5.5), // 5.5% royalty+ isCollection: true,+ }).sendAndConfirm(umi);++ console.log('Collection created with mint address:', collectionMint.publicKey);+ // 4. Save `collectionMint.publicKey` to the database for the agent.+}++createCollection();+```diff --git a/docs/monetization/06-solana-pay-endpoint.md b/docs/monetization/06-solana-pay-endpoint.mdnew file mode 100644index 000000000..6b412ecde--- /dev/null+++ b/docs/monetization/06-solana-pay-endpoint.md@@ -0,0 +1,93 @@+---+status: not-started+completed_at: null+---+# Prompt 6: On-Chain Payment API with Solana Pay++## Objective+Create a backend API endpoint that generates a Solana Pay transaction request for purchasing a specific agent skill.++## Explanation+To accept payments for skills, we need to integrate with the Solana blockchain. This prompt outlines the creation of an API endpoint that follows the Solana Pay specification. When a user wants to buy a skill, the frontend will call this endpoint. The endpoint will generate the details for a valid SPL Token transfer transaction, which the user's wallet will then use to approve the payment.++## Instructions+1. **Define the API Endpoint:**+ * Create a new route: `GET /api/purchase/skill/:agentId/:skillName`. This will be the main endpoint for initiating a purchase.+ * Also, create a `POST` handler for the same route, which will be used by the Solana Pay protocol to validate the transaction after the user signs it.++2. **Implement the `GET` Handler (Transaction Request):**+ * **Fetch Skill Price:** From the database, retrieve the `amount` and `currency_mint` for the requested `agentId` and `skillName`. If not found, return a `404 Not Found`.+ * **Fetch Creator's Wallet:** Get the agent creator's destination wallet address. This should be stored securely with the creator's user profile.+ * **Generate a Unique Reference Key:** Create a new, unique keypair (`Keypair.generate()`). The public key of this keypair will serve as a unique reference for the transaction, preventing double-spending. Store this reference in your database or cache temporarily, associating it with the purchase details (user, skill, agent).+ * **Construct the Solana Pay Response:**+ * `label`: The name of your platform.+ * `icon`: A URL to your platform's logo.+ * For the `POST` handler, construct the JSON response which includes the details needed for the wallet to build the transaction:+ * `transaction`: A Base64-encoded, serialized, but **unsigned** transaction.+ * `message` (optional): A descriptive message, e.g., "Purchase 'translate' skill for Agent 'X'".+ * The transaction should be a simple SPL Token transfer from the buyer (the wallet will fill this in) to the creator's wallet address.+ * The transaction must include the unique `reference` public key.++3. **Implement the `POST` Handler (Transaction Validation):**+ * **Receive Transaction:** The wallet will send the user-signed transaction to this endpoint. The body will contain `{ transaction: "..." }`.+ * **Deserialize and Verify:**+ * Deserialize the transaction.+ * Check that the signature is valid for the expected signer (the user).+ * Verify that the transaction details match the expected purchase: correct recipient, correct amount, correct SPL token mint, and the **correct unique reference key**. This is crucial for security.+ * **Record the Purchase:** If verification passes, save the purchase details to your `user_skill_purchases` table, including the transaction signature.+ * **Return Confirmation:** Respond with a success message including the transaction signature.++## Code Example (Backend `GET` Handler)++```javascript+// Example using Express.js and @solana/web3.js, @solana/spl-token++// GET /api/purchase/skill/:agentId/:skillName+app.get('/api/purchase/skill/:agentId/:skillName', async (req, res) => {+ // ... fetch skillPrice, creatorWallet from db ...++ const { amount, currency_mint } = skillPrice;+ const recipient = new PublicKey(creatorWallet);+ const splToken = new PublicKey(currency_mint);++ // Generate a unique reference for this transaction+ const reference = new Keypair().publicKey;+ // Store reference in cache/db to validate it in the POST request+ await cache.set(`ref_${reference.toBase58()}`, { agentId, skillName, userId: req.user.id });++ res.status(200).json({+ label: "My 3D Agent Platform",+ icon: "https://my-platform.com/logo.png",+ });+});++// POST /api/purchase/skill/:agentId/:skillName+app.post('/api/purchase/skill/:agentId/:skillName', async (req, res) => {+ // This endpoint should return the actual transaction details+ const { account } = req.body;+ if (!account) {+ return res.status(400).json({ error: 'Account is required.' });+ }+ // ... fetch skillPrice, creatorWallet from db ...+ // ... generate reference, etc ...++ // Create the unsigned transaction+ const transaction = new Transaction();+ // ... add SPL token transfer instruction ...+ // The instruction needs: source (user's wallet), destination (creator's wallet), amount, mint.+ // The wallet will provide the user's source token account.++ res.status(200).json({+ transaction: transaction.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64'),+ message: `Purchase skill for ${(amount / 1e6).toFixed(2)} USDC`,+ });+});+```++## Definition of Done+- A `GET` endpoint exists at `/api/purchase/skill/:agentId/:skillName` that returns the `label` and `icon` for a Solana Pay request.+- A `POST` endpoint exists at the same URL that takes a public key `account` and returns a serialized, unsigned transaction.+- The transaction is a valid SPL token transfer for the correct amount and token.+- A unique reference key is generated for each transaction request.+- The `POST` handler for validating the final signed transaction is implemented and secure.+- Successful purchases are recorded in the `user_skill_purchases` table.diff --git a/docs/monetization/07-frontend-payment-and-signing.md b/docs/monetization/07-frontend-payment-and-signing.mdnew file mode 100644index 000000000..474fa0c66--- /dev/null+++ b/docs/monetization/07-frontend-payment-and-signing.md@@ -0,0 +1,83 @@+# Prompt 7: Frontend Payment and Transaction Signing++## Status+- [ ] Not Started++## Objective+Implement the frontend logic to receive the serialized transaction from the backend, prompt the user to sign it with their wallet, and send the signed transaction to the network.++## Explanation+This prompt connects the UI to the backend payment API. When the user confirms a purchase, the frontend will fetch the transaction, use the wallet adapter to sign it, and then broadcast it to the Solana network.++## Instructions+1. **Update Modal Event Listener:**+ * In the `handlePurchaseClick` logic, add a click event listener to the `modal-confirm-btn`.+ * This listener will trigger the payment process.++2. **Implement the Payment Flow:**+ * When the confirm button is clicked, make a `POST` request to your `/api/payments/prepare-transaction` endpoint.+ * Send the necessary data: `skillName`, `agentId`, and the connected user's public key.+ * The backend will respond with a base64-encoded serialized transaction.++3. **Sign and Send the Transaction:**+ * Deserialize the transaction received from the backend.+ * Use the connected wallet adapter's `signTransaction` method.+ * Once signed, use the `connection.sendRawTransaction` method from `@solana/web3.js` to broadcast it.+ * Wait for the transaction to be confirmed and then notify the user of the result (success or failure).++## Code Example (Frontend Payment Logic)+```javascript+// Add this to your marketplace.js or a dedicated payments module+import { Connection, Transaction } from '@solana/web3.js';+import { getConnectedWallet, getConnectedWalletAddress } from './wallet.js';++const connection = new Connection(process.env.NEXT_PUBLIC_SOLANA_RPC_URL, 'confirmed');++async function handleConfirmPurchase() {+ const skillData = JSON.parse(document.getElementById('modal-confirm-btn').dataset.skillData);+ const buyerPublicKey = getConnectedWalletAddress();+ const wallet = getConnectedWallet();++ if (!buyerPublicKey || !wallet) {+ alert('Please connect your wallet first.');+ return;+ }++ // 1. Fetch transaction from backend+ const response = await fetch('/api/payments/prepare-transaction', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ ...skillData,+ buyerPublicKey,+ agentId: currentAgent.id, // Assuming 'currentAgent' is available in scope+ }),+ });++ const { transaction: base64Transaction } = await response.json();+ const transactionBuffer = Buffer.from(base64Transaction, 'base64');+ const transaction = Transaction.from(transactionBuffer);++ try {+ // 2. Sign the transaction+ const signedTransaction = await wallet.signTransaction(transaction);++ // 3. Send and confirm the transaction+ const signature = await connection.sendRawTransaction(signedTransaction.serialize());+ await connection.confirmTransaction(signature, 'confirmed');++ alert(`Purchase successful! Transaction signature: ${signature}`);+ // Next step: Update UI to show the user owns the skill.+ } catch (error) {+ console.error('Purchase failed:', error);+ alert('Purchase failed. See console for details.');+ } finally {+ // Hide the modal+ document.getElementById('purchase-confirm-modal').classList.add('modal-hidden');+ }+}++// Attach this to the confirm button+document.getElementById('modal-confirm-btn').addEventListener('click', handleConfirmPurchase);++```diff --git a/docs/monetization/07-frontend-unlock-skill-button.md b/docs/monetization/07-frontend-unlock-skill-button.mdnew file mode 100644index 000000000..dbe70c21d--- /dev/null+++ b/docs/monetization/07-frontend-unlock-skill-button.md@@ -0,0 +1,100 @@+---+status: not-started+---++# Prompt 7: Frontend - "Unlock Skill" Button++## Objective+Update the marketplace UI (`marketplace.js` and `marketplace.html`) to show a prominent "Unlock" or "Purchase" button next to paid skills.++## Explanation+Now that we can display prices, the next logical step for the user is an action to purchase the skill. This task involves changing the static price badge into an interactive button for skills that are not free and have not yet been purchased by the user.++## Instructions+1. **Fetch User's Unlocked Skills:**+ * You'll need a way to know which skills the currently logged-in user already owns. This requires a new API endpoint, e.g., `GET /api/users/me/unlocked-skills`, which returns an array of skill names or IDs the user has purchased.+ * In `marketplace.js`, when the application loads, fetch this list of unlocked skills and store it.++2. **Modify the `renderDetail` function:**+ * In `src/marketplace.js`, within the `renderDetail` function where you iterate over skills, you now need three pieces of information for each skill:+ 1. The skill's details (name, description).+ 2. The skill's price (from `agent.skill_prices`).+ 3. Whether the current user has unlocked it (from the list fetched in step 1).++3. **Conditional Rendering Logic:**+ * Inside the loop, implement the following logic for each skill:+ * **If `price` does not exist:** The skill is free. Render a "Free" badge.+ * **If `price` exists AND the user has unlocked the skill:** The skill is already owned. Render an "Unlocked" or "Owned" badge.+ * **If `price` exists AND the user has NOT unlocked the skill:** The skill is available for purchase. Render a "Unlock for X USDC" button.++4. **Add Data Attributes:**+ * The "Unlock" button needs to have necessary information attached to it so its event handler knows what to do. Use `data-*` attributes to store the `agentId` and `skillName`.++## Code Example (`src/marketplace.js` inside `renderDetail`)++```javascript+// Assume `unlockedSkills` is a Set or array of skill names fetched on page load+const unlockedSkills = new Set(['Jupiter Swapper']); // Example data++// ... inside renderDetail loop ...+const skillPrices = a.skill_prices || {};+$('d-skills').innerHTML = skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];++ let badgeHtml;+ if (!price) {+ badgeHtml = `<span class="price-badge price-free">Free</span>`;+ } else if (unlockedSkills.has(name)) {+ badgeHtml = `<span class="price-badge price-unlocked">✅ Unlocked</span>`;+ } else {+ const amount = (price.amount / 1e6).toFixed(2);+ badgeHtml = `+ <button+ class="btn-unlock-skill"+ data-agent-id="${escapeHtml(a.id)}"+ data-skill-name="${escapeHtml(name)}">+ Unlock for ${amount} USDC+ </button>+ `;+ }++ return `<div class="skill-entry">+ <span class="skill-name">${escapeHtml(name)}</span>+ ${badgeHtml}+ </div>`;+}).join('');+```++## CSS Example (`/marketplace.css`)++```css+.skill-entry {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 8px 4px;+ border-bottom: 1px solid #333;+}++.price-unlocked {+ color: #a7f3d0; /* Same as free, but with a checkmark */+ background-color: rgba(52, 211, 153, 0.1);+}++.btn-unlock-skill {+ background-color: #4f46e5;+ color: white;+ border: none;+ padding: 4px 10px;+ font-size: 11px;+ font-weight: 600;+ border-radius: 5px;+ cursor: pointer;+ transition: background-color 0.2s;+}++.btn-unlock-skill:hover {+ background-color: #6366f1;+}+```diff --git a/docs/monetization/07-mint-skill-nft-on-purchase.md b/docs/monetization/07-mint-skill-nft-on-purchase.mdnew file mode 100644index 000000000..ec7cdb2b9--- /dev/null+++ b/docs/monetization/07-mint-skill-nft-on-purchase.md@@ -0,0 +1,55 @@+# Prompt 7: Mint Skill NFT on Purchase++## Objective+After a user's payment transaction is successfully confirmed, the backend should mint a new NFT from the agent's collection to the user's wallet.++## Explanation+This step connects the payment with the proof-of-ownership. Minting an NFT serves as an on-chain receipt and a perpetual license for the user to access the skill. This NFT is a standard SPL token, making it viewable in wallets and on explorers.++## Instructions+1. **Create a Backend Minting Endpoint:**+ * Create a new API endpoint, e.g., `/api/skills/mint`. This endpoint should be called by the frontend *after* a payment transaction is confirmed.+ * It should accept the `agent_id`, `skill_name`, and the `user_wallet` address as parameters. It should also take the payment `transaction_signature` for verification.++2. **Verify Payment:**+ * Before minting, the backend *must* verify that the provided `transaction_signature` is valid, recent, and corresponds to the correct payment (correct amount to the correct creator). This prevents fraudulent minting requests.++3. **Mint the NFT using Umi:**+ * Fetch the agent's `collection_mint` address from the database.+ * Generate a new signer for the skill NFT's mint address.+ * Use Umi's `createNft` function, but this time:+ * Set the `collection` property to the agent's collection mint address.+ * The `name` and `uri` should be specific to the skill being purchased.+ * The `owner` should be the user's public key.++4. **Return NFT Details:**+ * The endpoint should return the mint address of the newly created skill NFT to the frontend.++## Code Example (Backend Minting Endpoint using Umi)+```javascript+// Inside the /api/skills/mint endpoint+import { createNft, mplTokenMetadata } from '@metaplex-foundation/mpl-token-metadata';++// ... (After setting up umi and verifying payment)++const agentCollectionMint = getAgentCollectionMintFromDB(agentId);+const userPublicKey = new PublicKey(userWallet);+const skillNftMint = generateSigner(umi);++const { signature } = await createNft(umi, {+ mint: skillNftMint,+ owner: userPublicKey,+ name: `Skill: ${skillName}`,+ uri: `URL_TO_${skillName}_METADATA.json`,+ sellerFeeBasisPoints: percentAmount(0), // No royalties on individual skills+ collection: {+ verified: false, // The collection authority needs to verify this in a separate transaction+ key: agentCollectionMint,+ },+}).sendAndConfirm(umi);++// After minting, you must also run a 'verifyCollection' transaction+// so the NFT shows up as part of the official collection in wallets.++res.status(200).json({ nftMint: skillNftMint.publicKey, signature });+```diff --git a/docs/monetization/08-backend-ownership-verification.md b/docs/monetization/08-backend-ownership-verification.mdnew file mode 100644index 000000000..e3f796c3f--- /dev/null+++ b/docs/monetization/08-backend-ownership-verification.md@@ -0,0 +1,53 @@+# Prompt 8: Backend Ownership Verification++## Objective+Create a secure backend endpoint that can verify whether a given user wallet holds the specific NFT required to access a paid skill.++## Explanation+Gating access to a feature requires a reliable way to check for ownership. This check must be done on the backend to prevent users from simply manipulating frontend code to bypass the restriction. The backend will query the Solana blockchain directly to verify NFT ownership.++## Instructions+1. **Create Verification Endpoint:**+ * Create a new API endpoint, e.g., `/api/skills/verify-ownership`.+ * It should accept `user_wallet`, `agent_id`, and `skill_name` as query parameters.++2. **Find the Required NFT:**+ * This is the challenging part. A user could own many NFTs. You need to find the *correct* one.+ * The most robust method is to query all token accounts for the `user_wallet`.+ * Then, for each token they own (where `amount > 0`), fetch its metadata.+ * Check the metadata to see if the NFT is part of the agent's verified `collection` (the `collection_mint` address you stored earlier).+ * Also, check if the NFT's name or a trait in its metadata matches the `skill_name`.++3. **Use a Solana RPC Provider or Indexer:**+ * Fetching all this data can be slow using a standard RPC. For performance, use a dedicated NFT indexing service like Helius, Shyft, or SimpleHash. These services provide APIs to quickly fetch all NFTs owned by a wallet and their metadata.++4. **Return Verification Status:**+ * The endpoint should return a simple JSON response, like `{ "has_access": true }` or `{ "has_access": false }`.++## Code Example (Backend using Helius API)+```javascript+// This is a conceptual example of using an indexer API++async function verifyOwnership(req, res) {+ const { user_wallet, agent_id, skill_name } = req.query;+ const agent = await getAgentFromDB(agent_id);+ const agentCollectionMint = agent.collection_mint;++ // Use an indexer API to get all assets owned by the user+ const response = await fetch(`https://api.helius.xyz/v0/addresses/${user_wallet}/nfts?api-key=YOUR_API_KEY`);+ const data = await response.json();++ let has_access = false;+ for (const nft of data.items) {+ if (nft.grouping?.group_key === 'collection' && nft.grouping?.group_value === agentCollectionMint) {+ // This NFT is in the right collection. Now check if it's the right skill.+ if (nft.content?.metadata?.name.includes(skill_name)) {+ has_access = true;+ break;+ }+ }+ }++ res.status(200).json({ has_access });+}+```diff --git a/docs/monetization/08-frontend-payment-flow.md b/docs/monetization/08-frontend-payment-flow.mdnew file mode 100644index 000000000..530ed9f86--- /dev/null+++ b/docs/monetization/08-frontend-payment-flow.md@@ -0,0 +1,95 @@+---+status: not-started+---++# Prompt 8: Frontend - Payment Flow++## Objective+Implement the client-side logic to handle the entire skill purchase flow: requesting the transaction, getting the user's signature, sending it to the network, and confirming it.++## Explanation+This prompt connects the "Unlock" button to the backend and the user's wallet. When a user clicks the button, the frontend will orchestrate the process of fetching, signing, and broadcasting the payment transaction on the Solana network. This is a critical user-facing step that needs to be smooth and provide clear feedback.++## Instructions+1. **Add Event Listener:**+ * In `src/marketplace.js`, add a click event listener to the container of the skills list (or delegate from a higher-level element). When a `.btn-unlock-skill` is clicked, the handler should fire.++2. **Request the Transaction:**+ * Inside the event handler, get the `agentId` and `skillName` from the button's `data-*` attributes.+ * Get the connected user's public key from the `useWallet` hook. If no wallet is connected, prompt the user to connect first.+ * Send a `POST` request to your `/api/payments/create-transaction` endpoint with the `agentId`, `skillName`, and `buyerPublicKey`.+ * Show a loading indicator to the user (e.g., disable the button and show a spinner).++3. **Deserialize and Sign:**+ * The API will respond with a base64-encoded transaction string.+ * Decode the base64 string into a buffer.+ * Use `Transaction.from()` from `@solana/web3.js` to deserialize the buffer back into a `Transaction` object.+ * Use the `signTransaction` function from the `useWallet` hook to prompt the user to sign the transaction with their wallet. This will open a popup in their wallet extension.++4. **Send and Confirm the Transaction:**+ * Once the user signs, the `signTransaction` function will return the signed transaction.+ * Serialize the signed transaction and use `connection.sendRawTransaction` to broadcast it to the Solana network. This will return a transaction signature (ID).+ * Use `connection.confirmTransaction` with the signature to wait for the transaction to be confirmed by the network. This is crucial for ensuring the payment went through before considering the skill unlocked.++5. **Provide Feedback:**+ * While confirming, keep the user informed (e.g., "Confirming transaction...").+ * On successful confirmation, show a success message ("Skill unlocked!").+ * You should then refresh the UI to show the skill as "Unlocked", either by re-fetching user data or just updating the DOM for that specific skill.+ * If any step fails (user rejects signature, transaction fails), show a clear error message.++## Code Example (`src/marketplace.js`)++```javascript+import { useWallet, useConnection } from '@solana/wallet-adapter-react';+import { Transaction } from '@solana/web3.js';+// ... other imports++// Add this listener in your initialization code+document.getElementById('d-skills').addEventListener('click', async (event) => {+ if (!event.target.matches('.btn-unlock-skill')) return;++ const button = event.target;+ const { agentId, skillName } = button.dataset;+ const { publicKey, signTransaction } = useWallet(); // From wallet adapter context+ const { connection } = useConnection(); // From wallet adapter context++ if (!publicKey || !signTransaction) {+ showToast('Please connect your wallet first.', 'error');+ return;+ }++ try {+ button.disabled = true;+ button.textContent = 'Processing...';++ // 1. Fetch transaction from backend+ const response = await fetch('/api/payments/create-transaction', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ agentId, skillName, buyerPublicKey: publicKey.toBase58() })+ });+ if (!response.ok) throw new Error('Failed to create transaction.');+ const { transaction: base64Transaction } = await response.json();++ // 2. Deserialize, sign, and send+ const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));+ const signedTransaction = await signTransaction(transaction);+ const signature = await connection.sendRawTransaction(signedTransaction.serialize());++ // 3. Confirm transaction+ await connection.confirmTransaction(signature, 'confirmed');++ showToast('Skill unlocked successfully!', 'success');++ // 4. Update UI+ button.outerHTML = `<span class="price-badge price-unlocked">✅ Unlocked</span>`;+ // Optionally, add skillName to a local `unlockedSkills` set.++ } catch (error) {+ console.error('Purchase failed:', error);+ showToast(error.message || 'Purchase failed. Please try again.', 'error');+ button.disabled = false;+ button.textContent = 'Unlock for ...'; // Restore original text+ }+});+```diff --git a/docs/monetization/08-record-skill-ownership.md b/docs/monetization/08-record-skill-ownership.mdnew file mode 100644index 000000000..9afe7c6db--- /dev/null+++ b/docs/monetization/08-record-skill-ownership.md@@ -0,0 +1,103 @@+# Prompt 8: Record Skill Ownership in Database++## Status+- [ ] Not Started++## Objective+Create a database table to track which users have purchased which skills, and an API endpoint to record a successful purchase.++## Explanation+After a transaction is successfully confirmed on the blockchain, we need to record the user's ownership of the skill in our own database. This allows us to easily check if a user has access to a skill without needing to query the blockchain every time.++## Instructions+1. **Design `user_owned_skills` Table:**+ * Create a new table with columns like:+ * `id`: Primary key.+ * `user_id`: Foreign key to the `users` table.+ * `agent_id`: Foreign key to the `agents` table.+ * `skill_name`: The name of the purchased skill.+ * `purchase_transaction_signature`: The Solana transaction signature of the purchase.+ * `created_at`: Timestamp.+ * Add a unique constraint on `(user_id, agent_id, skill_name)`.++2. **Create a "Finalize Purchase" API Endpoint:**+ * Create a new endpoint, e.g., `POST /api/payments/finalize-purchase`.+ * This endpoint will be called by the frontend *after* a transaction has been confirmed.+ * It should accept the `agent_id`, `skill_name`, and `transaction_signature`.++3. **Implement Finalization Logic:**+ * The backend should first verify the transaction signature on the Solana network to ensure it's valid and recent.+ * It should decode the transaction to confirm that the correct amount was transferred to the correct seller.+ * If the transaction is valid, insert a new record into the `user_owned_skills` table.++## SQL Example+```sql+CREATE TABLE user_owned_skills (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,+ skill_name VARCHAR(255) NOT NULL,+ purchase_transaction_signature VARCHAR(255) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++CREATE UNIQUE INDEX idx_user_owned_skills_on_user_agent_skill+ON user_owned_skills (user_id, agent_id, skill_name);+```++## Code Example (Backend - `/api/payments/finalize-purchase.js`)+```javascript+import { Connection } from '@solana/web3.js';+import { recordSkillOwnership } from './_db.js'; // DB function++export default async function handler(req, res) {+ const { agentId, skillName, transactionSignature, userId } = req.body;++ // 1. Verify transaction on-chain+ const connection = new Connection(process.env.SOLANA_RPC_URL, 'confirmed');+ const tx = await connection.getTransaction(transactionSignature, { maxSupportedTransactionVersion: 0 });++ if (!tx) {+ return res.status(400).json({ error: 'Transaction not found or not confirmed.' });+ }++ // 2. (Recommended) Decode the transaction to verify its contents+ // This part can be complex, involving parsing instructions and account keys.+ // For simplicity here, we're trusting the client, but in production, you MUST verify:+ // - The source wallet matches the user.+ // - The destination wallet matches the agent creator.+ // - The transfer amount and mint are correct.+ const isTransactionValid = true; // Placeholder for real validation logic++ if (!isTransactionValid) {+ return res.status(400).json({ error: 'Transaction validation failed.' });+ }++ // 3. Record ownership in the database+ await recordSkillOwnership(userId, agentId, skillName, transactionSignature);++ res.status(200).json({ success: true });+}+```++## Frontend Update+After a successful purchase, the frontend should call this new endpoint.+```javascript+// Inside the purchase success block in the frontend+const signature = await connection.sendRawTransaction(signedTransaction.serialize());+await connection.confirmTransaction(signature, 'confirmed');++// New part: Finalize with your backend+await fetch('/api/payments/finalize-purchase', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ agentId: currentAgent.id,+ skillName: skillData.skillName,+ transactionSignature: signature,+ userId: currentUser.id // Assuming you have the user's ID+ }),+});++alert('Purchase successful and recorded!');+```diff --git a/docs/monetization/09-backend-create-skill-ownership-table.md b/docs/monetization/09-backend-create-skill-ownership-table.mdnew file mode 100644index 000000000..7c924d819--- /dev/null+++ b/docs/monetization/09-backend-create-skill-ownership-table.md@@ -0,0 +1,55 @@+---+status: not-started+---++# Prompt 9: Backend - Create Skill Ownership Table++## Objective+Create a database table to permanently record which users have successfully purchased which skills.++## Explanation+After a user pays for a skill, we need to record their ownership so they don't have to pay for it again. A dedicated table, `user_unlocked_skills`, will store the relationship between a user, an agent, and a specific skill. This table will be the source of truth for checking skill access.++## Instructions+1. **Design the Table Schema:**+ * Name the table `user_unlocked_skills`.+ * It needs a column to link to the user (`user_id`).+ * It needs a column to link to the agent (`agent_id`).+ * It needs a column to identify the skill (`skill_name`).+ * It's highly recommended to store a reference to the purchase transaction (`purchase_tx_signature`) for auditing and customer support purposes.+ * Add a primary key and foreign keys to `users` and `agent_identities`.+ * Create a unique constraint on (`user_id`, `agent_id`, `skill_name`) to ensure a user can't have duplicate entries for the same skill.++2. **Create a SQL Migration File:**+ * Create a new SQL migration file (e.g., `scripts/migrations/003_create_user_unlocked_skills.sql`).+ * Write the `CREATE TABLE` statement.+ * Include a `created_at` timestamp to know when the skill was unlocked.++## Code Example (SQL)++```sql+-- scripts/migrations/003_create_user_unlocked_skills.sql++CREATE TABLE IF NOT EXISTS user_unlocked_skills (+ id SERIAL PRIMARY KEY,+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id INTEGER NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ skill_name VARCHAR(255) NOT NULL,++ -- The Solana transaction signature of the purchase+ purchase_tx_signature VARCHAR(88) NOT NULL,++ -- Store price info at time of purchase for historical records+ purchase_amount BIGINT NOT NULL,+ purchase_currency_mint VARCHAR(44) NOT NULL,++ unlocked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ -- A user can only unlock a specific agent's skill once.+ UNIQUE (user_id, agent_id, skill_name)+);++-- Add indexes for common queries+CREATE INDEX IF NOT EXISTS idx_user_unlocked_skills_user_id ON user_unlocked_skills(user_id);+CREATE INDEX IF NOT EXISTS idx_user_unlocked_skills_agent_id ON user_unlocked_skills(agent_id);+```diff --git a/docs/monetization/09-frontend-gating-for-skills.md b/docs/monetization/09-frontend-gating-for-skills.mdnew file mode 100644index 000000000..d4027a062--- /dev/null+++ b/docs/monetization/09-frontend-gating-for-skills.md@@ -0,0 +1,62 @@+# Prompt 9: Frontend Gating for Skills++## Objective+Implement a check in the frontend UI that calls the backend verification endpoint before allowing a user to use a paid skill.++## Explanation+This is the user-facing part of the access control system. When a user tries to interact with a paid skill (e.g., clicking a button in the chat interface that triggers the skill), the frontend must first confirm they have the right to do so.++## Instructions+1. **Identify Skill Triggers:**+ * Go through the chat UI or agent interaction logic and identify all the points where a skill is triggered.++2. **Create a Central Skill Dispatcher:**+ * Instead of triggering skills directly, create a central function, e.g., `tryUseSkill(skillName)`.+ * This function will be responsible for handling the gating logic.++3. **Implement the Check:**+ * Inside `tryUseSkill`, first determine if the skill is free or paid by checking the agent's `skill_prices` data.+ * If the skill is free, execute it immediately.+ * If the skill is paid, call the `/api/skills/verify-ownership` endpoint you created in the previous step.+ * Based on the `has_access` response:+ * If `true`, execute the skill.+ * If `false`, show a message to the user, e.g., "You need to purchase this skill to use it," and provide a link or button to the marketplace page.++4. **Cache Verification Results:**+ * To avoid calling the verification endpoint every single time, cache the results on the frontend for the duration of the user's session. A simple JavaScript object or `sessionStorage` can work for this.++## Code Example (Frontend Skill Dispatcher)+```javascript+const skillAccessCache = {};++async function tryUseSkill(skillName) {+ const agent = getCurrentAgentData();+ const isPaid = skillName in agent.skill_prices;++ if (!isPaid) {+ executeSkill(skillName);+ return;+ }++ // Check cache first+ if (skillAccessCache[skillName]) {+ executeSkill(skillName);+ return;+ }++ // If not in cache, verify with backend+ const userWallet = wallet.publicKey.toBase58(); // from wallet adapter+ const response = await fetch(`/api/skills/verify-ownership?user_wallet=${userWallet}&agent_id=${agent.id}&skill_name=${skillName}`);+ const data = await response.json();++ if (data.has_access) {+ skillAccessCache[skillName] = true; // Update cache+ executeSkill(skillName);+ } else {+ showPurchasePrompt(skillName); // UI function to tell user to buy the skill+ }+}++// Example usage:+// Instead of `runDanceSkill()`, you'd call `tryUseSkill('dance')`.+```diff --git a/docs/monetization/09-update-ui-for-owned-skills.md b/docs/monetization/09-update-ui-for-owned-skills.mdnew file mode 100644index 000000000..083e73f25--- /dev/null+++ b/docs/monetization/09-update-ui-for-owned-skills.md@@ -0,0 +1,81 @@+# Prompt 9: Update UI for Owned Skills++## Status+- [ ] Not Started++## Objective+Modify the agent detail page to visually reflect the skills a user already owns, disabling the "Purchase" button for those skills.++## Explanation+To prevent users from re-purchasing skills they already own, the UI needs to be updated based on their ownership status. This requires fetching the user's owned skills and adjusting the rendering logic.++## Instructions+1. **Backend: Expose Owned Skills:**+ * When fetching the agent details (`/api/marketplace/agents/:id`), if a user is authenticated, also query the `user_owned_skills` table.+ * Include a list of owned skill names for that specific agent in the API response.++2. **Frontend: Update Rendering Logic:**+ * In `src/marketplace.js`, the `renderDetail` function will now receive the list of owned skills.+ * In the skill rendering loop, check if the current skill is in the user's owned list.+ * If the user owns the skill, display an "Owned" badge or indicator instead of the "Purchase" button.++## Code Example (Backend API Response Snippet)+```json+{+ "id": "agent-uuid-123",+ "name": "Super Agent",+ "skills": ["super-jump", "laser-eyes"],+ "skill_prices": {+ "laser-eyes": { "amount": 2000000, "currency_mint": "..." }+ },+ "user_owned_skills": ["super-jump"]+}+```++## Code Example (Frontend - `src/marketplace.js` Update)+```javascript+// Inside renderDetail function+const skillPrices = a.skill_prices || {};+const ownedSkills = new Set(a.user_owned_skills || []); // Use a Set for efficient lookups++$('d-skills').innerHTML = skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ let actionElement;++ if (ownedSkills.has(name)) {+ actionElement = `<span class="ownership-badge">Owned</span>`;+ } else if (price) {+ const priceDisplay = `${(price.amount / 1e6).toFixed(2)} USDC`;+ actionElement = `<button class="purchase-skill-btn"+ data-skill-name="${escapeHtml(name)}"+ ... >+ Purchase for ${priceDisplay}+ </button>`;+ } else {+ // This is a free skill that hasn't been "claimed" or "owned" yet.+ // You might have a different state for free skills that are implicitly owned.+ actionElement = `<span class="price-badge price-free">Free</span>`;+ }++ return `<div class="skill-entry">+ <span>${escapeHtml(name)}</span>+ ${actionElement}+ </div>`;+}).join('');+```++## CSS for "Owned" Badge+```css+/* Add to marketplace.css */+.ownership-badge {+ display: inline-block;+ padding: 4px 10px;+ font-size: 11px;+ font-weight: 700;+ border-radius: 12px;+ background-color: #059669; /* Green */+ color: #d1fae5;+ border: 1px solid #06c78a;+}+```diff --git a/docs/monetization/09_api_purchase_confirm.md b/docs/monetization/09_api_purchase_confirm.mdnew file mode 100644index 000000000..ca4598b48--- /dev/null+++ b/docs/monetization/09_api_purchase_confirm.md@@ -0,0 +1,90 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 09: Backend API for Purchase Confirmation++## Objective+Create a backend endpoint to verify a skill purchase transaction on-chain and record it in the database.++## Explanation+After the frontend successfully broadcasts the transaction, it must notify the backend. This endpoint's job is to act as a final "source of truth." It verifies that the transaction signature provided by the client is valid, that it corresponds to the intended purchase, and that it was successful. Only after this verification does it save the purchase record to the `user_purchased_skills` table.++## Instructions+1. **Create the API Endpoint:**+ * Create a new file or handler for `POST /api/skills/purchase-confirm`.++2. **Implement the Logic:**+ * **Authentication:** The user must be authenticated.+ * **Input Validation:** The request body should contain `agent_id`, `skill_name`, and `signature`.+ * **Fetch Purchase Details:**+ * Retrieve the skill price and creator's wallet address, just as in the "prep" step. This is to ensure the on-chain transaction matches what we expected.+ * **On-Chain Verification:**+ * Use the Solana `connection.getParsedTransaction` method with the provided `signature`.+ * Inspect the transaction details to confirm:+ * The transaction was successful ( `tx.meta.err` is null).+ * The source account matches the buyer's wallet.+ * The destination account matches the creator's wallet.+ * The transfer amount matches the skill price.+ * The token mint matches the currency (e.g., USDC).+ * This step is critical to prevent users from submitting fraudulent or irrelevant transaction signatures.+ * **Database Operation:**+ * If on-chain verification passes, insert a new record into the `user_purchased_skills` table. Store all relevant details, including the transaction signature, for auditing.++## Code Example (Vercel Serverless Function)++```javascript+import { Connection } from '@solana/web3.js';+import { sql } from '../../_lib/db.js';+// ... other imports++export default wrap(async (req, res) => {+ // ... auth and input validation+ const { agent_id, skill_name, signature } = req.body;+ const user = await getSessionUser(req);+ const buyerWallet = user.wallet_address;++ // 1. Fetch expected details for verification+ const [skillPrice] = await sql`SELECT ...`;+ const [agent] = await sql`SELECT ...`;+ const creatorWallet = agent.meta.onchain.wallet;+ const expectedAmount = skillPrice.amount;+ const currencyMint = skillPrice.currency_mint;++ // 2. Verify transaction on-chain+ const connection = new Connection(rpcUrl('mainnet-beta'), 'confirmed');+ const tx = await connection.getParsedTransaction(signature, { maxSupportedTransactionVersion: 0 });++ if (!tx || tx.meta.err) {+ return error(res, 400, 'tx_failed', 'Transaction failed or not found.');+ }++ // Find the token transfer instruction+ const transferInstruction = tx.transaction.message.instructions.find(ix =>+ ix.parsed?.type === 'transfer' &&+ ix.program === 'spl-token'+ );++ if (!transferInstruction) {+ return error(res, 400, 'invalid_tx', 'No token transfer found in transaction.');+ }++ const { source, destination, amount } = transferInstruction.parsed.info;+ // Note: A robust implementation would resolve ATAs to owner wallets.+ // This is a simplified check.+ if (source !== buyerWalletAta || destination !== creatorWalletAta || amount !== expectedAmount) {+ return error(res, 400, 'tx_mismatch', 'Transaction details do not match expected purchase.');+ }++ // 3. Record the purchase in the database+ await sql`+ INSERT INTO user_purchased_skills+ (user_id, agent_id, skill_name, purchase_tx_signature, price_amount, price_currency_mint)+ VALUES+ (${user.id}, ${agent_id}, ${skill_name}, ${signature}, ${expectedAmount}, ${currencyMint})+ ON CONFLICT (user_id, agent_id, skill_name) DO NOTHING;+ `;++ return json(res, 201, { success: true, message: 'Purchase confirmed and recorded.' });+});+```diff --git a/docs/monetization/10-agent-editor-ui-for-pricing.md b/docs/monetization/10-agent-editor-ui-for-pricing.mdnew file mode 100644index 000000000..fc483a222--- /dev/null+++ b/docs/monetization/10-agent-editor-ui-for-pricing.md@@ -0,0 +1,91 @@+# Prompt 10: Create Agent Creation/Editing UI for Pricing++## Status+- [ ] Not Started++## Objective+Develop a user interface for agent creators to set and manage prices for their agent's skills.++## Explanation+For creators to monetize their work, they need a simple way to define which skills are for sale and at what price. This prompt focuses on building the UI for this purpose in the agent creation or editing page.++## Instructions+1. **Locate the Agent Editor:**+ * Find the HTML and JavaScript files responsible for the agent creation/editing form (e.g., `agent-edit.html` and `src/agent-editor.js`).++2. **Enhance the Skills Section:**+ * In the part of the form where skills are listed or added, add new input fields next to each skill.+ * The new fields should be for:+ * `Price`: A number input for the skill's price.+ * `Currency`: A dropdown/select input to choose the payment currency (e.g., USDC, SOL).++3. **Manage State:**+ * The JavaScript for the editor needs to manage this new pricing data.+ * When the form is loaded for an existing agent, it should be populated with the current skill prices.+ * As the creator changes the prices, the state should be updated.++4. **Handle Form Submission:**+ * When the agent creator saves their changes, the pricing information should be collected and sent to the backend.+ * The data should be structured in a way that's easy for the backend to process, e.g., an object where keys are skill names.++## Code Example (HTML in `agent-edit.html`)+```html+<div id="skills-editor">+ <!-- This part will be dynamically populated by JavaScript -->+</div>++<template id="skill-editor-template">+ <div class="skill-price-row">+ <input type="text" class="skill-name-input" placeholder="Skill Name" readonly>+ <input type="number" class="skill-price-input" placeholder="Price">+ <select class="skill-currency-select">+ <option value="USDC_MINT_ADDRESS">USDC</option>+ <option value="SOL_MINT_ADDRESS">SOL</option>+ <!-- Add other supported currencies -->+ </select>+ </div>+</template>+```++## Code Example (JavaScript in `src/agent-editor.js`)+```javascript+function renderSkillPricer(skills, currentPrices) {+ const container = document.getElementById('skills-editor');+ const template = document.getElementById('skill-editor-template');+ container.innerHTML = '';++ skills.forEach(skillName => {+ const skillRow = template.content.cloneNode(true);+ const price = currentPrices[skillName];++ skillRow.querySelector('.skill-name-input').value = skillName;+ if (price) {+ skillRow.querySelector('.skill-price-input').value = price.amount / 1e6; // Display in human-readable format+ skillRow.querySelector('.skill-currency-select').value = price.currency_mint;+ }++ container.appendChild(skillRow);+ });+}++function getSkillPricesFromForm() {+ const prices = {};+ document.querySelectorAll('#skills-editor .skill-price-row').forEach(row => {+ const name = row.querySelector('.skill-name-input').value;+ const amountInput = row.querySelector('.skill-price-input').value;+ const currency = row.querySelector('.skill-currency-select').value;++ if (amountInput && parseFloat(amountInput) > 0) {+ prices[name] = {+ amount: parseFloat(amountInput) * 1e6, // Convert to smallest unit+ currency_mint: currency+ };+ }+ });+ return prices;+}++// On save/submit:+const updatedPrices = getSkillPricesFromForm();+// Now, send 'updatedPrices' to the backend.+```diff --git a/docs/monetization/10-payment-recipient-setup.md b/docs/monetization/10-payment-recipient-setup.mdnew file mode 100644index 000000000..ff5d546fb--- /dev/null+++ b/docs/monetization/10-payment-recipient-setup.md@@ -0,0 +1,49 @@+# Prompt 10: Creator Payment Address Setup++## Objective+Allow agent creators to specify their own Solana wallet address as the recipient for skill payments.++## Explanation+To make the platform a true marketplace, creators need to be able to receive payments directly. This involves adding a field in the agent creation/editing form for a payout address and storing it securely in the backend.++## Instructions+1. **Update Database Schema:**+ * Add a `creator_wallet_address` column to the `agents` table in your database. This will store the public key of the creator's wallet.++2. **Modify Agent Edit UI:**+ * In the UI where creators can create or edit their agents (`agent-edit.html`), add a new input field for "Payout Wallet Address."+ * Implement frontend validation to ensure the entered string is a valid Solana public key format.++3. **Update Backend API:**+ * Modify the agent update endpoint (e.g., `/api/agents/:id` with a `POST` or `PUT` method).+ * When an agent is updated, validate the provided `creator_wallet_address` on the backend as well.+ * Save the validated address to the new column in the `agents` table.++4. **Use the Address in Transactions:**+ * In `prompt-05-initiate-solana-transaction`, the code already assumes the agent object contains `creator_wallet_address`. This prompt ensures that data is actually captured and saved correctly. No changes are needed to the transaction logic itself, as it was designed to be dynamic.++## Code Example (Frontend Validation in `agent-edit.js`)+```javascript+import { PublicKey } from '@solana/web3.js';++const walletInput = document.getElementById('payout-wallet-input');+const saveButton = document.getElementById('save-agent-button');++walletInput.addEventListener('input', () => {+ try {+ // Validate the public key format+ new PublicKey(walletInput.value);+ walletInput.setCustomValidity(''); // Valid+ } catch (error) {+ walletInput.setCustomValidity('Please enter a valid Solana wallet address.'); // Invalid+ }+});++saveButton.addEventListener('click', async () => {+ // On save, re-validate before sending to backend+ if (!walletInput.reportValidity()) {+ return; // Don't submit if invalid+ }+ //... proceed with fetch to backend API+});+```diff --git a/docs/monetization/10_enforce_skill_ownership.md b/docs/monetization/10_enforce_skill_ownership.mdnew file mode 100644index 000000000..3caacc19d--- /dev/null+++ b/docs/monetization/10_enforce_skill_ownership.md@@ -0,0 +1,62 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 10: Enforcing Skill Ownership for API Usage++## Objective+Secure the agent's skill execution endpoint (`/api/chat` or similar) to prevent users from using paid skills they have not purchased.++## Explanation+Currently, the chat API likely allows any user to invoke any of an agent's skills. With paid skills, we must add an ownership check. Before executing a skill, the API needs to determine if the skill is free or, if it's paid, whether the calling user has purchased it.++## Instructions+1. **Locate the Skill Execution Logic:**+ * Find the API endpoint responsible for agent chat and skill execution. This is likely a central part of the application, possibly in `api/chat.js`.++2. **Implement the Access Control Check:**+ * Inside the handler, just before the point where a skill is about to be executed, insert the access control logic.+ * **Step 1: Get Skill and User:**+ * You'll have the `agent_id`, the `skill_name` being invoked, and the `user_id` from the session.+ * **Step 2: Check if the Skill is Priced:**+ * Query the `agent_skill_prices` table to see if a price is set for the `agent_id` and `skill_name`.+ * **Step 3: Enforce Ownership:**+ * If no price exists, the skill is free, and execution can proceed.+ * If a price *does* exist, you must query the `user_purchased_skills` table to check for a record matching the `user_id`, `agent_id`, and `skill_name`.+ * If a record exists, the user owns the skill. Proceed with execution.+ * If no record exists, the user does not have access. Return a `403 Forbidden` error with a clear message like "You must purchase this skill to use it."++## Code Example (Inside the Chat/Skill Execution API)++```javascript+// This logic should be inserted before the skill execution block++const { agentId, skillName, userId } = /* ... from request context ... */;++// 1. Check if the skill has a price+const [skillPrice] = await sql`+ SELECT id FROM agent_skill_prices+ WHERE agent_id = ${agentId} AND skill_name = ${skillName}+`;++// If it has no price, it's free, so we can exit the check early+if (!skillPrice) {+ // Proceed with skill execution...+ return;+}++// 2. If it's priced, check if the user owns it+const [purchaseRecord] = await sql`+ SELECT id FROM user_purchased_skills+ WHERE user_id = ${userId} AND agent_id = ${agentId} AND skill_name = ${skillName}+`;++if (!purchaseRecord) {+ // User does NOT own the skill. Block execution.+ return error(res, 403, 'skill_not_owned', `Access denied. You must purchase the '${skillName}' skill to use it.`);+}++// 3. If we reach here, the user owns the skill.+// Proceed with skill execution...++```diff --git a/docs/monetization/11-backend-api-for-skill-prices.md b/docs/monetization/11-backend-api-for-skill-prices.mdnew file mode 100644index 000000000..873d95959--- /dev/null+++ b/docs/monetization/11-backend-api-for-skill-prices.md@@ -0,0 +1,78 @@+# Prompt 11: Backend API for Saving Skill Prices++## Status+- [ ] Not Started++## Objective+Create the backend API endpoint that allows agent creators to save the prices they've set for their skills.++## Explanation+This prompt complements the previous one by providing the backend infrastructure to persist the pricing information set in the agent editor UI. This endpoint will receive the pricing data and update the `agent_skill_prices` table.++## Instructions+1. **Create the API Endpoint:**+ * Create a new route, for example `POST /api/agents/:id/skill-prices`.+ * This endpoint must be protected and only accessible by the agent's creator.++2. **Implement the Update Logic:**+ * The endpoint will receive the agent's ID and a payload containing the skill prices (e.g., `{ "skill_name": { "amount": ..., "currency_mint": "..." } }`).+ * The logic should handle creating, updating, and deleting skill prices. A common approach is to:+ * Delete all existing price entries for that agent.+ * Insert the new price entries from the payload.+ * This "delete-then-insert" pattern is simple to implement, but for more advanced use cases, you might want to perform individual `UPSERT` operations.+ * Validate the input data to ensure amounts are valid numbers and currency mints are in the correct format.++## Code Example (Backend - `/api/agents/[id]/skill-prices.js`)+```javascript+// Example using a hypothetical DB utility+import { db } from './_db.js';+import { getUserIdFromRequest } from './_auth.js'; // Auth utility++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ return res.status(405).json({ error: 'Method Not Allowed' });+ }++ const agentId = req.query.id;+ const userId = await getUserIdFromRequest(req);++ // 1. Authorization: Check if the user is the agent's creator+ const agent = await db.query('SELECT creator_id FROM agents WHERE id = $1', [agentId]);+ if (!agent || agent.creator_id !== userId) {+ return res.status(403).json({ error: 'Forbidden' });+ }++ const skillPrices = req.body.skillPrices;++ // 2. Database transaction for atomicity+ const client = await db.getClient();+ try {+ await client.query('BEGIN');++ // 3. Delete old prices for this agent+ await client.query('DELETE FROM agent_skill_prices WHERE agent_id = $1', [agentId]);++ // 4. Insert new prices+ for (const skillName in skillPrices) {+ const { amount, currency_mint } = skillPrices[skillName];+ // Basic validation+ if (typeof amount !== 'number' || typeof currency_mint !== 'string') {+ throw new Error('Invalid price data for skill: ' + skillName);+ }+ await client.query(+ 'INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint) VALUES ($1, $2, $3, $4)',+ [agentId, skillName, amount, currency_mint]+ );+ }++ await client.query('COMMIT');+ res.status(200).json({ success: true });+ } catch (error) {+ await client.query('ROLLBACK');+ console.error('Failed to save skill prices:', error);+ res.status(500).json({ error: 'Internal Server Error' });+ } finally {+ client.release();+ }+}+```diff --git a/docs/monetization/11-creator-dashboard-ui.md b/docs/monetization/11-creator-dashboard-ui.mdnew file mode 100644index 000000000..1b2a658e0--- /dev/null+++ b/docs/monetization/11-creator-dashboard-ui.md@@ -0,0 +1,63 @@+# Prompt 11: Creator Dashboard UI++## Objective+Design and create the basic user interface for a new "Creator Dashboard" page, where agent creators can manage their monetization settings and view sales data.++## Explanation+A centralized dashboard is essential for creators to feel in control of their creations and revenue. This initial step focuses on building the static UI layout, which will be populated with dynamic data in subsequent tasks.++## Instructions+1. **Create New HTML File:**+ * Create a new file, `dashboard.html`.+ * This page should be behind authentication, accessible only to logged-in users.++2. **Design the Layout:**+ * The layout should include:+ * A main navigation/header shared with the rest of the site.+ * A sidebar for dashboard-specific navigation (e.g., "Overview," "My Agents," "Analytics," "Settings").+ * A main content area.++3. **Build UI Components (Static):**+ * In the "Overview" section, add placeholder components for:+ * A summary card for total revenue.+ * A summary card for total sales.+ * A chart (you can use a library like Chart.js or just use a placeholder image for now) to show sales over time.+ * In the "My Agents" section, add a placeholder for a table that will list the user's agents, along with stats like sales and revenue for each.++4. **Add CSS:**+ * Create a new CSS file, `dashboard.css`, and link it to your HTML.+ * Add styles to create a clean, modern, and professional-looking dashboard layout.++## Code Example (HTML Structure - `dashboard.html`)+```html+<div class="dashboard-container">+ <aside class="dashboard-sidebar">+ <nav>+ <ul>+ <li><a href="#" class="active">Overview</a></li>+ <li><a href="#">My Agents</a></li>+ <li><a href="#">Analytics</a></li>+ <li><a href="#">Settings</a></li>+ </ul>+ </nav>+ </aside>+ <main class="dashboard-content">+ <h1>Overview</h1>+ <div class="stats-grid">+ <div class="stat-card">+ <h2>Total Revenue</h2>+ <p>$0.00</p>+ </div>+ <div class="stat-card">+ <h2>Total Sales</h2>+ <p>0</p>+ </div>+ </div>+ <div class="chart-container">+ <h2>Sales Over Time</h2>+ <!-- Placeholder for a chart -->+ <canvas id="sales-chart"></canvas>+ </div>+ </main>+</div>+```diff --git a/docs/monetization/11_creator_wallet_ui.md b/docs/monetization/11_creator_wallet_ui.mdnew file mode 100644index 000000000..f444475fa--- /dev/null+++ b/docs/monetization/11_creator_wallet_ui.md@@ -0,0 +1,87 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 11: Creator Wallet Management UI++## Objective+Create a settings page where agent creators can specify the Solana wallet address where they want to receive payments for skill purchases.++## Explanation+To receive payments, creators must provide a destination wallet. This needs to be a secure and user-friendly process. We will create a dedicated UI in the user's profile or dashboard area to manage this. The chosen wallet address will be linked to the agent's on-chain identity.++## Instructions+1. **Design the UI:**+ * Create a new page or a new section in an existing user settings/dashboard page (e.g., `profile.html`).+ * The UI should consist of:+ * An input field for the user to paste their Solana wallet address.+ * A "Save" button.+ * A display area showing the currently saved wallet address, if any.+ * Clear instructions and warnings (e.g., "Use a wallet you control. Payments are irreversible.").++2. **Connect to Backend:**+ * The "Save" button will send the wallet address to a new backend endpoint.++3. **Backend Logic:**+ * Create an endpoint like `POST /api/users/payout-wallet`.+ * **Authentication:** The user must be logged in.+ * **Validation:**+ * The provided string must be a valid Solana public key. Use a library like `@solana/web3.js`'s `PublicKey` constructor to validate.+ * **Storage:**+ * The wallet address should be stored securely. A good place for it is in the `meta` JSONB column of the user's primary `agent_identity` that represents their creator profile, or on the `users` table itself. Let's associate it with their main agent identity.+ * Specifically, update the agent's `meta.onchain.wallet` field. This aligns with the on-chain identity of the agent.++## Code Example (HTML in `profile.html`)++```html+<div class="panel">+ <h2 class="panel-title">Payout Wallet</h2>+ <p class="panel-subtitle">+ Enter the Solana wallet address where you'd like to receive payments for skill sales.+ </p>+ <div class="field">+ <label for="payout-wallet">Solana Wallet Address</label>+ <input type="text" id="payout-wallet" placeholder="Enter your Solana address">+ </div>+ <button id="save-wallet-btn" class="btn">Save Wallet</button>+ <div id="wallet-save-status"></div>+</div>+```++## Code Example (JavaScript)++```javascript+const saveBtn = document.getElementById('save-wallet-btn');+const walletInput = document.getElementById('payout-wallet');+const statusEl = document.getElementById('wallet-save-status');++// On page load, fetch and display the current wallet+fetch('/api/users/me').then(r => r.json()).then(user => {+ const mainAgent = user.identities?.find(id => id.is_primary);+ if (mainAgent?.meta?.onchain?.wallet) {+ walletInput.value = mainAgent.meta.onchain.wallet;+ }+});++saveBtn.addEventListener('click', async () => {+ const newAddress = walletInput.value.trim();+ saveBtn.disabled = true;+ statusEl.textContent = 'Saving...';++ const resp = await fetch('/api/users/payout-wallet', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ wallet_address: newAddress }),+ });++ if (resp.ok) {+ statusEl.textContent = 'Wallet updated successfully!';+ statusEl.style.color = 'var(--ok)';+ } else {+ const { error_description } = await resp.json();+ statusEl.textContent = `Error: ${error_description}`;+ statusEl.style.color = 'var(--err)';+ }+ saveBtn.disabled = false;+});+```diff --git a/docs/monetization/12-sales-analytics-api.md b/docs/monetization/12-sales-analytics-api.mdnew file mode 100644index 000000000..7ce7f448e--- /dev/null+++ b/docs/monetization/12-sales-analytics-api.md@@ -0,0 +1,66 @@+# Prompt 12: Sales Analytics API++## Objective+Create a secure backend API endpoint that retrieves and aggregates sales data for a creator's agents.++## Explanation+The creator dashboard needs data to display. This endpoint will be responsible for querying the database (or blockchain data) to provide the necessary analytics, such as total revenue and sales volume, for the currently logged-in creator.++## Instructions+1. **Record Sales Data:**+ * First, you need data to query. In the `/api/skills/mint` endpoint from Prompt 7, after a successful mint, you must save a record of the sale to a new `sales` table in your database.+ * The `sales` table should include `id`, `agent_id`, `skill_name`, `price`, `currency`, `buyer_wallet`, `transaction_signature`, and a `timestamp`.++2. **Create Analytics Endpoint:**+ * Create a new endpoint, `/api/dashboard/analytics`.+ * This endpoint must be authenticated, ensuring a user can only access their own sales data. It should get the `user_id` from the session.++3. **Query and Aggregate Data:**+ * In the endpoint logic:+ * Find all agents owned by the logged-in user.+ * Query the `sales` table for all sales related to those agents.+ * Use SQL `SUM()` and `COUNT()` to aggregate the data to calculate:+ * Total revenue.+ * Total number of sales.+ * Sales data grouped by day or month for the chart.++4. **Return Data:**+ * Return the aggregated data in a structured JSON format that the frontend can easily consume.++## Code Example (Backend Endpoint - `/api/dashboard/analytics.js`)+```javascript+// This is a conceptual example using a SQL-like query builder++async function getAnalytics(req, res) {+ const userId = req.session.userId; // Get user ID from session+ if (!userId) {+ return res.status(401).json({ error: 'Unauthorized' });+ }++ // Query the database+ const result = await db.query(+ `SELECT+ SUM(price) as total_revenue,+ COUNT(id) as total_sales,+ DATE_TRUNC('day', timestamp) as date,+ COUNT(id) as daily_sales+ FROM sales+ WHERE agent_id IN (SELECT id FROM agents WHERE owner_id = $1)+ GROUP BY DATE_TRUNC('day', timestamp)+ ORDER BY date ASC;+ `, [userId]+ );++ // Process and return data+ const analyticsData = {+ totalRevenue: result.rows.reduce((acc, row) => acc + parseFloat(row.total_revenue), 0),+ totalSales: result.rows.reduce((acc, row) => acc + parseInt(row.total_sales), 0),+ salesOverTime: result.rows.map(row => ({+ date: row.date,+ sales: row.daily_sales+ }))+ };++ res.status(200).json(analyticsData);+}+```diff --git a/docs/monetization/12_creator_payouts_dashboard.md b/docs/monetization/12_creator_payouts_dashboard.mdnew file mode 100644index 000000000..d9cc314f2--- /dev/null+++ b/docs/monetization/12_creator_payouts_dashboard.md@@ -0,0 +1,86 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 12: Creator Payouts Dashboard++## Objective+Create a dashboard for creators to view their sales history and total earnings.++## Explanation+To provide transparency and a good creator experience, we need a dashboard that shows them how much they've earned from their paid skills. This involves aggregating data from the `user_purchased_skills` table and presenting it in a clear, easy-to-understand format.++## Instructions+1. **Create a New Page:**+ * Create a new HTML file for the dashboard, e.g., `creator-dashboard.html`.+ * This page will be accessible to logged-in users from their profile or a main navigation link.++2. **Backend API for Sales Data:**+ * Create a new endpoint, e.g., `GET /api/creators/sales-data`.+ * **Authentication:** Requires a logged-in user.+ * **Database Query:**+ * The endpoint should query the `user_purchased_skills` table.+ * It needs to find all purchases where the `agent_id` belongs to an agent owned by the current user.+ * It should aggregate the data to calculate:+ * Total revenue (sum of `price_amount`).+ * Number of sales.+ * A list of recent sales transactions with details (skill name, agent name, price, date).+ * The data should be grouped by currency if multiple currencies are supported in the future.++3. **Frontend Implementation:**+ * The `creator-dashboard.html` page's JavaScript will call the new API endpoint.+ * **Display Key Metrics:** Show "Total Revenue" and "Total Sales" in prominent summary cards.+ * **Display Sales History:** Render the list of recent transactions in a table or a list format. Each entry should be clear and provide essential information.+ * **Add Charts (Optional but Recommended):** Use a charting library (like Chart.js) to visualize sales over time (e.g., daily or weekly revenue).++## Code Example (Backend API - `GET /api/creators/sales-data`)++```javascript+import { sql } from '../../_lib/db.js';+// ... other imports++export default wrap(async (req, res) => {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized');++ // 1. Get all agents owned by the user+ const userAgents = await sql`+ SELECT id FROM agent_identities WHERE user_id = ${user.id}+ `;+ const agentIds = userAgents.map(a => a.id);++ if (agentIds.length === 0) {+ return json(res, 200, { totalRevenue: 0, salesCount: 0, recentSales: [] });+ }++ // 2. Aggregate sales data for those agents+ const [salesData] = await sql`+ SELECT+ SUM(price_amount) AS total_revenue,+ COUNT(id) AS sales_count+ FROM user_purchased_skills+ WHERE agent_id = ANY(${agentIds})+ `;++ // 3. Get recent sales+ const recentSales = await sql`+ SELECT+ p.skill_name,+ a.name AS agent_name,+ p.price_amount,+ p.price_currency_mint,+ p.created_at+ FROM user_purchased_skills p+ JOIN agent_identities a ON p.agent_id = a.id+ WHERE p.agent_id = ANY(${agentIds})+ ORDER BY p.created_at DESC+ LIMIT 20+ `;++ return json(res, 200, {+ totalRevenue: parseInt(salesData.total_revenue) || 0,+ salesCount: parseInt(salesData.sales_count) || 0,+ recentSales: recentSales+ });+});+```diff --git a/docs/monetization/13-display-sales-analytics.md b/docs/monetization/13-display-sales-analytics.mdnew file mode 100644index 000000000..b6df02995--- /dev/null+++ b/docs/monetization/13-display-sales-analytics.md@@ -0,0 +1,58 @@+# Prompt 13: Display Sales Analytics in Dashboard++## Objective+Fetch data from the new `/api/dashboard/analytics` endpoint and use it to populate the creator dashboard UI with dynamic charts and statistics.++## Explanation+This prompt brings the creator dashboard to life by replacing the static placeholder elements with real, live data from the backend.++## Instructions+1. **Fetch Data on Page Load:**+ * In the JavaScript file for the dashboard (`dashboard.js`), add a function that runs when the page loads.+ * This function should make a `fetch` request to the `/api/dashboard/analytics` endpoint.++2. **Populate Stat Cards:**+ * Once the data is received, update the content of the summary cards for "Total Revenue" and "Total Sales" with the values from the API response.+ * Format the revenue as a currency string (e.g., using `toLocaleString`).++3. **Render the Chart:**+ * Use a charting library like Chart.js to render the `salesOverTime` data.+ * The X-axis should represent the date, and the Y-axis should represent the number of sales.+ * Configure the chart to be a line chart for a clear visual representation of trends.++## Code Example (JavaScript - `dashboard.js`)+```javascript+import Chart from 'chart.js/auto';++async function loadAnalytics() {+ try {+ const response = await fetch('/api/dashboard/analytics');+ if (!response.ok) throw new Error('Failed to fetch analytics');+ const data = await response.json();++ // Populate stat cards+ document.getElementById('total-revenue').textContent = (data.totalRevenue / 1e6).toLocaleString('en-US', { style: 'currency', currency: 'USD' });+ document.getElementById('total-sales').textContent = data.totalSales;++ // Render chart+ const ctx = document.getElementById('sales-chart').getContext('2d');+ new Chart(ctx, {+ type: 'line',+ data: {+ labels: data.salesOverTime.map(item => new Date(item.date).toLocaleDateString()),+ datasets: [{+ label: 'Sales per Day',+ data: data.salesOverTime.map(item => item.sales),+ borderColor: '#4f46e5',+ tension: 0.1+ }]+ }+ });+ } catch (error) {+ console.error('Error loading analytics:', error);+ // Display an error message in the UI+ }+}++document.addEventListener('DOMContentLoaded', loadAnalytics);+```diff --git a/docs/monetization/13_platform_fee_integration.md b/docs/monetization/13_platform_fee_integration.mdnew file mode 100644index 000000000..8c1d02ee0--- /dev/null+++ b/docs/monetization/13_platform_fee_integration.md@@ -0,0 +1,70 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 13: Platform Fee Integration++## Objective+Modify the skill purchase transaction to include a platform fee that is sent to the company's treasury wallet.++## Explanation+To create a sustainable business model, the platform will take a small percentage of each skill sale. This needs to be handled on-chain and transparently. The backend will now construct a transaction with two transfers instead of one: one for the creator's payout and one for the platform fee.++## Instructions+1. **Update Configuration:**+ * Store the platform's treasury wallet address and the fee percentage in a secure configuration file or environment variables (e.g., `PLATFORM_FEE_BPS=500` for 5%, `PLATFORM_TREASURY_WALLET="...address..."`).++2. **Modify the Purchase Preparation API:**+ * Locate the `POST /api/skills/purchase-prep` endpoint.+ * Inside the transaction construction logic, calculate the platform fee from the total skill price. For example, if the fee is 5% (500 basis points), `fee_amount = total_price * 500 / 10000`.+ * The creator's payout is now `creator_amount = total_price - fee_amount`.+ * **Add a second `spl-token` transfer instruction** to the transaction.+ * The first instruction transfers `creator_amount` to the creator's wallet.+ * The second instruction transfers `fee_amount` to the platform's treasury wallet.+ * The user still signs a single transaction, but it now atomically handles both the payout and the platform fee.++3. **Update Purchase Confirmation:**+ * The `POST /api/skills/purchase-confirm` endpoint should be updated to verify this new transaction structure. It now needs to look for *two* `spl-token` transfers and validate that both the creator payout and the platform fee were sent correctly.++## Code Example (Inside `purchase-prep` API)++```javascript+// ... after fetching price and wallets+const PLATFORM_FEE_BPS = 500; // 5%+const PLATFORM_TREASURY_WALLET = new PublicKey("...");+const totalAmount = skillPrice.amount;++const feeAmount = Math.floor(totalAmount * PLATFORM_FEE_BPS / 10000);+const creatorAmount = totalAmount - feeAmount;++// ...+const tx = new Transaction({ /* ... */ });++// Instruction for Creator Payout+tx.add(+ createTransferInstruction(+ buyerAta.address,+ creatorAta.address,+ buyerPublicKey,+ creatorAmount+ )+);++// Instruction for Platform Fee+const platformTreasuryAta = await getOrCreateAssociatedTokenAccount(+ connection,+ buyerPublicKey,+ usdcMint,+ PLATFORM_TREASURY_WALLET+);+tx.add(+ createTransferInstruction(+ buyerAta.address,+ platformTreasuryAta.address,+ buyerPublicKey,+ feeAmount+ )+);++// ... serialize and return the transaction with two instructions+```diff --git a/docs/monetization/14-payout-management-ui.md b/docs/monetization/14-payout-management-ui.mdnew file mode 100644index 000000000..624872896--- /dev/null+++ b/docs/monetization/14-payout-management-ui.md@@ -0,0 +1,55 @@+# Prompt 14: Payout Management UI++## Objective+Add a "Settings" section to the creator dashboard where creators can manage their payout wallet address and view a history of past payouts.++## Explanation+Providing financial controls is crucial for creator trust and usability. This UI will allow creators to easily update where their funds are sent and to track when they have been paid.++## Instructions+1. **Create Settings UI:**+ * In `dashboard.html`, create the structure for the "Settings" tab.+ * Add an input field, pre-filled with the creator's current payout wallet address.+ * Include a "Save" button next to the input field.+ * Add a section for "Payout History" with a placeholder for a table. The table should have columns for `Date`, `Amount`, and `Transaction Signature`.++2. **Implement Update Logic:**+ * In `dashboard.js`, add an event listener to the "Save" button.+ * When clicked, it should take the value from the input field, validate it as a Solana public key, and send it to the backend agent update endpoint (`/api/agents/:id`, similar to Prompt 10).+ * Provide feedback (e.g., "Saved successfully" or "Invalid address") to the user.++3. **Fetch and Display Payout History (Future Prompt):**+ * This prompt focuses on the UI. A future prompt will cover creating the backend logic and a `payouts` table to store and serve the data for the "Payout History" section. For now, the table can remain empty or contain placeholder data.++## Code Example (HTML - `dashboard.html` Settings Tab)+```html+<div id="settings-tab" class="tab-content hidden">+ <h2>Settings</h2>+ <div class="setting-item">+ <h3>Payout Wallet</h3>+ <p>This is the Solana wallet where your earnings will be sent.</p>+ <input type="text" id="payout-wallet-input" value="CURRENT_WALLET_ADDRESS_FROM_API">+ <button id="save-payout-wallet">Save</button>+ </div>+ <div class="setting-item">+ <h3>Payout History</h3>+ <table id="payout-history-table">+ <thead>+ <tr>+ <th>Date</th>+ <th>Amount</th>+ <th>Transaction</th>+ </tr>+ </thead>+ <tbody>+ <!-- Payout rows will be populated here -->+ <tr>+ <td>2026-05-01</td>+ <td>15.50 USDC</td>+ <td><a href="#">view on explorer</a></td>+ </tr>+ </tbody>+ </table>+ </div>+</div>+```diff --git a/docs/monetization/14-ui-transaction-status.md b/docs/monetization/14-ui-transaction-status.mdnew file mode 100644index 000000000..811f6a914--- /dev/null+++ b/docs/monetization/14-ui-transaction-status.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 14: UI for Transaction Status++## Objective+Provide real-time feedback to the user about the status of their purchase transaction.++## Explanation+Blockchain transactions are not instant. To provide a good user experience, the UI should show the user that their transaction is being processed and notify them when it's complete.++## Instructions+1. **Update the Payment Modal:**+ * After a transaction is sent, update the payment modal to show a "Processing..." state.+ * Disable the purchase button to prevent multiple submissions.++2. **Display Confirmation:**+ * Once the transaction is confirmed, show a success message in the modal.+ * Include a link to the transaction on a block explorer like Solscan.++3. **Handle Errors:**+ * If the transaction fails, display a clear error message and allow the user to try again.diff --git a/docs/monetization/14_graceful_tx_failures.md b/docs/monetization/14_graceful_tx_failures.mdnew file mode 100644index 000000000..49b8e8dc0--- /dev/null+++ b/docs/monetization/14_graceful_tx_failures.md@@ -0,0 +1,60 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 14: Handling Transaction Failures Gracefully++## Objective+Improve the frontend purchase flow to provide clear feedback to the user when a transaction fails for any reason.++## Explanation+On-chain transactions can fail for many reasons: insufficient funds, user rejection, network congestion, or a dropped connection. Our UI must handle these scenarios gracefully instead of leaving the user in a stuck or confusing state.++## Instructions+1. **Review the Purchase Flow:**+ * In `src/marketplace.js`, locate the `handlePurchase` function.+ * It should already have a `try...catch` block. We will make the error handling more specific and user-friendly.++2. **Implement Granular Error Handling:**+ * **User Rejection:** The `wallet.signTransaction` call will throw a specific error if the user clicks "Reject" in their wallet. Catch this error and display a message like "Purchase cancelled."+ * **Insufficient Funds:** While hard to detect pre-emptively without extra calls, RPC errors from `sendRawTransaction` often contain clues. If an error occurs during sending or confirmation, provide a generic but helpful message: "Transaction failed. This could be due to insufficient SOL for gas fees or network issues. Please check your wallet and try again."+ * **Timeout:** The `connection.confirmTransaction` can time out. Handle this by informing the user: "Transaction confirmation timed out. It may still succeed. Please check your wallet history or a block explorer."+ * **Backend Errors:** Any failure from our own `prep` or `confirm` APIs should be caught and displayed cleanly.++3. **Update UI State:**+ * Ensure that no matter what error occurs, the "Purchase" button is re-enabled and reset to its original state (e.g., "Purchase for X USDC"), allowing the user to retry.+ * Display the error message in a small, non-intrusive element near the button or as a temporary notification toast.++## Code Example (`src/marketplace.js` - enhanced `catch` block)++```javascript+// ... inside handlePurchase function+} catch (err) {+ console.error('Purchase failed:', err);++ let userMessage = 'An unknown error occurred. Please try again.';++ // Check for specific wallet error codes for user rejection+ if (err.name === 'WalletSignTransactionError' || err.code === 4001) {+ userMessage = 'Purchase cancelled in wallet.';+ } else if (err.message.includes('failed to send')) {+ userMessage = 'Broadcast failed. Check your connection and wallet balance.';+ } else if (err.message.includes('Timed out')) {+ userMessage = 'Confirmation timed out. Please check a block explorer for status.';+ } else if (err.message.includes('Failed to prepare') || err.message.includes('Failed to confirm')) {+ userMessage = 'A server error occurred. Please try again later.';+ }++ // Display the message to the user (e.g., in a status element)+ const statusEl = document.getElementById('purchase-status-indicator'); // Assume this exists+ if (statusEl) {+ statusEl.textContent = userMessage;+ statusEl.style.color = 'var(--err)';+ }++ // Reset the button+ button.disabled = false;+ // You might need to retrieve the price again to format this text correctly+ button.textContent = 'Retry Purchase';+}+```diff --git a/docs/monetization/15-caching-skill-prices.md b/docs/monetization/15-caching-skill-prices.mdnew file mode 100644index 000000000..2beeb04b8--- /dev/null+++ b/docs/monetization/15-caching-skill-prices.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 15: Caching Skill Prices++## Objective+Implement a caching layer to reduce database load and improve the performance of fetching skill prices.++## Explanation+Skill prices are unlikely to change frequently. Caching this data will improve the responsiveness of the marketplace and reduce the number of queries to the database.++## Instructions+1. **Choose a Caching Strategy:**+ * Decide on a caching solution, such as Redis or an in-memory cache.++2. **Implement Caching Logic:**+ * When fetching agent details, first check the cache for the skill prices.+ * If the prices are in the cache, return them directly.+ * If not, fetch them from the database and store them in the cache with an expiration time (e.g., 1 hour).++3. **Cache Invalidation:**+ * When a creator updates their skill prices, invalidate the corresponding cache entry to ensure the new prices are displayed.diff --git a/docs/monetization/15-skill-pricing-management.md b/docs/monetization/15-skill-pricing-management.mdnew file mode 100644index 000000000..9f663cf9c--- /dev/null+++ b/docs/monetization/15-skill-pricing-management.md@@ -0,0 +1,45 @@+# Prompt 15: Skill Pricing Management++## Objective+Create a UI in the creator dashboard that allows creators to set and update prices for their agent's skills.++## Explanation+Pricing needs to be dynamic. This feature empowers creators to manage their own economy by letting them add, change, and remove prices for their skills without needing to edit code or contact support.++## Instructions+1. **Create Pricing UI:**+ * In the "My Agents" tab of the dashboard, for each agent listed, add a "Manage Skills" button.+ * Clicking this button should open a modal or a new page dedicated to that agent's skills.+ * In this view, list all of the agent's available skills.+ * Next to each skill, provide an input field for the price and a dropdown for the currency (e.g., USDC).+ * Include a "Save Prices" button.++2. **Backend API for Pricing:**+ * Create a new backend endpoint, e.g., `/api/agents/:id/skill-prices`.+ * This endpoint should accept a `PUT` or `POST` request with a body containing an object of skill prices, like `{ "skill_one": { "amount": 1000000, "currency": "USDC" }, "skill_two": ... }`.+ * The endpoint should be secure, ensuring only the agent's owner can update its prices.++3. **Database for Prices:**+ * Create a new table, `agent_skill_prices`, with columns like `id`, `agent_id`, `skill_name`, `amount`, and `currency_mint`.+ * The backend endpoint will `INSERT` or `UPDATE` rows in this table based on the incoming data.++4. **Connect UI to API:**+ * When the creator clicks "Save Prices," the frontend should gather the data from all the input fields and send it to the new backend endpoint.+ * The page that displays prices to customers (`marketplace.html`) will need to be updated to fetch from this new table instead of a hardcoded source. This links back to Prompt 1.++## Code Example (UI Concept)+```html+<!-- Inside the "Manage Skills" modal -->+<h3>Manage Prices for Agent 'X'</h3>+<div class="skill-price-editor">+ <label>dance</label>+ <input type="number" value="1.00">+ <span>USDC</span>+</div>+<div class="skill-price-editor">+ <label>tell_joke</label>+ <input type="number" placeholder="Not for sale">+ <span>USDC</span>+</div>+<button id="save-prices-btn">Save Prices</button>+```diff --git a/docs/monetization/15_gasless_transactions.md b/docs/monetization/15_gasless_transactions.mdnew file mode 100644index 000000000..d4db344f0--- /dev/null+++ b/docs/monetization/15_gasless_transactions.md@@ -0,0 +1,74 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 15: Gasless Transactions (Payer Sponsorship)++## Objective+Implement a "gasless" transaction system where the platform sponsors the Solana network fees for skill purchases, improving the user experience.++## Explanation+Users often don't have SOL in their wallets, even if they have USDC. Forcing them to acquire SOL just to pay for a minor gas fee is a major point of friction. We can sponsor these transactions. The user still signs the token transfer, but our backend pays the associated SOL fee. This is done using Solana's "Versioned Transactions" with a Payer.++## Instructions+1. **Platform Payer Keypair:**+ * Create a dedicated Solana keypair for the platform, which will be used to pay for transaction fees.+ * Store this keypair's secret key securely in the backend environment (e.g., in a secrets manager).+ * This wallet must be funded with SOL.++2. **Modify Purchase Preparation API (`purchase-prep`):**+ * Instead of creating a "Legacy" `Transaction`, you will now create a `VersionedTransaction`.+ * The `feePayer` of the transaction will now be the **platform's payer public key**.+ * The user's public key is still the one signing the token transfer instruction itself.+ * After adding the transfer instructions, the transaction is **partially signed by the platform's payer keypair on the backend**.+ * The serialized transaction sent to the frontend is now a partially signed `VersionedTransaction`.++3. **Modify Frontend Signing Logic:**+ * The frontend will receive the partially signed, versioned transaction.+ * The `wallet.signTransaction` method works the same way for the user; they are just signing a transaction where they are not the fee payer.+ * The rest of the flow (send, confirm) remains largely the same.++## Code Example (Backend `purchase-prep` API)++```javascript+import {+ Connection,+ PublicKey,+ TransactionMessage,+ VersionedTransaction,+ Keypair+} from '@solana/web3.js';+// ...++// Load your platform's payer keypair securely+const platformPayer = Keypair.fromSecretKey(Buffer.from(process.env.PAYER_SECRET_KEY, 'base64'));++// ... Inside the endpoint logic+export default wrap(async (req, res) => {+ // ...+ // The buyer is still the authority for the transfer, but not the fee payer+ const buyerPublicKey = new PublicKey(user.wallet_address);++ const instructions = [+ // ... createTransferInstruction for creator payout+ // ... createTransferInstruction for platform fee+ ];++ const { blockhash } = await connection.getLatestBlockhash();+ const messageV0 = new TransactionMessage({+ payerKey: platformPayer.publicKey, // PLATFORM pays the fee+ recentBlockhash: blockhash,+ instructions,+ }).compileToV0Message();++ const tx = new VersionedTransaction(messageV0);++ // The user's wallet will provide the signature for the token transfer+ // We sign it with our payer key to cover the fees+ tx.sign([platformPayer]);++ const serializedTx = Buffer.from(tx.serialize()).toString('base64');++ return json(res, 200, { transaction: serializedTx });+});+```diff --git a/docs/monetization/16-skill-bundles-subscriptions.md b/docs/monetization/16-skill-bundles-subscriptions.mdnew file mode 100644index 000000000..5c3708af1--- /dev/null+++ b/docs/monetization/16-skill-bundles-subscriptions.md@@ -0,0 +1,24 @@+---+status: not-started+---++# Prompt 16: Skill Bundles & Subscriptions++## Objective+Introduce the ability for creators to sell bundles of skills or offer a monthly subscription for access to all their skills.++## Explanation+This is an advanced monetization feature that provides more value to users and more revenue opportunities for creators.++## Instructions+1. **Update Database Schema:**+ * Add new tables to support skill bundles and subscriptions.+ * A `skill_bundles` table would define which skills are in a bundle and the price.+ * A `user_subscriptions` table would track active user subscriptions.++2. **Modify UI:**+ * Update the creator UI to allow them to create and manage bundles/subscriptions.+ * Update the marketplace UI to display these new purchasing options.++3. **Implement Recurring Payments:**+ * For subscriptions, you will need a system to handle recurring payments. This is complex on a blockchain and might require a service like Streamflow or a custom smart contract.diff --git a/docs/monetization/16-subscription-model-database.md b/docs/monetization/16-subscription-model-database.mdnew file mode 100644index 000000000..c97913fbd--- /dev/null+++ b/docs/monetization/16-subscription-model-database.md@@ -0,0 +1,59 @@+# Prompt 16: Subscription Model Database Schema++## Objective+Update the database schema to support recurring subscriptions for agent access, allowing creators to offer monthly or yearly tiers.++## Explanation+Moving beyond individual skill sales, subscriptions offer a predictable revenue stream for creators and a better value proposition for users who want full access. This foundational step involves designing the necessary database tables to track subscription plans and user statuses.++## Instructions+1. **Design `subscription_tiers` Table:**+ * Create a new table named `subscription_tiers`.+ * This table will define the plans a creator can offer for an agent.+ * Columns should include:+ * `id`: Primary key.+ * `agent_id`: Foreign key to the `agents` table.+ * `name`: The name of the tier (e.g., "Pro," "All-Access").+ * `price`: The cost of the subscription.+ * `currency_mint`: The currency of the price.+ * `interval`: The billing period (e.g., 'month', 'year').+ * `description`: A brief description of the tier.++2. **Design `user_subscriptions` Table:**+ * Create a new table named `user_subscriptions` to track which users are subscribed to which tiers.+ * Columns should include:+ * `id`: Primary key.+ * `user_id`: Foreign key to the `users` table.+ * `tier_id`: Foreign key to the `subscription_tiers` table.+ * `start_date`: Timestamp when the subscription started.+ * `end_date`: Timestamp when the subscription is due to expire.+ * `status`: The current status (e.g., 'active', 'cancelled', 'past_due').+ * `last_payment_signature`: The transaction signature of the last successful payment.++3. **Apply Migrations:**+ * Create and run a new database migration script to apply these schema changes.++## SQL Schema Example+```sql+CREATE TABLE subscription_tiers (+ id SERIAL PRIMARY KEY,+ agent_id INTEGER REFERENCES agents(id) ON DELETE CASCADE,+ name VARCHAR(255) NOT NULL,+ price BIGINT NOT NULL, -- in smallest currency unit, e.g., lamports+ currency_mint VARCHAR(255) NOT NULL,+ interval VARCHAR(50) NOT NULL, -- 'month' or 'year'+ description TEXT,+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP+);++CREATE TABLE user_subscriptions (+ id SERIAL PRIMARY KEY,+ user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,+ tier_id INTEGER REFERENCES subscription_tiers(id) ON DELETE CASCADE,+ start_date TIMESTAMP WITH TIME ZONE NOT NULL,+ end_date TIMESTAMP WITH TIME ZONE NOT NULL,+ status VARCHAR(50) NOT NULL,+ last_payment_signature VARCHAR(255),+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP+);+```diff --git a/docs/monetization/17-subscription-purchase-flow.md b/docs/monetization/17-subscription-purchase-flow.mdnew file mode 100644index 000000000..1570199e3--- /dev/null+++ b/docs/monetization/17-subscription-purchase-flow.md@@ -0,0 +1,31 @@+# Prompt 17: Subscription Purchase Flow++## Objective+Implement the UI and backend logic for purchasing a monthly subscription to an agent, which grants access to all its skills.++## Explanation+This prompt builds on the subscription database schema by creating the user-facing flow to purchase a subscription. This will involve presenting subscription tiers, handling payment, and creating the `user_subscriptions` record.++## Instructions+1. **Display Subscription Tiers:**+ * On the agent detail page in the marketplace, if an agent offers subscriptions, display the available tiers (from the `subscription_tiers` table).+ * Each tier should show its name, price, interval (e.g., "$10/month"), and description.+ * Add a "Subscribe" button to each tier.++2. **Create Subscription Checkout API:**+ * Create a new endpoint, e.g., `/api/subscriptions/purchase`.+ * This endpoint will handle the payment logic. Since subscriptions are recurring, a simple transfer is not enough. You need to use a Solana protocol designed for recurring payments, like Solana Pay or a custom smart contract.+ * For this prompt, we can simulate the first payment: the endpoint should behave like the skill purchase endpoint, processing a one-time payment for the first month.++3. **Create `user_subscriptions` Record:**+ * After the first payment is successfully processed, the backend must:+ * Create a new record in the `user_subscriptions` table.+ * Set the `user_id`, `tier_id`, and `status` to 'active'.+ * Set the `start_date` to the current time.+ * Calculate and set the `end_date` (e.g., `start_date` + 1 month).++4. **Connect UI to API:**+ * Wire the "Subscribe" button to call the purchase endpoint and handle the transaction with the user's wallet.++## Note on Recurring Payments+True on-chain recurring payments are complex. They often require users to deposit funds into an escrow contract or use token streaming protocols. This prompt simplifies the task to focus on the initial purchase and record creation, which is the first step in any subscription system. A later, more advanced prompt would cover the on-chain automation for renewals.diff --git a/docs/monetization/17-user-purchase-history.md b/docs/monetization/17-user-purchase-history.mdnew file mode 100644index 000000000..a70cee103--- /dev/null+++ b/docs/monetization/17-user-purchase-history.md@@ -0,0 +1,21 @@+---+status: not-started+---++# Prompt 17: User Purchase History++## Objective+Create a page where users can see a history of all the skills they have purchased.++## Explanation+A purchase history page provides transparency and allows users to keep track of their spending and owned assets.++## Instructions+1. **Create a New API Endpoint:**+ * Develop an endpoint, e.g., `GET /api/users/me/purchases`, that returns a list of all skills purchased by the authenticated user.+ * This will query the `user_skill_purchases` table.++2. **Build the Frontend Page:**+ * Create a new page in the user's profile section.+ * Fetch the purchase history from the API and display it in a clean and organized table.+ * Include details like the skill name, agent name, price paid, and transaction date.diff --git a/docs/monetization/18-gifting-skills.md b/docs/monetization/18-gifting-skills.mdnew file mode 100644index 000000000..a2f2ad867--- /dev/null+++ b/docs/monetization/18-gifting-skills.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 18: Gifting Skills++## Objective+Allow users to purchase a skill and gift it to another user.++## Explanation+Gifting is a great way to encourage user engagement and introduce new users to the platform.++## Instructions+1. **Update the UI:**+ * Add a "Gift" option to the purchase modal.+ * If selected, an input field will appear for the user to enter the recipient's wallet address or username.++2. **Modify the Backend:**+ * The payment processing endpoint will need to accept an optional `recipient_id`.+ * When the purchase is recorded in the `user_skill_purchases` table, it will be associated with the recipient's user ID instead of the sender's.++3. **Notifications:**+ * Implement a notification system to inform the recipient that they have received a gift.diff --git a/docs/monetization/18-subscription-token-gating.md b/docs/monetization/18-subscription-token-gating.mdnew file mode 100644index 000000000..49929add9--- /dev/null+++ b/docs/monetization/18-subscription-token-gating.md@@ -0,0 +1,44 @@+# Prompt 18: Subscription Token Gating++## Objective+Gate agent and skill access based on a user's subscription status.++## Explanation+Similar to gating individual skills with NFT ownership, this prompt applies the same principle to subscriptions. If an agent offers subscriptions, users with an active subscription should get access to all of its paid skills.++## Instructions+1. **Create Subscription Status Endpoint:**+ * Create a new backend endpoint, e.g., `/api/subscriptions/status`.+ * It should take an `agent_id` and `user_id` (from session) as input.+ * The endpoint queries the `user_subscriptions` table to check if there is an 'active' subscription for that user and agent, where the `end_date` is in the future.+ * It should return a simple JSON response, like `{ "is_subscribed": true, "tier": "Pro" }`.++2. **Modify Skill Gating Logic:**+ * Update the `tryUseSkill` function from Prompt 9.+ * Before checking for individual NFT ownership for a paid skill, first check if the user has an active subscription to the agent.+ * Call the new `/api/subscriptions/status` endpoint.+ * If the user `is_subscribed`, grant them access to the skill immediately, bypassing the NFT check.++3. **Update UI Based on Subscription:**+ * On the agent detail page, if a user is already subscribed, the "Unlock" buttons for skills should be hidden or changed to "Use".+ * The "Subscribe" buttons for tiers should be replaced with a message like "You are currently subscribed to the Pro plan."++## Code Example (Backend Status Endpoint)+```javascript+async function getSubscriptionStatus(req, res) {+ const userId = req.session.userId;+ const { agent_id } = req.query;++ const result = await db.query(+ `SELECT * FROM user_subscriptions+ WHERE user_id = $1 AND agent_id = $2 AND status = 'active' AND end_date > NOW()`,+ [userId, agent_id]+ );++ if (result.rows.length > 0) {+ res.status(200).json({ is_subscribed: true });+ } else {+ res.status(200).json({ is_subscribed: false });+ }+}+```diff --git a/docs/monetization/19-free-trials-for-skills.md b/docs/monetization/19-free-trials-for-skills.mdnew file mode 100644index 000000000..58cb88776--- /dev/null+++ b/docs/monetization/19-free-trials-for-skills.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 19: Free Trials for Paid Skills++## Objective+Implement a "free trial" feature that allows users to try a paid skill for a limited time or a limited number of uses.++## Explanation+Free trials can significantly increase the conversion rate for paid skills by allowing users to experience their value before committing to a purchase.++## Instructions+1. **Update Database Schema:**+ * Add a `user_skill_trials` table to track active trials.+ * This table would include `user_id`, `skill_name`, `start_date`, and `end_date` or `usage_count`.++2. **Modify Access Control:**+ * The access control middleware needs to be updated to check for active trials in addition to ownership.+ * If a user has an active trial, they should be allowed to use the skill.++3. **UI for Trials:**+ * Update the marketplace UI to show a "Start Free Trial" button for eligible skills.diff --git a/docs/monetization/19-platform-fee-integration.md b/docs/monetization/19-platform-fee-integration.mdnew file mode 100644index 000000000..51f93f246--- /dev/null+++ b/docs/monetization/19-platform-fee-integration.md@@ -0,0 +1,59 @@+# Prompt 19: Platform Fee Integration++## Objective+Implement a platform fee on all transactions (both individual skill sales and subscription payments).++## Explanation+To create a sustainable business model, the platform needs to take a small percentage of each transaction. This requires modifying the on-chain payment logic to split the payment between the agent creator and the platform's treasury wallet.++## Instructions+1. **Store Platform Wallet Address:**+ * Store the platform's main treasury wallet address in a secure place, like an environment variable (`PLATFORM_TREASURY_WALLET`).++2. **Modify Transaction Logic:**+ * Locate the backend code that constructs the payment transaction (from Prompt 5 and Prompt 17).+ * Instead of a single `SystemProgram.transfer` instruction, the transaction must now include **two** transfer instructions.++3. **Calculate and Split Payment:**+ * Define the platform fee percentage (e.g., 5%).+ * When a payment is made, calculate the fee amount and the creator's share.+ * `platform_fee = total_price * 0.05`+ * `creator_share = total_price * 0.95`+ * The first transfer instruction will send `creator_share` to the `creator_wallet_address`.+ * The second transfer instruction will send `platform_fee` to the `PLATFORM_TREASURY_WALLET`.++4. **Update Database and UI:**+ * Ensure your `sales` table has columns to record the `platform_fee` and `creator_payout` amounts for transparent accounting.+ * The UI should clearly state that the price includes a platform fee.++## Code Example (Updated Solana Transaction)+```javascript+// ...inside the purchase logic+const PLATFORM_FEE_PERCENT = 0.05; // 5%+const platformTreasury = new PublicKey(process.env.PLATFORM_TREASURY_WALLET);+const creatorWallet = new PublicKey(agent.creator_wallet_address);+const totalLamports = price.amount;++const platformFeeLamports = Math.round(totalLamports * PLATFORM_FEE_PERCENT);+const creatorShareLamports = totalLamports - platformFeeLamports;++const transaction = new Transaction()+ .add(+ // First instruction: pay the creator+ SystemProgram.transfer({+ fromPubkey: wallet.publicKey,+ toPubkey: creatorWallet,+ lamports: creatorShareLamports,+ })+ )+ .add(+ // Second instruction: pay the platform+ SystemProgram.transfer({+ fromPubkey: wallet.publicKey,+ toPubkey: platformTreasury,+ lamports: platformFeeLamports,+ })+ );++// Send and confirm the transaction as before...+```diff --git a/docs/monetization/20-analytics-for-creators.md b/docs/monetization/20-analytics-for-creators.mdnew file mode 100644index 000000000..c9f1ca54e--- /dev/null+++ b/docs/monetization/20-analytics-for-creators.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 20: Analytics for Creators++## Objective+Provide creators with analytics about how their skills are performing in the marketplace.++## Explanation+Data-driven insights can help creators optimize their offerings and pricing.++## Instructions+1. **Track Metrics:**+ * Start tracking key metrics, such as skill page views, clicks on the "Purchase" button, and successful purchases.++2. **Create an Analytics Dashboard:**+ * In the creator dashboard, add a new section for analytics.+ * Display charts and graphs for:+ * Sales over time.+ * Conversion rate (views to sales).+ * Top-performing skills.+ * Revenue by skill.diff --git a/docs/monetization/20-referral-system.md b/docs/monetization/20-referral-system.mdnew file mode 100644index 000000000..03aba0eb4--- /dev/null+++ b/docs/monetization/20-referral-system.md@@ -0,0 +1,27 @@+# Prompt 20: Referral System++## Objective+Design and implement a referral system where users can earn a percentage of sales by referring new customers to purchase skills or subscriptions.++## Explanation+Referral programs are a powerful growth marketing tool. By rewarding users for bringing in new customers, we can create a viral loop that accelerates platform adoption. This involves generating unique referral codes and tracking their usage.++## Instructions+1. **Database Schema:**+ * Add a `referral_code` column to the `users` table, which should be a unique, randomly generated string.+ * Create a new `referrals` table to track successful referrals. Columns should include `id`, `referrer_user_id`, `new_user_id`, `sale_id`, and `commission_earned`.++2. **Generate Referral Codes:**+ * When a user signs up, generate a unique referral code for them and store it in their user record.++3. **Track Referrals:**+ * When a new user visits the site via a referral link (e.g., `three.ws/?ref=UNIQUE_CODE`), store the referral code in a cookie or `localStorage`.+ * When that new user eventually makes their first purchase, the backend should check for the referral code.+ * If a valid referral code is present, record the referral in the `referrals` table.++4. **Split Payments for Commission:**+ * The payment transaction logic from Prompt 19 needs to be updated again.+ * If a sale is part of a referral, the transaction will now have **three** transfer instructions: one for the creator, one for the platform, and one for the referrer's commission.++5. **Referral Dashboard UI:**+ * Create a new section in the user's dashboard where they can find their referral link and track how much commission they have earned.diff --git a/docs/monetization/21-affiliate-referral-program.md b/docs/monetization/21-affiliate-referral-program.mdnew file mode 100644index 000000000..4ef9cb4e5--- /dev/null+++ b/docs/monetization/21-affiliate-referral-program.md@@ -0,0 +1,21 @@+---+status: not-started+---++# Prompt 21: Affiliate/Referral Program++## Objective+Create a referral program that rewards users for bringing new customers to the platform.++## Explanation+A referral program can be a powerful engine for growth, incentivizing users to promote the marketplace.++## Instructions+1. **Generate Referral Codes:**+ * Create a system to generate unique referral codes for each user.++2. **Track Referrals:**+ * When a new user signs up or makes a purchase using a referral code, track this relationship in the database.++3. **Reward Referrers:**+ * Implement a system to reward the referrer, for example, with a percentage of the referred user's first purchase, paid out as a platform credit or directly to their wallet.diff --git a/docs/monetization/21-transaction-status-notifications.md b/docs/monetization/21-transaction-status-notifications.mdnew file mode 100644index 000000000..0e77734d7--- /dev/null+++ b/docs/monetization/21-transaction-status-notifications.md@@ -0,0 +1,43 @@+# Prompt 21: Transaction Status Notifications++## Objective+Provide real-time feedback to the user about the status of their purchase transaction, from initiation to final confirmation.++## Explanation+Blockchain transactions aren't instant. A user needs clear, immediate feedback to know that their payment is being processed and to be notified of success or failure. This builds trust and improves the user experience significantly.++## Instructions+1. **Update UI on Submission:**+ * When the user clicks "Confirm Purchase" and approves the transaction in their wallet, immediately update the UI.+ * Disable the purchase button and show a loading spinner with a message like "Processing transaction on the Solana blockchain..."++2. **Use Connection Methods for Status:**+ * The `@solana/web3.js` `Connection` object provides methods to track transaction status.+ * After sending the transaction with `sendTransaction`, you get a `signature`.+ * Use `connection.confirmTransaction(signature, 'processed')`. The promise returned by this method will resolve when the transaction is processed but not yet finalized. You can update the UI here to "Processing..."+ * You can then use a second confirmation with commitment level `'confirmed'` or `'finalized'` for the final success message.++3. **Display Success/Failure Messages:**+ * On successful confirmation, hide the spinner and show a clear success message like, "Purchase complete! You now own the skill."+ * If the transaction fails at any point (e.g., the promise from `sendTransaction` or `confirmTransaction` rejects), display a descriptive error message.+ * Use a library like `notistack` or `react-hot-toast` (if using React) or a simple custom notification component to show these messages as non-modal popups.++## Code Example (Polling for Status)+```javascript+// ... after getting the signature+setUiLoading("Processing transaction...");++try {+ const result = await connection.confirmTransaction(signature, 'processed');++ if (result.value.err) {+ throw new Error('Transaction failed on-chain');+ }++ setUiSuccess("Purchase confirmed! You can now use the skill.");+ // Close the modal and update the UI to show ownership+} catch (error) {+ console.error(error);+ setUiError("Transaction failed. Please try again.");+}+```diff --git a/docs/monetization/22-my-collection-page.md b/docs/monetization/22-my-collection-page.mdnew file mode 100644index 000000000..b08be866d--- /dev/null+++ b/docs/monetization/22-my-collection-page.md@@ -0,0 +1,55 @@+# Prompt 22: "My Collection" Page++## Objective+Create a dedicated page where users can view all the premium skills and agent subscriptions they have purchased.++## Explanation+As users begin to acquire assets on the platform, they need a central place to view their collection. This page acts as their personal inventory, reinforcing the value of their purchases and providing easy access to the agents and skills they've unlocked.++## Instructions+1. **Create New Page:**+ * Create a new HTML file, `collection.html`, and its corresponding JavaScript file, `src/collection.js`.+ * This page must be accessible only to logged-in users.++2. **Backend API for Owned Assets:**+ * Create a new backend endpoint, `/api/users/my-collection`.+ * This endpoint will fetch all the assets owned by the currently logged-in user.+ * It should query the database to find:+ * All purchased skills (by looking at the `sales` table or by querying for their skill NFTs on-chain, though the database is faster).+ * All active subscriptions from the `user_subscriptions` table.++3. **Frontend UI:**+ * On page load, `src/collection.js` should call the `/api/users/my-collection` endpoint.+ * The UI should be divided into two sections: "My Skills" and "My Subscriptions."+ * For each skill, display its name, the agent it belongs to, and a link to that agent's page.+ * For each subscription, display the agent's name, the subscription tier, and the renewal/expiry date.+ * Design the page with clean cards or list items to make the collection easy to browse.++## Code Example (HTML Structure for `collection.html`)+```html+<h1>My Collection</h1>++<section>+ <h2>My Subscriptions</h2>+ <div id="subscriptions-list" class="collection-grid">+ <!-- Subscription cards will be populated here -->+ <div class="card">+ <h3>Agent 'X' - Pro Tier</h3>+ <p>Renews on: 2026-06-04</p>+ <a href="/agent/x">View Agent</a>+ </div>+ </div>+</section>++<section>+ <h2>My Skills</h2>+ <div id="skills-list" class="collection-grid">+ <!-- Skill cards will be populated here -->+ <div class="card">+ <h3>Skill: dance</h3>+ <p>From: Agent 'Y'</p>+ <a href="/agent/y">View Agent</a>+ </div>+ </div>+</section>+```diff --git a/docs/monetization/22-user-reviews-for-skills.md b/docs/monetization/22-user-reviews-for-skills.mdnew file mode 100644index 000000000..8d9086c67--- /dev/null+++ b/docs/monetization/22-user-reviews-for-skills.md@@ -0,0 +1,20 @@+---+status: not-started+---++# Prompt 22: User Reviews and Ratings for Skills++## Objective+Allow users to leave reviews and ratings for the skills they have purchased.++## Explanation+Social proof is a powerful factor in purchasing decisions. Reviews and ratings will help users identify high-quality skills and build trust in the marketplace.++## Instructions+1. **Update Database Schema:**+ * Create a `skill_reviews` table with columns for `skill_name`, `user_id`, `rating` (1-5), and a `comment`.++2. **UI for Reviews:**+ * On the agent detail page, display the average rating for each skill.+ * Add a section where users can read all reviews for a skill.+ * Allow users who have purchased a skill to submit a review.diff --git a/docs/monetization/23-gifting-skills.md b/docs/monetization/23-gifting-skills.mdnew file mode 100644index 000000000..ac64711e0--- /dev/null+++ b/docs/monetization/23-gifting-skills.md@@ -0,0 +1,55 @@+# Prompt 23: Gifting Skills++## Objective+Implement a feature that allows a user to purchase a skill and have the ownership NFT sent to another user's wallet address.++## Explanation+Gifting is a powerful social and commercial feature. It allows users to introduce others to the platform and expands the potential market for creators' skills.++## Instructions+1. **Add "Gift" Option to UI:**+ * In the purchase modal (from Prompt 3), add a checkbox or button that says "This is a gift."+ * When checked, reveal a new input field for the user to enter the recipient's Solana wallet address.++2. **Modify Backend Minting Logic:**+ * Update the `/api/skills/mint` endpoint (from Prompt 7).+ * The endpoint should now optionally accept a `recipient_address` in the request body.+ * If `recipient_address` is provided, the backend must use *that* address as the owner when minting the NFT.+ * If it's not provided, it should default to the wallet address of the user making the purchase (the `user_wallet`).++3. **Update Frontend Request:**+ * In `src/marketplace.js`, when the purchase is confirmed, check if the gift option is enabled.+ * If it is, validate the recipient address on the frontend, and then include it in the body of the `fetch` request to the `/api/skills/mint` endpoint.++4. **Transaction Payer:**+ * The transaction for the *payment* is still paid and signed by the person buying the gift. The only thing that changes is the *destination address* for the NFT being minted.++## Code Example (Frontend `marketplace.js`)+```javascript+// Inside the 'Confirm Purchase' click handler+const isGift = document.getElementById('gift-checkbox').checked;+let recipientAddress = null;++if (isGift) {+ const input = document.getElementById('recipient-address-input');+ // Validate the address+ try {+ new PublicKey(input.value);+ recipientAddress = input.value;+ } catch (e) {+ alert('Invalid recipient address');+ return;+ }+}++// ... after payment is confirmed, call the mint endpoint+const response = await fetch('/api/skills/mint', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ // ... other params like agent_id, skill_name+ user_wallet: wallet.publicKey.toBase58(),+ recipient_address: recipientAddress // will be null if not a gift+ })+});+```diff --git a/docs/monetization/23-on-chain-royalties.md b/docs/monetization/23-on-chain-royalties.mdnew file mode 100644index 000000000..8d7c070e4--- /dev/null+++ b/docs/monetization/23-on-chain-royalties.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 23: On-Chain Royalties for Skills++## Objective+Use an NFT-based approach to represent skill ownership, enabling on-chain royalties for creators.++## Explanation+This is a more decentralized and advanced approach to monetization. Each purchased skill could be represented as an NFT in the user's wallet. The NFT's metadata would grant access to the skill, and royalties could be enforced at the smart contract level.++## Instructions+1. **Smart Contract Development:**+ * Develop a smart contract (e.g., using Anchor for Solana) that can mint "Skill NFTs".+ * The contract would handle the logic for purchasing and transferring these NFTs.+ * Implement the Metaplex protocol for on-chain royalties, so that every time a Skill NFT is resold on a secondary market, the original creator gets a percentage.++2. **Frontend Integration:**+ * The frontend would interact with this smart contract instead of a traditional backend API for purchases.++3. **Access Control:**+ * The access control middleware would check the user's wallet for the presence of the required Skill NFT.diff --git a/docs/monetization/24-dynamic-pricing.md b/docs/monetization/24-dynamic-pricing.mdnew file mode 100644index 000000000..620131f2d--- /dev/null+++ b/docs/monetization/24-dynamic-pricing.md@@ -0,0 +1,20 @@+---+status: not-started+---++# Prompt 24: Dynamic Pricing++## Objective+Allow creators to set dynamic pricing rules for their skills, for example, based on demand or time.++## Explanation+Dynamic pricing can help creators maximize their revenue. For example, they could offer a discount for the first 100 buyers or increase the price as the skill becomes more popular.++## Instructions+1. **UI for Pricing Rules:**+ * In the creator UI, add an advanced section for setting up pricing rules.+ * Example rules: "First 100 purchases cost X", "Price increases by Y after every Z sales".++2. **Backend Logic:**+ * The backend will need a rules engine to calculate the current price of a skill based on these rules and the sales history.+ * This will be a complex piece of logic that needs to be carefully designed and tested.diff --git a/docs/monetization/24-skill-bundling.md b/docs/monetization/24-skill-bundling.mdnew file mode 100644index 000000000..ce8ea4329--- /dev/null+++ b/docs/monetization/24-skill-bundling.md@@ -0,0 +1,42 @@+# Prompt 24: Skill Bundling++## Objective+Allow creators to bundle multiple skills together for a single, often discounted, price.++## Explanation+Bundles are a classic marketing strategy. They increase the average transaction value for creators and provide better value for users who want to acquire multiple skills from a single agent.++## Instructions+1. **Database Schema for Bundles:**+ * Create a `skill_bundles` table. Columns should include `id`, `agent_id`, `name`, `price`, `currency_mint`.+ * Create a `bundle_items` table to link bundles to skills. Columns: `id`, `bundle_id`, `skill_name`.++2. **UI for Creating Bundles:**+ * In the creator dashboard, add a new section for "Manage Bundles."+ * Here, a creator can create a new bundle, give it a name and price, and select which of their existing skills to include in it.++3. **Backend API for Bundles:**+ * Create CRUD endpoints (`/api/agents/:id/bundles`) for creating, updating, and deleting skill bundles.++4. **Display Bundles in Marketplace:**+ * On the agent detail page, display any available bundles, perhaps in their own section above the individual skills.+ * Each bundle should show its name, price, and the list of skills included.+ * Add a "Purchase Bundle" button.++5. **Purchase Logic for Bundles:**+ * When a bundle is purchased, the payment logic is the same (transferring the bundle price).+ * However, the minting logic is different. After the payment is confirmed, the `/api/skills/mint` endpoint must be called in a loop, once for **each skill** included in the bundle, minting multiple NFTs to the user's wallet.++## Code Example (UI Concept on Marketplace Page)+```html+<div class="bundle-card">+ <h3>The 'Dancer's Pack' Bundle</h3>+ <p class="bundle-price">5.00 USDC (Save 20%)</p>+ <ul class="bundle-contents">+ <li>Skill: ballet</li>+ <li>Skill: hip_hop</li>+ <li>Skill: tango</li>+ </ul>+ <button class="purchase-bundle-btn" data-bundle-id="123">Purchase Bundle</button>+</div>+```diff --git a/docs/monetization/25-fiat-on-ramp-integration.md b/docs/monetization/25-fiat-on-ramp-integration.mdnew file mode 100644index 000000000..5ce22c19b--- /dev/null+++ b/docs/monetization/25-fiat-on-ramp-integration.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 25: Fiat On-Ramp Integration++## Objective+Integrate a fiat on-ramp service (like Crossmint or Moonpay) to allow users to purchase skills with a credit card.++## Explanation+To reach the widest possible audience, it's essential to offer a way for non-crypto-native users to participate. A fiat on-ramp will handle the conversion from fiat to the required cryptocurrency, making the process seamless for the user.++## Instructions+1. **Choose a Provider:**+ * Research and select a fiat on-ramp provider that offers a good developer experience and supports Solana.++2. **Integrate their SDK:**+ * In the frontend, integrate the provider's SDK.+ * The "Purchase" button would open their widget, where the user can complete the payment with a credit card.++3. **Webhook for Confirmation:**+ * The on-ramp service will typically send a webhook to your backend when the crypto transaction is complete.+ * Your backend will listen for this webhook, verify it, and then unlock the skill for the user.diff --git a/docs/monetization/25-free-trials-for-skills.md b/docs/monetization/25-free-trials-for-skills.mdnew file mode 100644index 000000000..e1fedaf70--- /dev/null+++ b/docs/monetization/25-free-trials-for-skills.md@@ -0,0 +1,35 @@+# Prompt 25: Free Trials for Skills++## Objective+Implement a "free trial" mechanism that allows users to temporarily access a paid skill for a limited time or a limited number of uses before needing to purchase it.++## Explanation+Free trials are a highly effective way to convert users by letting them experience the value of a premium feature firsthand. This can be implemented using temporary, off-chain access tokens.++## Instructions+1. **Database for Trials:**+ * Create a `skill_trials` table.+ * Columns should include `id`, `user_id`, `skill_name`, `agent_id`, `expiry_date` (for time-based trials) or `uses_remaining` (for usage-based trials).++2. **UI to Start a Trial:**+ * On the marketplace page, next to a paid skill, add a "Start Free Trial" button.++3. **Backend API to Grant Trial:**+ * Create an endpoint, `/api/skills/start-trial`.+ * When a user clicks the button, this endpoint is called.+ * It checks if the user has already had a trial for this skill.+ * If not, it creates a new record in the `skill_trials` table for that user and skill, setting an `expiry_date` (e.g., 24 hours from now) or a `uses_remaining` count (e.g., 3).++4. **Update Gating Logic:**+ * Modify the `tryUseSkill` function from Prompt 9 and Prompt 18.+ * This function now has a more complex order of checks:+ 1. Is the skill free? If yes, allow.+ 2. Does the user have an active subscription? If yes, allow.+ 3. Does the user have a valid NFT for the skill? If yes, allow.+ 4. **New:** Does the user have an active free trial for the skill?+ * To check this, call a new backend endpoint `/api/skills/check-trial`.+ * This endpoint checks the `skill_trials` table. If a valid trial exists, it decrements `uses_remaining` (if applicable) and returns `{"has_trial_access": true}`.+ 5. If all checks fail, deny access and prompt the user to purchase.++## Note on Security+Since trial status is stored in your central database (off-chain), this is less decentralized than NFT ownership but offers more flexibility for implementing complex trial logic (like limiting trials per IP address to prevent abuse).diff --git a/docs/prompts/monetization/02-purchase-skill-button.md b/docs/prompts/monetization/02-purchase-skill-button.mdnew file mode 100644index 000000000..457b7c9b1--- /dev/null+++ b/docs/prompts/monetization/02-purchase-skill-button.md@@ -0,0 +1,74 @@+---+status: not-started+---+# Prompt 2: Add Purchase Button for Priced Skills++## Objective+In the agent detail page, replace the price badge for unowned, paid skills with a "Purchase" button to initiate the buying process.++## Explanation+Displaying the price is the first step. Now, we need to give users a clear call-to-action to buy the skill. This prompt focuses on changing the UI to be interactive. The actual payment flow will be handled in subsequent prompts.++## Instructions+1. **Check Ownership:**+ * The frontend needs to know which skills the current user already owns. Create a new API endpoint (e.g., `/api/users/me/purchased-skills`) that returns a list of skill IDs owned by the authenticated user.+ * In `src/marketplace.js`, fetch the list of purchased skills when the component mounts.++2. **Conditionally Render Button:**+ * Inside the `renderDetail` function, modify the skill rendering loop.+ * For each skill, determine its state: free, paid and owned, or paid and unowned.+ * - If free, show the "Free" badge.+ * - If paid and owned, show an "Owned" badge.+ * - If paid and unowned, show a "Purchase" button with the price.++3. **Button Styling:**+ * Style the "Purchase" button to be a prominent call-to-action.+ * Style the "Owned" badge to give the user clear feedback.++## Code Example (Frontend - `src/marketplace.js`)+```javascript+// Inside renderDetail function, assuming `ownedSkills` is a Set of skill names++const skillPrices = a.skill_prices || {};+$('d-skills').innerHTML = skillsArr.map(s => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ const isOwned = ownedSkills.has(name);+ let badge = '';++ if (price && !isOwned) {+ badge = `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}">${(price.amount / 1e6).toFixed(2)} USDC</button>`;+ } else if (price && isOwned) {+ badge = `<span class="price-badge price-owned">Owned</span>`;+ } else {+ badge = `<span class="price-badge price-free">Free</span>`;+ }+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+}).join(' ');+```++## CSS Example (`/marketplace.css`)+```css+.purchase-btn {+ background-color: #5a67d8;+ color: white;+ border: none;+ padding: 4px 10px;+ font-size: 11px;+ font-weight: 600;+ border-radius: 4px;+ cursor: pointer;+ margin-left: 8px;+ vertical-align: middle;+ transition: background-color 0.2s;+}++.purchase-btn:hover {+ background-color: #434190;+}++.price-owned {+ color: #9ae6b4;+ background-color: rgba(72, 187, 120, 0.1);+}+```diff --git a/docs/prompts/monetization/03-solana-pay-integration.md b/docs/prompts/monetization/03-solana-pay-integration.mdnew file mode 100644index 000000000..086851cb0--- /dev/null+++ b/docs/prompts/monetization/03-solana-pay-integration.md@@ -0,0 +1,65 @@+---+status: not-started+---+# Prompt 3: Solana Pay Integration for Skill Purchases++## Objective+Integrate Solana Pay to allow users to purchase skills using a QR code or wallet deeplink.++## Explanation+We need a robust payment mechanism. Solana Pay is a standard for on-chain payments that provides a great user experience on both desktop and mobile. When a user clicks "Purchase," we will generate a Solana Pay QR code that encodes the transaction details (recipient, amount, currency).++## Instructions+1. **Add Solana Pay Library:**+ * Add the `@solana/pay` library to your frontend dependencies using npm: `npm install @solana/pay`.++2. **Create a Payment Request API:**+ * Create a new backend endpoint, e.g., `/api/payments/request`.+ * This endpoint should take `agentId` and `skillName` as input.+ * It should look up the skill's price and the creator's payout address from the database.+ * Generate a unique reference key (a new Solana public key) for the transaction and store it in a `skill_purchases` table with a `pending` status. This reference will be used for verification later.+ * The endpoint should return a JSON object containing the `recipient` address, `amount`, `splToken` (mint address for USDC), and the `reference` key as a string.++3. **Generate QR Code on Frontend:**+ * In `src/marketplace.js`, add a click handler to the "Purchase" buttons.+ * When a button is clicked, call the `/api/payments/request` endpoint.+ * Use the response data and the `@solana/pay` library to generate a Solana Pay URL.+ * Display a modal with a QR code generated from this URL. The library provides utilities for this.+ * The modal should also include a "Pay with Wallet" button for mobile users, which creates a `solana:PAY_URL` deeplink.++## Code Example (Frontend - `src/marketplace.js`)+```javascript+import { createQR, encodeURL } from '@solana/pay';+import { PublicKey } from '@solana/web3.js';+import BigNumber from 'bignumber.js';++// ... inside the purchase button click handler ...++const skillName = button.dataset.skillName;+const agentId = currentAgent.id;++try {+ const { recipient, amount, splToken, reference } = await post('/api/payments/request', { agentId, skillName });++ const url = encodeURL({+ recipient: new PublicKey(recipient),+ amount: new BigNumber(amount).dividedBy(1e6), // Convert from lamports to token units+ splToken: new PublicKey(splToken),+ reference: new PublicKey(reference),+ label: `3D-Agent Skill Purchase`,+ message: `Skill: ${skillName} for Agent: ${agentId}`,+ });++ // --- Render Modal with QR Code ---+ const qr = createQR(url);+ const modal = document.getElementById('payment-modal');+ const qrContainer = modal.querySelector('.qr-code-container');+ qrContainer.innerHTML = '';+ qr.append(qrContainer);+ modal.style.display = 'block';++} catch (error) {+ console.error('Payment request failed', error);+ // Show an error message to the user+}+```diff --git a/docs/prompts/monetization/04-backend-payment-verification.md b/docs/prompts/monetization/04-backend-payment-verification.mdnew file mode 100644index 000000000..e6729a5f2--- /dev/null+++ b/docs/prompts/monetization/04-backend-payment-verification.md@@ -0,0 +1,71 @@+---+status: not-started+---+# Prompt 4: Backend Payment Verification++## Objective+Create a backend endpoint to verify the Solana Pay transaction and confirm that the skill purchase was successful.++## Explanation+After the user completes the payment, the frontend needs to confirm with the backend that the transaction was valid. The backend will find the transaction on the Solana blockchain using the unique `reference` key we generated earlier, validate it, and update the purchase status in the database.++## Instructions+1. **Create Verification Endpoint:**+ * Create a new backend endpoint, e.g., `GET /api/payments/verify`.+ * It should accept the `reference` public key as a query parameter.++2. **Find and Validate Transaction:**+ * Inside the endpoint, use the Solana Web3 JS library (`@solana/web3.js`) to connect to the blockchain.+ * Use the `findReference` method to find the transaction signature associated with our `reference` public key.+ * Once you have the signature, fetch the full transaction details.+ * Verify that the transaction details (recipient, amount, SPL token mint) match the details stored in your `skill_purchases` table for the given reference. This is crucial for security.++3. **Update Database:**+ * If the transaction is valid, update the corresponding record in the `skill_purchases` table. Set its status from `pending` to `completed` and associate it with the user ID.+ * The endpoint should return a success message.++4. **Frontend Polling:**+ * In the frontend payment modal, after displaying the QR code, start polling the `/api/payments/verify` endpoint every few seconds, sending the `reference` key.+ * When the endpoint returns a success status, close the modal, show a "Purchase Successful" confirmation message, and refresh the agent detail view to show the skill as "Owned".++## Code Example (Backend - `/api/payments/verify.js`)+```javascript+import { Connection, PublicKey } from '@solana/web3.js';+import { findReference, validateTransfer } from '@solana/pay';+import BigNumber from 'bignumber.js';++// ... inside the endpoint handler ...++const { reference } = req.query;+if (!reference) {+ return res.status(400).json({ error: 'Reference key is required' });+}++// 1. Get purchase details from DB+const purchase = await db.getPendingPurchaseByReference(reference);+if (!purchase) {+ return res.status(404).json({ error: 'Pending purchase not found' });+}++// 2. Find transaction on-chain+const connection = new Connection(process.env.SOLANA_RPC_HOST);+const signatureInfo = await findReference(connection, new PublicKey(reference), { finality: 'confirmed' });++// 3. Validate transaction+await validateTransfer(+ connection,+ signatureInfo.signature,+ {+ recipient: new PublicKey(purchase.recipient),+ amount: new BigNumber(purchase.amount).dividedBy(1e6), // Convert to token units+ splToken: new PublicKey(purchase.spl_token_mint),+ reference: new PublicKey(reference),+ },+ { commitment: 'confirmed' }+);++// 4. If validation passes, update DB+await db.markPurchaseCompleted(reference, userId);++res.status(200).json({ status: 'verified' });+```diff --git a/marketplace.html b/marketplace.htmlindex b8ef4a4d5..9878e5e42 100644--- a/marketplace.html+++ b/marketplace.html@@ -13,10 +13,11 @@<link rel="shortcut icon" href="/favicon.ico" /><link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />- <link rel="stylesheet" href="/style.css" />- <link rel="stylesheet" href="/marketplace.css" />+<link rel="stylesheet" href="style.css" />+ <link rel="stylesheet" href="footer.css" />+ <link rel="stylesheet" href="marketplace.css" /><link- href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"rel="stylesheet"/>diff --git a/tasks/monetization-feature/01-display-priced-skills.md b/tasks/monetization-feature/01-display-priced-skills.mdindex 4f41e44f2..44794909b 100644--- a/tasks/monetization-feature/01-display-priced-skills.md+++ b/tasks/monetization-feature/01-display-priced-skills.md@@ -2,8 +2,14 @@status: not-started---+---+status: not-started+---+# Prompt 1: Display Priced Skills in Marketplace+**Status:** Completed+## ObjectiveModify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.@@ -11,17 +17,17 @@ Modify the agent detail page in the marketplace to visually distinguish betweenCurrently, 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.+- [x] **Modify the Backend API:**+ - [x] Locate the API endpoint that serves the agent detail data (`/api/marketplace/agents/:id`). You can find this in `api/marketplace/[action].js`.+ - [x] When fetching agent details, also query the `agent_skill_prices` table to get the prices for the agent's skills.+ - [x] 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..." } }`.++- [x] **Update the Frontend UI:**+ - [x] In `src/marketplace.js`, find the `renderDetail` function.+ - [x] This function receives the agent object, which now includes `skill_prices`.+ - [x] Inside the loop that renders the skills (`d-skills` element), check if a price exists for the current skill.+ - [x] 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).+ - [x] Style the price badge to be visually distinct.## Code Example (Frontend - `src/marketplace.js`)diff --git a/docs/02-backend-create-skill-pricing-table.md b/tasks/monetization-feature/02-backend-create-skill-pricing-table.mdsimilarity index 98%rename from docs/02-backend-create-skill-pricing-table.mdrename to tasks/monetization-feature/02-backend-create-skill-pricing-table.mdindex b019e208e..a9379e4ad 100644--- a/docs/02-backend-create-skill-pricing-table.md+++ b/tasks/monetization-feature/02-backend-create-skill-pricing-table.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 2: Backend - Create Skill Pricing Table## Objectivediff --git a/tasks/monetization-feature/02-create-skill-pricing-table.md b/tasks/monetization-feature/02-create-skill-pricing-table.mdnew file mode 100644index 000000000..a98cc162b--- /dev/null+++ b/tasks/monetization-feature/02-create-skill-pricing-table.md@@ -0,0 +1,51 @@+---+title: "Prompt 2: Create `agent_skill_prices` Table Schema"+status: "not-started"+---++# Prompt 2: Create `agent_skill_prices` Table Schema++## Objective+Define and create the necessary database table to store skill prices set by agent creators.++## Explanation+Before creators can set prices, we need a place in our database to store this information. This task involves creating a new table, `agent_skill_prices`, that will link an agent and a skill to a specific price in a specific currency. This forms the backbone of our pricing system.++## Instructions+1. **Locate the schema definition file:** Find the main `schema.sql` file, likely located at `api/_lib/schema.sql`.+2. **Define the `agent_skill_prices` table:** Add a new `CREATE TABLE` statement to this file. The table should include:+ * `agent_id`: A foreign key referencing the `agents` table.+ * `skill_id`: A string identifier for the skill (e.g., "weather-api", "translation-pro").+ * `amount`: A `BIGINT` to store the price in the smallest denomination of the currency (e.g., lamports for SOL, or 10^-6 for USDC). Using a `BIGINT` avoids floating-point precision issues.+ * `currency_mint`: The public key (as a string) of the SPL token mint for the currency (e.g., `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T` for USDC on Solana Mainnet).+ * A primary key combining `agent_id` and `skill_id` to ensure each skill on an agent has only one price.+ * Timestamps (`created_at`, `updated_at`).+3. **Apply the schema:** Run the updated `schema.sql` against your local database to create the table.++## Code Example (`api/_lib/schema.sql`)++```sql+-- ... other table definitions++-- Stores prices for agent skills, set by the agent's creator.+CREATE TABLE IF NOT EXISTS agent_skill_prices (+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,+ skill_id TEXT NOT NULL,+ 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(),+ PRIMARY KEY (agent_id, skill_id)+);++-- Index for efficient lookups+CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);++-- Auto-update the 'updated_at' column+-- This assumes a 'trigger_set_timestamp' function is already defined in your database.+CREATE TRIGGER set_timestamp+BEFORE UPDATE ON agent_skill_prices+FOR EACH ROW+EXECUTE PROCEDURE trigger_set_timestamp();++```diff --git a/docs/03-backend-seed-skill-pricing-data.md b/tasks/monetization-feature/03-backend-seed-skill-pricing-data.mdsimilarity index 99%rename from docs/03-backend-seed-skill-pricing-data.mdrename to tasks/monetization-feature/03-backend-seed-skill-pricing-data.mdindex 396c54138..0f1bf3c29 100644--- a/docs/03-backend-seed-skill-pricing-data.md+++ b/tasks/monetization-feature/03-backend-seed-skill-pricing-data.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 3: Backend - Seed Skill Pricing Data## Objectivediff --git a/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md b/tasks/monetization-feature/03-creator-ui-for-skill-pricing.mdnew file mode 100644index 000000000..fdbe9e55c--- /dev/null+++ b/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md@@ -0,0 +1,79 @@+---+title: "Prompt 3: Creator UI for Skill Pricing"+status: "not-started"+---++# Prompt 3: Creator UI for Skill Pricing++## Objective+Create a user interface in the agent editor that allows creators to view their agent's skills and set a price for each one.++## Explanation+To enable skill monetization, creators need a simple and intuitive way to manage the prices of their skills. This task involves adding a new section to the `agent-edit.html` page. This section will list all the skills associated with the agent and provide input fields for setting a price and selecting a currency.++## Instructions+1. **Locate the agent editor page:** Open the `agent-edit.html` file.+2. **Add a new "Skill Pricing" section:** Find the area where skills are listed or managed. Add a new section with a clear heading like "Skill Monetization" or "Set Skill Prices".+3. **Render skills with pricing inputs:**+ * Iterate through the agent's skills.+ * For each skill, display its name.+ * Add an `input[type="number"]` for the price amount.+ * Add a `select` dropdown to choose the currency (for now, we can hardcode USDC on Solana, but it should be extensible).+ * Add a "Save Prices" button.+4. **Fetch existing prices:** When the page loads, the frontend should fetch the agent's details, including any already-saved skill prices, and populate the input fields with the current values.+5. **Style the new section:** Ensure the new UI elements are well-styled and fit seamlessly into the existing design of the agent editor.++## Code Example (HTML in `agent-edit.html`)++```html+<!-- Inside the main form or a relevant section of agent-edit.html -->+<div class="panel">+ <h3>Skill Monetization</h3>+ <p class="note">Set a price for your skills. Leave blank for free skills. Prices are set in USDC.</p>+ <div id="skill-pricing-list">+ <!-- Skills will be dynamically rendered here by JavaScript -->+ </div>+ <div class="action-row">+ <button type="button" class="btn-primary" id="save-prices-btn">Save Prices</button>+ </div>+ <p id="save-prices-status" class="form-status" hidden></p>+</div>+```++## Code Example (JavaScript for `agent-edit.html`)++```javascript+// In the script that manages agent-edit.html++function renderSkillPricer(agent) {+ const container = document.getElementById('skill-pricing-list');+ const skills = agent.manifest?.skills || [];+ const prices = agent.skill_prices || {};++ if (!skills.length) {+ container.innerHTML = '<p class="note">This agent has no skills to price.</p>';+ return;+ }++ container.innerHTML = skills.map(skill => {+ const skillId = skill.name || 'unknown-skill';+ const currentPrice = prices[skillId];+ const amount = currentPrice ? (currentPrice.amount / 1e6).toFixed(2) : ''; // Assuming 6 decimal places for USDC++ return `+ <div class="skill-price-row" data-skill-id="${escapeHtml(skillId)}">+ <span class="skill-name">${escapeHtml(skillId)}</span>+ <div class="price-input-wrap">+ <input type="number" class="price-input" min="0" step="0.01" placeholder="Free" value="${amount}">+ <span class="currency-label">USDC</span>+ </div>+ </div>+ `;+ }).join('');+}++// Add event listener for the save button to collect and POST the data.+document.getElementById('save-prices-btn').addEventListener('click', async () => {+ // ... logic to collect prices from inputs and call the backend API ...+});+```diff --git a/docs/04-frontend-create-pricebadge-component.md b/tasks/monetization-feature/04-frontend-create-pricebadge-component.mdsimilarity index 99%rename from docs/04-frontend-create-pricebadge-component.mdrename to tasks/monetization-feature/04-frontend-create-pricebadge-component.mdindex 3b1cb187b..22e4d2045 100644--- a/docs/04-frontend-create-pricebadge-component.md+++ b/tasks/monetization-feature/04-frontend-create-pricebadge-component.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 4: Frontend - Create Reusable PriceBadge Component## Objectivediff --git a/docs/05-frontend-handle-price-loading-states.md b/tasks/monetization-feature/05-frontend-handle-price-loading-states.mdsimilarity index 98%rename from docs/05-frontend-handle-price-loading-states.mdrename to tasks/monetization-feature/05-frontend-handle-price-loading-states.mdindex 4b92bd523..423f4ea68 100644--- a/docs/05-frontend-handle-price-loading-states.md+++ b/tasks/monetization-feature/05-frontend-handle-price-loading-states.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 5: Frontend - Handle Price Loading States## Objectivediff --git a/docs/06-uiux-design-purchase-modal.md b/tasks/monetization-feature/06-uiux-design-purchase-modal.mdsimilarity index 99%rename from docs/06-uiux-design-purchase-modal.mdrename to tasks/monetization-feature/06-uiux-design-purchase-modal.mdindex f6ec5b04e..533980282 100644--- a/docs/06-uiux-design-purchase-modal.md+++ b/tasks/monetization-feature/06-uiux-design-purchase-modal.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 6: UI/UX - Design the Skill Purchase Modal## Objectivediff --git a/docs/07-frontend-implement-purchase-modal-ui.md b/tasks/monetization-feature/07-frontend-implement-purchase-modal-ui.mdsimilarity index 99%rename from docs/07-frontend-implement-purchase-modal-ui.mdrename to tasks/monetization-feature/07-frontend-implement-purchase-modal-ui.mdindex 60a723b6b..5fa1bdb10 100644--- a/docs/07-frontend-implement-purchase-modal-ui.md+++ b/tasks/monetization-feature/07-frontend-implement-purchase-modal-ui.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 7: Frontend - Implement Skill Purchase Modal UI## Objectivediff --git a/tasks/monetization-feature/08-backend-create-purchase-transaction-api.md b/tasks/monetization-feature/08-backend-create-purchase-transaction-api.mdnew file mode 100644index 000000000..798e78a08--- /dev/null+++ b/tasks/monetization-feature/08-backend-create-purchase-transaction-api.md@@ -0,0 +1,74 @@+---+status: not-started+---++# Prompt 8: Backend - Create Purchase Transaction API++## Objective+Create a backend API endpoint to generate Solana Pay transaction requests for skill purchases.++## Explanation+To allow users to buy skills, we need an API that can create a Solana Pay transaction on demand. This endpoint will be called by the frontend when a user clicks the "Purchase" button. It will generate a unique transaction reference and return the necessary details for the frontend to display a Solana Pay QR code.++## Instructions+1. **Create the API Endpoint:**+ * Create a new file, e.g., `api/payments/create-transaction.js`.+ * This endpoint should accept `skill_id` and the `buyer_wallet_address` as input.+ * It should be a `POST` request and require authentication.++2. **Implement the Logic:**+ * Fetch the skill's price from the `agent_skill_prices` table.+ * Fetch the creator's wallet address from the `users` table.+ * Use the Solana Pay SDK to construct a transaction that transfers the correct amount of USDC from the buyer to the creator.+ * Generate a unique reference public key for this transaction. This is crucial for tracking the payment status later.+ * Store the pending transaction details (e.g., reference, skill_id, buyer_id) in a new `skill_purchases` table.+ * Return the Solana Pay URL (`solana:....`) and the `reference` public key to the frontend.++## Code Example (`api/payments/create-transaction.js`)++```javascript+import { Keypair } from '@solana/web3.js';+import { createQR, encodeURL } from '@solana/pay';+// ... other imports for db, etc.++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ return res.status(405).json({ error: 'Method Not Allowed' });+ }++ const { skillId, buyerAddress } = req.body;+ const userId = req.session.userId; // Assuming you have auth middleware++ if (!userId) {+ return res.status(401).json({ error: 'Unauthorized' });+ }++ // 1. Fetch skill price and creator's wallet+ const { price, creatorWallet } = await getSkillPriceAndCreator(skillId);+ if (!price) {+ return res.status(404).json({ error: 'Skill not found or not for sale' });+ }++ // 2. Generate a reference keypair for the transaction+ const reference = new Keypair().publicKey;++ // 3. Store pending purchase+ await recordPendingPurchase(userId, skillId, reference.toBase58());++ // 4. Create Solana Pay URL+ const url = encodeURL({+ recipient: creatorWallet,+ amount: new BigNumber(price.amount / 1e6), // Convert to decimal representation+ splToken: new PublicKey(price.currency_mint),+ reference,+ label: `Skill Purchase: ${skillName}`,+ memo: `SKILL:${skillId}`,+ });++ // 5. Return details to frontend+ res.status(200).json({+ solanaPayUrl: url.toString(),+ reference: reference.toBase58(),+ });+}+```diff --git a/tasks/monetization-feature/09-frontend-integrate-solana-pay.md b/tasks/monetization-feature/09-frontend-integrate-solana-pay.mdnew file mode 100644index 000000000..580b4af0d--- /dev/null+++ b/tasks/monetization-feature/09-frontend-integrate-solana-pay.md@@ -0,0 +1,84 @@+---+status: not-started+---++# Prompt 9: Frontend - Integrate Solana Pay QR Code++## Objective+Connect the purchase modal to the backend, generate a Solana Pay QR code, and display it to the user.++## Explanation+This prompt links our frontend UI to the backend payment logic. When a user clicks "Purchase", we will call the API created in the previous step, receive the Solana Pay URL, and render it as a QR code within the modal. This is the core of the user-facing payment experience.++## Instructions+1. **Add a QR Code Library:**+ * Install a library to generate QR codes, such as `qrious`. You can add it via a script tag or install it via npm.++2. **Handle the Purchase Click:**+ * In `src/marketplace.js`, add an event listener to the "Purchase" button in the modal (`purchase-modal-cta`).+ * When clicked, it should:+ * Show a loading state in the modal status area.+ * Make a `POST` request to your `/api/payments/create-transaction` endpoint, sending the `skillId` and the user's connected wallet address.+ * On success, receive the `solanaPayUrl` and `reference`.++3. **Render the QR Code:**+ * Use the QR code library to generate a QR code from the `solanaPayUrl`.+ * Display the QR code in the modal, replacing the "Purchase" button.+ * Update the status text to "Scan with your Solana wallet to approve."++## Code Example (`src/marketplace.js`)++```javascript+// Add QR library to marketplace.html+// <script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>++async function handlePurchaseClick(event) {+ const cta = event.target;+ const { skillName, amount, mint } = cta.dataset;+ const statusEl = $('purchase-modal-status');+ const modalBody = $('purchase-modal').querySelector('.modal-body');++ statusEl.textContent = 'Generating transaction...';+ cta.disabled = true;++ try {+ const res = await fetch('/api/payments/create-transaction', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ skillId: getSkillIdByName(skillName), // You'll need a way to get the ID+ buyerAddress: window.userWallet.publicKey.toBase58(), // Assuming wallet is connected+ }),+ });++ if (!res.ok) throw new Error('Failed to create transaction');++ const { solanaPayUrl, reference } = await res.json();++ // Hide description, price, etc. to make space for QR+ modalBody.innerHTML = `+ <div id="qr-code-container" style="text-align: center;"></div>+ <div class="status-area">Scan with your Solana wallet to approve.</div>+ `;++ // Render QR code+ new QRious({+ element: $('qr-code-container'),+ value: solanaPayUrl,+ size: 200,+ background: 'white',+ foreground: 'black',+ });++ // Start polling for transaction confirmation+ pollForTransaction(reference);++ } catch (error) {+ statusEl.textContent = `Error: ${error.message}`;+ cta.disabled = false;+ }+}++// Attach listener+$('purchase-modal-cta').addEventListener('click', handlePurchaseClick);+```diff --git a/tasks/monetization-feature/10-backend-verify-payment.md b/tasks/monetization-feature/10-backend-verify-payment.mdnew file mode 100644index 000000000..32960e970--- /dev/null+++ b/tasks/monetization-feature/10-backend-verify-payment.md@@ -0,0 +1,84 @@+---+status: not-started+---++# Prompt 10: Backend - Verify Payment and Unlock Skill++## Objective+Create a backend process to verify Solana Pay transactions and grant the purchased skill to the user upon confirmation.++## Explanation+After the user approves the transaction, our backend needs to confirm that the payment was successfully made. We will do this by polling the Solana blockchain for the transaction signature associated with our unique reference key. Once verified, we will record the purchase and create a record that the user now owns the skill.++## Instructions+1. **Create a Verification Endpoint or Process:**+ * This can be a new API endpoint that the frontend polls (e.g., `/api/payments/verify-transaction?reference=...`) or a background worker.+ * Given a `reference` public key, the process should:+ * Use the Solana `findReference` method from `@solana/pay` to find the transaction signature.+ * This method will repeatedly query the chain until the transaction is found or it times out.++2. **Validate the Transaction:**+ * Once the transaction is found, validate its details:+ * Check that the recipient, amount, and SPL token mint match the expected values for the skill purchase.+ * This step is crucial to prevent users from sending incorrect payments and wrongly getting access.++3. **Grant the Skill:**+ * If validation passes, update the user's record to indicate they own the skill.+ * Create a new table, `unlocked_agent_skills`, with `user_id` and `skill_id` to store this relationship.+ * Update your `skill_purchases` table to mark the purchase as `completed`.++## Code Example (Verification Endpoint)++```javascript+import { findReference, validateTransfer } from '@solana/pay';+import { Connection, clusterApiUrl, PublicKey } from '@solana/web3.js';++// ... db connection++export default async function handler(req, res) {+ const { reference } = req.query;+ if (!reference) {+ return res.status(400).json({ error: 'Reference key is required' });+ }++ try {+ const connection = new Connection(clusterApiUrl('mainnet-beta'));+ const referencePubkey = new PublicKey(reference);++ // 1. Find the transaction+ const signature = await findReference(connection, referencePubkey, { finality: 'confirmed' });++ // 2. Get purchase details from our DB+ const purchase = await getPendingPurchaseByReference(reference);+ if (!purchase) {+ return res.status(404).json({ status: 'not_found' });+ }++ // 3. Validate the transaction against our records+ await validateTransfer(+ connection,+ signature,+ {+ recipient: new PublicKey(purchase.creator_wallet),+ amount: new BigNumber(purchase.amount / 1e6),+ splToken: new PublicKey(purchase.currency_mint),+ reference: referencePubkey,+ },+ { commitment: 'confirmed' }+ );++ // 4. If validation doesn't throw, grant the skill+ await grantSkillToUser(purchase.user_id, purchase.skill_id);+ await markPurchaseAsComplete(purchase.id);++ res.status(200).json({ status: 'confirmed' });++ } catch (error) {+ if (error.message.includes('not found')) {+ res.status(202).json({ status: 'pending' });+ } else {+ res.status(500).json({ status: 'error', message: error.message });+ }+ }+}+```diff --git a/tasks/monetization-feature/README.md b/tasks/monetization-feature/README.mdnew file mode 100644index 000000000..73815c007--- /dev/null+++ b/tasks/monetization-feature/README.md@@ -0,0 +1,35 @@+# Feature: Skill Monetization++This folder contains a series of prompts to guide the development of the skill monetization feature from start to finish. Each file represents a distinct, actionable task.++## Task Status++The status of each task is tracked in its frontmatter (`status: not-started | in-progress | completed`).++| ID | Task | Status |+|----|--------------------------------------------|-------------|+| 01 | Display Priced Skills in Marketplace | `not-started` |+| 02 | Create `agent_skill_prices` Table Schema | `not-started` |+| 03 | Creator UI for Skill Pricing | `not-started` |+| 04 | Backend for Saving Skill Prices | `not-started` |+| 05 | Add "Purchase" Button to Marketplace UI | `not-started` |+| 06 | Implement User Wallet Connection | `not-started` |+| 07 | Frontend Transaction Logic for Purchases | `not-started` |+| 08 | Backend to Verify On-Chain Purchase | `not-started` |+| 09 | Create `user_purchased_skills` Table Schema | `not-started` |+| 10 | Update UI After Purchase | `not-started` |+| 11 | Runtime Check for Skill Ownership | `not-started` |+| 12 | Graceful Handling for Unauthorized Use | `not-started` |+| 13 | Creator Dashboard for Sales Analytics | `not-started` |+| 14 | User-Facing Purchase History Page | `not-started` |+| 15 | Support Multiple Token Currencies | `not-started` |+| 16 | Implement Platform Fee/Revenue Split | `not-started` |+| 17 | Robust Error Handling for Purchase Flow | `not-started` |+| 18 | Add Integration Tests for Purchase Flow | `not-started` |+| 19 | Creator Payout/Withdrawal System (UI) | `not-started` |+| 20 | Creator Payout/Withdrawal System (Backend) | `not-started` |+| 21 | Email Notifications for Sales | `not-started` |+| 22 | On-Chain Skill Price Registry (Advanced) | `not-started` |+| 23 | Add Tooltips and Guides for New UI | `not-started` |+| 24 | Secure API Endpoints with Auth Middleware | `not-started` |+| 25 | Final Feature Polish and Documentation | `not-started` |