Skip to content

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

feat: Implement backend logic for recording earnings after payment confirmation

nirholas758bd0b4812c
diff --git a/docs/monetization-feature/02-backend-create-skill-pricing-table.md b/docs/monetization-feature/02-backend-create-skill-pricing-table.md
new file mode 100644
index 000000000..6a6768360
--- /dev/null
+++ b/docs/monetization-feature/02-backend-create-skill-pricing-table.md
@@ -0,0 +1,55 @@
+---
+status: not-started
+---
+
+# Prompt 2: Create Skill Pricing Table
+
+**Status:** Not Started
+
+## Objective
+Create a database table to store pricing information for agent skills. This is a foundational step for monetizing skills.
+
+## Explanation
+To allow agent creators to set prices for their skills, we need a dedicated table in our database. This table, `agent_skill_prices`, will link a skill to an agent and define its price and currency. We'll use a SQL migration script to create this table.
+
+## Instructions
+1. **Create a new migration file:**
+ - In your database migration tool (e.g., `node-pg-migrate`, `flyway`), create a new migration file. Name it something like `1683158400_create_agent_skill_prices.js`.
+
+2. **Define the table schema:**
+ - The table should include the following columns:
+ - `id`: Primary key (e.g., UUID or auto-incrementing integer).
+ - `agent_id`: Foreign key referencing the `agents` table.
+ - `skill_name`: The name of the skill (e.g., `text-to-speech`). This should match the skill identifier in the agent's definition.
+ - `amount`: The price of the skill in the smallest currency unit (e.g., lamports for SOL, or cents for USD). Use a `BIGINT` to support large numbers.
+ - `currency_mint`: The mint address of the currency token (e.g., the USDC mint address on Solana).
+ - `created_at`: Timestamp of creation.
+ - `updated_at`: Timestamp of last update.
+
+3. **Add constraints:**
+ - Create a unique constraint on `(agent_id, skill_name)` to ensure a skill can only have one price per agent.
+ - Add an index on `agent_id` for faster lookups.
+
+4. **Run the migration:**
+ - Execute the migration to create the table in your database.
+
+## Code Example (SQL)
+
+```sql
+CREATE TABLE agent_skill_prices (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
+ skill_name VARCHAR(255) NOT NULL,
+ amount BIGINT NOT NULL,
+ currency_mint VARCHAR(255) NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE(agent_id, skill_name)
+);
+
+CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);
+```
+
+## Verification
+- After running the migration, connect to your database and verify that the `agent_skill_prices` table exists with the correct schema.
+- You can try inserting a sample record to ensure it works as expected.
diff --git a/docs/monetization-prompts/02-purchase-skill-button.md b/docs/monetization-prompts/02-purchase-skill-button.md
new file mode 100644
index 000000000..731533c75
--- /dev/null
+++ b/docs/monetization-prompts/02-purchase-skill-button.md
@@ -0,0 +1,67 @@
+# Prompt 02: Add Purchase Button for Priced Skills
+
+## Objective
+Add a "Purchase" button next to paid skills on the agent detail page, creating a clear call-to-action for users.
+
+## Explanation
+With prices now visible, the next step is to provide a way for users to initiate a purchase. This prompt focuses on adding the button to the UI. The button's functionality will be implemented in subsequent steps.
+
+## Instructions
+1. **Update the Frontend UI (`src/marketplace.js`):**
+ * Modify the `renderDetail` function.
+ * In the skill rendering loop, if a skill is paid, render a "Purchase" button next to the price badge.
+ * For now, we will assume the user does not own any skills. In a later prompt, we will fetch user ownership data and update the button state (e.g., to a disabled "Unlocked" button).
+ * Add a `data-skill-name` attribute to the button to easily identify which skill is being purchased when the button is clicked.
+
+## Code Example (Frontend - `src/marketplace.js`)
+
+```javascript
+// Inside renderDetail's map function for skills
+const name = typeof s === 'string' ? s : (s.name || '');
+const price = skillPrices[name];
+
+if (price) {
+ // In a future step, isOwned will be dynamically determined.
+ const isOwned = false;
+ const priceText = `${(price.amount / 1e6).toFixed(2)} USDC`;
+ const badge = `<span class="price-badge price-paid">${priceText}</span>`;
+ const button = isOwned
+ ? `<button class="purchase-btn" disabled>Unlocked</button>`
+ : `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}">Purchase</button>`;
+ return `<span class="skill-entry">${escapeHtml(name)}${badge}${button}</span>`;
+} else {
+ const badge = `<span class="price-badge price-free">Free</span>`;
+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
+}
+```
+
+## CSS Example
+
+Add these styles to a relevant CSS file.
+
+```css
+.purchase-btn {
+ margin-left: 8px;
+ padding: 4px 10px;
+ font-size: 12px;
+ font-weight: 600;
+ border-radius: 6px;
+ border: 1px solid #fde047;
+ background-color: transparent;
+ color: #fde047;
+ cursor: pointer;
+ transition: background-color 0.2s, color 0.2s;
+}
+
+.purchase-btn:hover {
+ background-color: #fde047;
+ color: #111;
+}
+
+.purchase-btn:disabled {
+ border-color: #444;
+ color: #444;
+ cursor: not-allowed;
+ background-color: transparent;
+}
+```
diff --git a/docs/monetization-prompts/03-skill-purchase-modal.md b/docs/monetization-prompts/03-skill-purchase-modal.md
new file mode 100644
index 000000000..bf996e7b6
--- /dev/null
+++ b/docs/monetization-prompts/03-skill-purchase-modal.md
@@ -0,0 +1,60 @@
+# Prompt 03: Create Skill Purchase Modal
+
+## Objective
+Create a modal that appears when a user clicks the "Purchase" button, confirming the skill details and price before the transaction.
+
+## Explanation
+A confirmation modal prevents accidental purchases and provides a clear, focused step in the user journey. This modal will be the central point for initiating the wallet transaction.
+
+## Instructions
+1. **Create the Modal HTML:**
+ * Add the HTML structure for a hidden modal to `marketplace.html`. It should include placeholders for the skill name, price, and agent name, along with "Confirm Purchase" and "Cancel" buttons.
+
+2. **Add JavaScript Logic (`src/marketplace.js`):**
+ * Create a new function, `openPurchaseModal(skillName, price, agentName)`. This function will populate the modal with the correct data and make it visible.
+ * Attach an event listener to the `d-skills` container that listens for clicks on `.purchase-btn`.
+ * When a purchase button is clicked, get the skill name from the `data-skill-name` attribute, find its price from the agent data, and call `openPurchaseModal`.
+ * Add event listeners for the "Confirm" and "Cancel" buttons within the modal. For now, they can just log to the console.
+
+## HTML Example (in `marketplace.html`)
+
+```html
+<div id="purchase-modal" class="modal-hidden">
+ <div class="modal-content">
+ <h2>Confirm Purchase</h2>
+ <p>Unlock the skill <strong id="modal-skill-name"></strong> for agent <strong id="modal-agent-name"></strong>?</p>
+ <div class="modal-price">Price: <span id="modal-skill-price"></span></div>
+ <div class="modal-actions">
+ <button id="modal-cancel-btn">Cancel</button>
+ <button id="modal-confirm-btn">Confirm Purchase</button>
+ </div>
+ </div>
+</div>
+```
+
+## JavaScript Example (`src/marketplace.js`)
+
+```javascript
+// At the end of init function
+const skillsContainer = document.getElementById('d-skills');
+skillsContainer.addEventListener('click', (event) => {
+ if (event.target.classList.contains('purchase-btn')) {
+ const skillName = event.target.dataset.skillName;
+ // Assume 'currentAgent' is available in a higher scope
+ const price = currentAgent.skill_prices[skillName];
+ if (price) {
+ openPurchaseModal(skillName, price, currentAgent.name);
+ }
+ }
+});
+
+function openPurchaseModal(skillName, price, agentName) {
+ document.getElementById('modal-skill-name').textContent = skillName;
+ document.getElementById('modal-agent-name').textContent = agentName;
+ const priceText = `${(price.amount / 1e6).toFixed(2)} USDC`;
+ document.getElementById('modal-skill-price').textContent = priceText;
+ document.getElementById('purchase-modal').classList.remove('modal-hidden');
+}
+
+// Add listeners for modal buttons to close it, etc.
+```
diff --git a/docs/monetization-prompts/04-wallet-integration-setup.md b/docs/monetization-prompts/04-wallet-integration-setup.md
new file mode 100644
index 000000000..db9be09f5
--- /dev/null
+++ b/docs/monetization-prompts/04-wallet-integration-setup.md
@@ -0,0 +1,72 @@
+# Prompt 04: Frontend Wallet Integration Setup
+
+## Objective
+Integrate a Solana wallet adapter to allow users to connect their wallets (e.g., Phantom) to the application.
+
+## Explanation
+To perform any on-chain transactions, the user must first connect their cryptocurrency wallet. This step involves adding the necessary libraries and UI elements for wallet connection. We will use the official Solana wallet-adapter libraries.
+
+## Instructions
+1. **Add Wallet-Adapter Libraries:**
+ * Include the Solana wallet-adapter scripts in `marketplace.html`. You can use a CDN like unpkg for this proof-of-concept. You'll need `@solana/wallet-adapter-base` and `@solana/wallet-adapter-wallets`, plus the DOM integration package.
+
+2. **Add "Connect Wallet" Button:**
+ * Add a "Connect Wallet" button to the header of the application. The button text should dynamically update to show the user's wallet address when connected.
+
+3. **Initialize the Wallet Adapter:**
+ * In your main JavaScript file (`src/marketplace.js`), initialize the wallet adapter.
+ * Configure the wallets you want to support (e.g., Phantom, Solflare).
+ * Add logic to the "Connect Wallet" button to trigger the connection prompt.
+ * Listen for connection status changes to update the UI accordingly.
+
+## HTML Example (in `marketplace.html` header)
+
+```html
+<div class="wallet-controls">
+ <button id="connect-wallet-btn">Connect Wallet</button>
+</div>
+```
+
+## JavaScript Example (`src/marketplace.js`)
+
+```javascript
+// This is a simplified example. Refer to Solana wallet-adapter docs for the full setup.
+
+// Use imports if you have a build system, or window vars from CDN
+const { WalletAdapterNetwork } = solanaWalletAdapter;
+const {
+ ConnectionProvider,
+ WalletProvider,
+} = solanaWalletAdapterReact;
+const {
+ WalletModalProvider,
+ WalletMultiButton,
+} = solanaWalletAdapterReactUi;
+
+// In your main app logic
+const network = WalletAdapterNetwork.Devnet;
+const endpoint = web3.clusterApiUrl(network);
+const wallets = [new PhantomWalletAdapter()];
+
+// You would typically wrap your app in providers.
+// For vanilla JS, you'll need to instantiate and manage the adapter manually.
+
+const wallet = ... // initialization logic
+
+const connectBtn = document.getElementById('connect-wallet-btn');
+connectBtn.addEventListener('click', async () => {
+ try {
+ await wallet.connect();
+ } catch (error) {
+ console.error('Failed to connect wallet', error);
+ }
+});
+
+wallet.on('connect', (publicKey) => {
+ connectBtn.textContent = `${publicKey.toBase58().slice(0, 4)}...${publicKey.toBase58().slice(-4)}`;
+});
+
+wallet.on('disconnect', () => {
+ connectBtn.textContent = 'Connect Wallet';
+});
+```
diff --git a/docs/monetization-prompts/05-solana-pay-integration.md b/docs/monetization-prompts/05-solana-pay-integration.md
new file mode 100644
index 000000000..1b394012f
--- /dev/null
+++ b/docs/monetization-prompts/05-solana-pay-integration.md
@@ -0,0 +1,66 @@
+# Prompt 05: Solana Pay Transaction Integration
+
+## Objective
+Integrate Solana Pay into the purchase modal to generate a transaction for the user to sign.
+
+## Explanation
+When the user clicks "Confirm Purchase", we need to construct and present a Solana transaction. We'll use the Solana Pay standard, which allows for reliable transaction requests. The backend will create the transaction, and the frontend will use it.
+
+## Instructions
+1. **Create a Backend Endpoint for Transaction Creation:**
+ * Create a new API endpoint, e.g., `POST /api/transactions/create-skill-purchase`.
+ * This endpoint will take `agentId`, `skillName`, and the `buyerPublicKey` as input.
+ * It should look up the skill price, the creator's destination wallet, and the platform fee wallet.
+ * Using the Solana SDK (`@solana/web3.js`), it will construct a transaction that transfers the correct amount of USDC from the buyer to the creator (and platform).
+ * The endpoint should return the serialized transaction.
+
+2. **Update Frontend Modal Logic:**
+ * In `src/marketplace.js`, modify the event listener for the "Confirm Purchase" button (`#modal-confirm-btn`).
+ * When clicked, it should first check if the user's wallet is connected.
+ * Then, it should make a `POST` request to your new backend endpoint.
+ * The frontend receives the serialized transaction from the backend.
+
+3. **Sign and Send the Transaction:**
+ * Use the wallet-adapter's `sendTransaction` method to ask the user to sign and send the transaction received from the backend.
+ * Handle potential errors during this process (e.g., user rejection).
+
+## JavaScript Example (`src/marketplace.js` - Confirm Button Listener)
+
+```javascript
+const confirmBtn = document.getElementById('modal-confirm-btn');
+confirmBtn.addEventListener('click', async () => {
+ if (!wallet.connected) {
+ alert('Please connect your wallet first.');
+ return;
+ }
+
+ // Get details from modal/app state
+ const skillName = document.getElementById('modal-skill-name').textContent;
+ const buyerPublicKey = wallet.publicKey.toBase58();
+
+ try {
+ // 1. Fetch transaction from backend
+ const response = await fetch('/api/transactions/create-skill-purchase', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ skillName, agentId: currentAgent.id, buyerPublicKey }),
+ });
+ const { transaction } = await response.json();
+
+ // 2. Deserialize and send
+ const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));
+ const tx = solanaWeb3.Transaction.from(Buffer.from(transaction, 'base64'));
+
+ const signature = await wallet.sendTransaction(tx, connection);
+
+ // 3. Start polling for confirmation (covered in next prompt)
+ console.log('Transaction sent with signature:', signature);
+ await connection.confirmTransaction(signature, 'processed');
+ alert('Purchase successful!');
+
+ } catch (error) {
+ console.error('Purchase failed', error);
+ alert('Purchase failed. See console for details.');
+ }
+});
+```
diff --git a/docs/monetization-prompts/06-transaction-status-polling.md b/docs/monetization-prompts/06-transaction-status-polling.md
new file mode 100644
index 000000000..7b1d408d0
--- /dev/null
+++ b/docs/monetization-prompts/06-transaction-status-polling.md
@@ -0,0 +1,58 @@
+# Prompt 06: Transaction Status Polling and Verification
+
+## Objective
+After a transaction is sent, reliably confirm its success by polling a Solana RPC endpoint and then verifying it on the backend.
+
+## Explanation
+Sending a transaction to the network doesn't guarantee its success. We must confirm it has been processed and finalized. The frontend will poll for initial confirmation to give the user quick feedback, and the backend will do a final verification before unlocking the skill.
+
+## Instructions
+1. **Frontend: Poll for Confirmation:**
+ * After sending the transaction with `sendTransaction`, the wallet adapter returns a transaction signature (txid).
+ * Use the `Connection` object's `confirmTransaction` method. This will poll the RPC until the transaction reaches a certain commitment level (e.g., 'processed' or 'confirmed').
+ * While polling, update the UI to show a "Processing..." state in the purchase modal.
+
+2. **Backend: Create a Verification Endpoint:**
+ * Create a new backend endpoint, e.g., `POST /api/skills/purchase/verify`.
+ * This endpoint will receive the `transactionSignature`.
+ * On the backend, use the Solana SDK to fetch the transaction details using the signature.
+
+3. **Backend: Verify Transaction Details:**
+ * In the verification endpoint, inspect the fetched transaction.
+ * Confirm that the transaction involves the correct sender (buyer), receiver (creator), and amount (price). This is a critical security step to prevent users from submitting fake or incorrect transaction signatures.
+ * If the transaction is valid, proceed to record the skill ownership (covered in the next prompt).
+
+## JavaScript Example (`src/marketplace.js` - inside confirm button handler)
+
+```javascript
+// ... after const signature = await wallet.sendTransaction(tx, connection);
+
+// Show processing state in UI
+setModalState('processing');
+
+const { value: status } = await connection.confirmTransaction(signature, 'confirmed');
+
+if (status.err) {
+ console.error('Transaction failed to confirm', status.err);
+ setModalState('error', 'Transaction Failed');
+ return;
+}
+
+// Now that frontend has confirmation, send signature to backend for final verification
+try {
+ const verifyResponse = await fetch('/api/skills/purchase/verify', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ transactionSignature: signature, agentId: currentAgent.id, skillName }),
+ });
+
+ if (!verifyResponse.ok) throw new Error('Backend verification failed');
+
+ setModalState('success', 'Purchase Complete!');
+ // Update UI to show skill as unlocked (covered in next prompt)
+
+} catch (error) {
+ console.error('Backend verification failed', error);
+ setModalState('error', 'Verification Failed');
+}
+```
diff --git a/docs/monetization-prompts/08-purchase-skill-api-endpoint.md b/docs/monetization-prompts/08-purchase-skill-api-endpoint.md
new file mode 100644
index 000000000..91f16af9d
--- /dev/null
+++ b/docs/monetization-prompts/08-purchase-skill-api-endpoint.md
@@ -0,0 +1,75 @@
+# Prompt 08: Backend Purchase API Endpoint
+
+## Objective
+Create the initial backend API endpoint that constructs and returns a Solana transaction for a skill purchase.
+
+## Explanation
+The frontend needs a secure way to get a valid transaction object. The backend is responsible for creating this transaction because it has secure access to critical information like the creator's payout wallet and the correct skill price, preventing tampering.
+
+## Instructions
+1. **Create the API File and Route:**
+ * Create a new API file, e.g., `api/transactions/create-skill-purchase.js`.
+ * This file will handle `POST` requests. It should expect `agentId`, `skillName`, and `buyerPublicKey` in the request body.
+
+2. **Fetch Necessary Data:**
+ * Inside the endpoint logic, perform database lookups to get:
+ * The skill's price from the `agent_skill_prices` table.
+ * The agent creator's payout wallet address from the `users` or `agents` table.
+ * The platform's fee wallet address (can be a constant or from a config file).
+
+3. **Construct the Solana Transaction:**
+ * Use the `@solana/web3.js` SDK.
+ * You will be creating a SPL Token Transfer instruction. The currency is likely USDC, so you'll need its mint address.
+ * The transaction will transfer `X` amount of USDC from the `buyerPublicKey` to the creator's wallet. (Platform fees will be added in a later prompt).
+ * Set the `feePayer` to be the `buyerPublicKey`.
+ * Fetch a recent blockhash.
+
+4. **Serialize and Return the Transaction:**
+ * Serialize the transaction but **do not sign it**. The user's wallet must sign it.
+ * Return the serialized transaction as a base64-encoded string in the JSON response.
+
+## Code Example (Node.js with Express-like framework)
+
+```javascript
+import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
+import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') return res.status(405).end();
+
+ const { agentId, skillName, buyerPublicKey } = req.body;
+
+ // 1. Fetch data from DB (pseudo-code)
+ const priceInfo = await db.getSkillPrice(agentId, skillName); // { amount: 1000000, currency_mint: '...' }
+ const creator = await db.getAgentCreator(agentId); // { payout_wallet: '...' }
+
+ const connection = new Connection(clusterApiUrl('devnet'));
+ const buyer = new PublicKey(buyerPublicKey);
+ const creatorWallet = new PublicKey(creator.payout_wallet);
+ const usdcMint = new PublicKey(priceInfo.currency_mint);
+
+ // 2. Get the buyer's and creator's token accounts
+ const buyerUsdcAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, usdcMint, buyer);
+ const creatorUsdcAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, usdcMint, creatorWallet);
+
+ // 3. Create the transaction
+ const transaction = new Transaction().add(
+ createTransferInstruction(
+ buyerUsdcAccount.address,
+ creatorUsdcAccount.address,
+ buyer,
+ priceInfo.amount // Amount in smallest unit (lamports for SOL, etc.)
+ )
+ );
+
+ transaction.feePayer = buyer;
+ transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
+
+ // 4. Serialize and return
+ const serializedTx = transaction.serialize({ requireAllSignatures: false });
+
+ res.status(200).json({
+ transaction: serializedTx.toString('base64'),
+ });
+}
+```
diff --git a/docs/monetization-prompts/09-verify-solana-transaction-api.md b/docs/monetization-prompts/09-verify-solana-transaction-api.md
new file mode 100644
index 000000000..68b7ebf31
--- /dev/null
+++ b/docs/monetization-prompts/09-verify-solana-transaction-api.md
@@ -0,0 +1,74 @@
+# Prompt 09: Backend Transaction Verification API
+
+## Objective
+Create the backend API endpoint that securely verifies a Solana transaction signature after it has been confirmed on the blockchain.
+
+## Explanation
+This is a critical security step. The frontend informs the backend that a transaction is complete by sending its signature. The backend must then independently fetch the transaction from the blockchain and verify that its contents (amount, sender, receiver) are correct before granting the user access to the skill. This prevents users from sending fake signatures or signatures for unrelated transactions.
+
+## Instructions
+1. **Create the API File and Route:**
+ * Create a new API file, e.g., `api/skills/purchase/verify.js`.
+ * It will handle `POST` requests with `transactionSignature`, `agentId`, and `skillName` in the body.
+
+2. **Fetch the Transaction from the Blockchain:**
+ * Use the `@solana/web3.js` SDK's `connection.getParsedTransaction()` method with the provided signature. This method is useful as it parses the instruction data.
+
+3. **Perform Verification Checks:**
+ * Check if the transaction was successful (`err` field is null).
+ * Look up the expected price and creator wallet from your database for the given `agentId` and `skillName`.
+ * Parse the transaction's instructions to find the token transfer.
+ * **Crucially, verify:**
+ * The transfer `source` matches the buyer's public key (you might need to get this from the user's session or the transaction itself).
+ * The transfer `destination` matches the creator's expected payout wallet.
+ * The transfer `amount` matches the expected price from your database.
+ * The token `mint` matches the expected currency (e.g., USDC).
+
+4. **Handle Verification Outcome:**
+ * If all checks pass, proceed to the next step: recording the ownership in the database.
+ * If any check fails, return a `400 Bad Request` or `403 Forbidden` error with a message like "Transaction verification failed."
+
+## Code Example (Node.js with Express-like framework)
+
+```javascript
+import { Connection, PublicKey } from '@solana/web3.js';
+
+export default async function handler(req, res) {
+ const { transactionSignature, agentId, skillName } = req.body;
+
+ // 1. Get expected data from DB (pseudo-code)
+ const expectedPrice = await db.getSkillPrice(agentId, skillName);
+ const creator = await db.getAgentCreator(agentId);
+ // Assume we get buyer public key from authenticated session
+ const expectedBuyer = new PublicKey(req.session.user.publicKey);
+
+ const connection = new Connection(clusterApiUrl('devnet'));
+
+ // 2. Fetch transaction
+ const tx = await connection.getParsedTransaction(transactionSignature, 'confirmed');
+ if (!tx || tx.meta.err) {
+ return res.status(400).json({ message: "Transaction not found or failed." });
+ }
+
+ // 3. Find the transfer instruction and verify details
+ const transferInstruction = tx.transaction.message.instructions.find(ix => ix.parsed?.type === 'transferChecked');
+
+ if (!transferInstruction) {
+ return res.status(400).json({ message: "No valid transfer instruction found." });
+ }
+
+ const { source, destination, tokenAmount } = transferInstruction.parsed.info;
+ const isVerified = source === expectedBuyer.toBase58() &&
+ destination === creator.payout_wallet &&
+ parseInt(tokenAmount.amount) === expectedPrice.amount;
+
+ // 4. Handle outcome
+ if (isVerified) {
+ // Ownership recording logic comes next
+ await recordSkillOwnership(req.session.user.id, agentId, skillName);
+ res.status(200).json({ message: "Verification successful." });
+ } else {
+ res.status(403).json({ message: "Transaction details do not match expected values." });
+ }
+}
+```
diff --git a/docs/monetization-prompts/10-creator-payout-logic.md b/docs/monetization-prompts/10-creator-payout-logic.md
new file mode 100644
index 000000000..a9f2ee30e
--- /dev/null
+++ b/docs/monetization-prompts/10-creator-payout-logic.md
@@ -0,0 +1,68 @@
+# Prompt 10: Logic for Creator Payouts and Platform Fees
+
+**Status:** - [ ] Not Started
+
+## Objective
+Implement the logic, both on-chain and off-chain, for splitting payments between the agent creator and the platform.
+
+## Explanation
+To create a sustainable business model, the platform will likely take a small fee from each skill purchase. This requires a system to automatically split the incoming funds. This can be done either on-chain with a smart contract or off-chain by having payments go to a platform wallet which then distributes the funds. An on-chain approach is more transparent.
+
+## Instructions
+1. **Design the Payout Flow:**
+ * Decide on the fee structure (e.g., a 5% platform fee).
+ * Decide on the mechanism:
+ * **On-chain (preferred):** A smart contract (or a simple wallet acting as an escrow) receives the payment, then immediately splits it between the creator and the platform treasury.
+ * **Off-chain:** Payment goes to a platform-controlled wallet. A backend process then periodically calculates and sends the creator's share to their wallet.
+
+2. **Implement On-Chain Split (if chosen):**
+ * This is a more advanced task involving Solana smart contract development (e.g., using Anchor).
+ * The frontend transaction would change to call this new smart contract instead of a direct SPL transfer.
+ * The smart contract would require two instructions in the transaction: one to transfer the total amount to the contract, and another to trigger the split.
+
+3. **Implement Off-Chain Split (simpler alternative):**
+ * Modify the SPL transfer logic from Prompt 5. Instead of transferring to the creator's address, transfer to a platform-owned treasury address. This address should be configured per-skill or per-agent in the `agent_skill_prices` table.
+ * Create a backend cron job or batch process (`/api/cron/process-payouts.js`).
+ * This job runs periodically (e.g., daily), queries all purchase records since the last run, calculates the creator's share for each, and queues up the payout transactions.
+ * Use a secure backend wallet to sign and send these payout transactions.
+
+## Code Example (Off-chain Payout Cron Job - `/api/cron/process-payouts.js`)
+
+```javascript
+// This is a conceptual example of a cron job for Vercel
+import { getDB } from './_lib/db';
+import { Connection, Keypair, SystemProgram, Transaction } from '@solana/web3.js';
+// And SPL token transfer functions
+
+const PLATFORM_FEE_PERCENT = 5;
+
+export default async function handler(req, res) {
+ // Secure this endpoint, e.g., with a secret key
+
+ const db = getDB();
+ const pendingPurchases = await db.getUnprocessedPurchases();
+
+ const creatorPayouts = {}; // { [creator_address]: amount_to_pay }
+
+ for (const purchase of pendingPurchases) {
+ const creatorShare = purchase.amount * (1 - PLATFORM_FEE_PERCENT / 100);
+ const creator = purchase.creator_address;
+ creatorPayouts[creator] = (creatorPayouts[creator] || 0) + creatorShare;
+ }
+
+ // Use a secure way to load your backend wallet
+ const platformWallet = Keypair.fromSecretKey(...);
+ const connection = new Connection('your_rpc_url');
+
+ for (const [creator, amount] of Object.entries(creatorPayouts)) {
+ // Construct and send transaction to pay out `amount` to `creator`
+ // This involves creating and sending an SPL token transfer from the platform's wallet
+ // ...
+ }
+
+ // Mark purchases as processed in the DB
+ await db.markPurchasesAsProcessed(pendingPurchases.map(p => p.id));
+
+ res.status(200).json({ success: true, message: 'Payouts processed.' });
+}
+```
diff --git a/docs/monetization-prompts/10-record-skill-ownership.md b/docs/monetization-prompts/10-record-skill-ownership.md
new file mode 100644
index 000000000..2816af465
--- /dev/null
+++ b/docs/monetization-prompts/10-record-skill-ownership.md
@@ -0,0 +1,62 @@
+# Prompt 10: Record Skill Ownership in Database
+
+## Objective
+Create the database schema and logic to record that a user has successfully purchased and unlocked a skill.
+
+## Explanation
+After a transaction is successfully verified, the final step on the backend is to persist the user's ownership of the skill. This record will be the source of truth for all future checks, such as gating skill usage and updating the marketplace UI.
+
+## Instructions
+1. **Design and Create a New Database Table:**
+ * Create a new table named `unlocked_skills` (or similar).
+ * It should contain, at a minimum, the following columns:
+ * `id` (Primary Key)
+ * `user_id` (Foreign Key to your `users` table)
+ * `agent_id` (Foreign Key to your `agents` table)
+ * `skill_name` (String)
+ * `purchase_transaction_signature` (String, for auditing)
+ * `created_at` (Timestamp)
+ * Consider adding a unique constraint on `(user_id, agent_id, skill_name)` to prevent duplicate entries.
+
+2. **Implement the Database Insertion Logic:**
+ * In your backend verification endpoint (`/api/skills/purchase/verify`), after all the checks have passed, add the code to insert a new row into the `unlocked_skills` table.
+ * Pass the authenticated user's ID, the agent ID, the skill name, and the transaction signature to the database query.
+
+3. **Update Agent Details API to Include Ownership:**
+ * Modify the main API that fetches agent details for the marketplace (`/api/marketplace/agents/:id`).
+ * When a user requests this endpoint, it should now also query the `unlocked_skills` table to see which skills that specific user owns for that agent.
+ * Include this ownership information in the API response, perhaps as an array of skill names: `unlocked_skills: ["skill1", "skill2"]`.
+
+4. **Update Frontend to Use Ownership Data:**
+ * In `src/marketplace.js`, when you receive the agent details, use the new `unlocked_skills` array.
+ * In your skill rendering loop, set the `isOwned` variable based on whether the current skill's name is in this array. This will now correctly show the "Purchase" or "Unlocked" button.
+
+## SQL Schema Example
+
+```sql
+CREATE TABLE unlocked_skills (
+ id SERIAL PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES users(id),
+ agent_id INTEGER NOT NULL REFERENCES agents(id),
+ skill_name VARCHAR(255) NOT NULL,
+ purchase_transaction_signature VARCHAR(128) NOT NULL UNIQUE,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE (user_id, agent_id, skill_name)
+);
+```
+
+## Frontend Code Example (`src/marketplace.js`)
+
+```javascript
+// Inside renderDetail function, after fetching agent 'a'
+const unlockedSkills = a.unlocked_skills || [];
+
+// Inside the skillsArr.map loop
+const name = s.name || '';
+const price = a.skill_prices[name];
+
+if (price) {
+ const isOwned = unlockedSkills.includes(name); // <-- This is the new logic
+ // ... rest of the button rendering logic
+}
+```
diff --git a/docs/monetization-prompts/11-api-security-for-purchase.md b/docs/monetization-prompts/11-api-security-for-purchase.md
new file mode 100644
index 000000000..dd71b478d
--- /dev/null
+++ b/docs/monetization-prompts/11-api-security-for-purchase.md
@@ -0,0 +1,70 @@
+# Prompt 11: API Security for Purchase Flow
+
+## Objective
+Implement essential security measures, including user authentication and input validation, for all monetization-related API endpoints.
+
+## Explanation
+Monetization APIs handle real money and user entitlements, making them a prime target for abuse. It's critical to ensure that only authenticated users can make purchases for themselves and that all incoming data is sanitized and validated to prevent exploits.
+
+## Instructions
+1. **Implement User Authentication Middleware:**
+ * Ensure all monetization endpoints (`/api/transactions/*`, `/api/skills/purchase/*`) are protected by an authentication middleware.
+ * This middleware should verify the user's session (e.g., via a JWT token, session cookie, or API key).
+ * If the user is not authenticated, the request should be rejected with a `401 Unauthorized` error.
+ * The authenticated user's data (especially `user_id` and `publicKey`) should be attached to the request object for later use.
+
+2. **Enforce Authorization:**
+ * A user should only be able to purchase skills for their own account. The `user_id` used when recording skill ownership should come from the secure session, *not* from the request body.
+
+3. **Implement Input Validation:**
+ * For every monetization endpoint, validate the request body.
+ * Use a library like `zod`, `joi`, or a simple custom validation function.
+ * **Checks for `/api/transactions/create-skill-purchase`:**
+ * `agentId`: should be a valid ID format.
+ * `skillName`: should be a non-empty string.
+ * `buyerPublicKey`: should be a valid Solana public key format.
+ * **Checks for `/api/skills/purchase/verify`:**
+ * `transactionSignature`: should be a valid Solana transaction signature format.
+ * `agentId` and `skillName`: same as above.
+ * If validation fails, return a `400 Bad Request` error with a clear message indicating the invalid field.
+
+## Code Example (Express.js-style Middleware)
+
+```javascript
+// middleware/auth.js
+export function requireAuth(req, res, next) {
+ // Logic to verify session token (e.g., from Authorization header)
+ const user = verifyToken(req.headers.authorization);
+
+ if (!user) {
+ return res.status(401).json({ message: "Authentication required." });
+ }
+ req.user = user; // Attach user to the request
+ next();
+}
+
+// api/skills/purchase/verify.js
+import { requireAuth } from 'middleware/auth';
+import { z } from 'zod';
+
+const purchaseSchema = z.object({
+ transactionSignature: z.string().min(80).max(100), // Basic validation
+ agentId: z.number().int(),
+ skillName: z.string().min(1),
+});
+
+// Apply middleware and validation
+export default async function handler(req, res) {
+ requireAuth(req, res, () => {
+ const validation = purchaseSchema.safeParse(req.body);
+ if (!validation.success) {
+ return res.status(400).json({ message: "Invalid input", errors: validation.error.issues });
+ }
+
+ // --- Main endpoint logic ---
+ // Use req.user.id instead of any user ID from the body
+ const userId = req.user.id;
+ // ...
+ });
+}
+```
diff --git a/docs/monetization-prompts/11-user-purchased-skills.md b/docs/monetization-prompts/11-user-purchased-skills.md
new file mode 100644
index 000000000..e9b520bf3
--- /dev/null
+++ b/docs/monetization-prompts/11-user-purchased-skills.md
@@ -0,0 +1,93 @@
+# Prompt 11: Display User's Purchased Skills in Profile
+
+**Status:** - [ ] Not Started
+
+## Objective
+Create a section in the user's profile or dashboard page (`profile.html` or a new dashboard page) where they can see all the agent skills they have purchased.
+
+## Explanation
+Users need a centralized place to view their digital assets. This enhances the sense of ownership and provides a useful overview of their collection of skills.
+
+## Instructions
+1. **Create a Backend Endpoint:**
+ * Develop an API endpoint, e.g., `/api/users/me/purchased-skills`.
+ * This endpoint should be authenticated.
+ * It should query the `user_agent_skills` table for all records matching the logged-in user's ID.
+ * To make the output more useful, it should join with the `agents` table to include details about the agent for each skill (e.g., agent name and image).
+ * The endpoint should return an array of objects, each containing skill name, agent details, and purchase date.
+
+2. **Develop the Frontend UI:**
+ * On the user's profile page (`profile.html`), add a new tab or section for "My Purchased Skills".
+ * When the page loads (or this section is viewed), make a request to the new API endpoint.
+ * Render the list of purchased skills. Each item in the list should display:
+ * The skill name.
+ * The name of the agent it belongs to (and maybe a thumbnail).
+ * The date of purchase.
+ * A link to the agent's detail page in the marketplace.
+
+## Code Example (Backend - `/api/users/me/purchased-skills.js`)
+
+```javascript
+import { getDB } from './_lib/db';
+
+export default async function handler(req, res) {
+ // Assume user is authenticated
+ const userId = req.user.id;
+
+ const db = getDB();
+ try {
+ // This query would join user_agent_skills with agents table
+ const skills = await db.query(
+ `SELECT uas.skill_name, uas.created_at, a.name as agent_name, a.slug as agent_slug, a.thumbnail_url as agent_thumbnail
+ FROM user_agent_skills uas
+ JOIN agents a ON uas.agent_id = a.id
+ WHERE uas.user_id = $1
+ ORDER BY uas.created_at DESC`,
+ [userId]
+ );
+
+ res.status(200).json({ skills });
+ } catch (error) {
+ console.error('Failed to fetch purchased skills:', error);
+ res.status(500).json({ error: 'Failed to fetch skills.' });
+ }
+}
+```
+
+## Code Example (JavaScript for `profile.html`)
+
+```javascript
+async function loadPurchasedSkills() {
+ const container = $('purchased-skills-list');
+ container.innerHTML = 'Loading...';
+
+ try {
+ const response = await fetch('/api/users/me/purchased-skills');
+ if (!response.ok) throw new Error('Failed to load skills');
+
+ const { skills } = await response.json();
+
+ if (!skills.length) {
+ container.innerHTML = 'You have not purchased any skills yet.';
+ return;
+ }
+
+ container.innerHTML = skills.map(skill => `
+ <div class="skill-item">
+ <img src="${skill.agent_thumbnail || '/placeholder.png'}" alt="${skill.agent_name}" class="agent-thumb">
+ <div>
+ <div class="skill-name">${skill.skill_name}</div>
+ <div class="agent-name">for <a href="/marketplace/${skill.agent_slug}">${skill.agent_name}</a></div>
+ <div class="purchase-date">Purchased on ${new Date(skill.created_at).toLocaleDateString()}</div>
+ </div>
+ </div>
+ `).join('');
+
+ } catch (error) {
+ container.innerHTML = 'Error loading your skills.';
+ }
+}
+
+// Call this function when the page loads
+loadPurchasedSkills();
+```
diff --git a/docs/monetization-prompts/12-creator-payout-setup.md b/docs/monetization-prompts/12-creator-payout-setup.md
new file mode 100644
index 000000000..ef8b775a1
--- /dev/null
+++ b/docs/monetization-prompts/12-creator-payout-setup.md
@@ -0,0 +1,55 @@
+# Prompt 12: Creator Payout Wallet Setup
+
+## Objective
+Allow agent creators to specify and save a Solana wallet address for receiving payments.
+
+## Explanation
+To pay creators, we need to know where to send the funds. This involves adding a field to the database for their payout address and creating a UI and API for them to manage this setting.
+
+## Instructions
+1. **Update Database Schema:**
+ * Add a new column to your `users` table (or whichever table represents your creators).
+ * The column should be named `payout_wallet_address` or similar.
+ * It should be a `VARCHAR` or `TEXT` field, capable of storing a Solana public key (e.g., up to 44 characters). It can be nullable, as a user might not be a creator.
+
+2. **Create API Endpoint for Saving Wallet Address:**
+ * Create a new API endpoint, e.g., `PUT /api/users/payout-settings`.
+ * This endpoint should be protected by authentication middleware.
+ * It will accept a new `payout_wallet_address` in the request body.
+ * Validate that the provided string is a valid Solana public key.
+ * Update the `payout_wallet_address` for the authenticated user in the database.
+
+3. **Update "Create Transaction" Endpoint:**
+ * Modify the `POST /api/transactions/create-skill-purchase` endpoint.
+ * When fetching creator details, retrieve the new `payout_wallet_address`.
+ * Use this address as the destination for the payment transfer in the Solana transaction. If the address is not set, the transaction should fail with an error indicating the creator has not configured their payouts.
+
+## SQL Schema Example (Alter Table)
+
+```sql
+ALTER TABLE users
+ADD COLUMN payout_wallet_address VARCHAR(44) NULL;
+```
+
+## API Validation Example (Node.js)
+
+```javascript
+import { PublicKey } from '@solana/web3.js';
+
+function isValidSolanaAddress(address) {
+ try {
+ new PublicKey(address);
+ return true;
+ } catch (e) {
+ return false;
+ }
+}
+
+// In your PUT /api/users/payout-settings endpoint
+const { payout_wallet_address } = req.body;
+if (!isValidSolanaAddress(payout_wallet_address)) {
+ return res.status(400).json({ message: "Invalid Solana wallet address." });
+}
+
+// ... proceed to update database for req.user.id
+```
diff --git a/docs/monetization-prompts/12-on-chain-receipts-as-nfts.md b/docs/monetization-prompts/12-on-chain-receipts-as-nfts.md
new file mode 100644
index 000000000..2455cb569
--- /dev/null
+++ b/docs/monetization-prompts/12-on-chain-receipts-as-nfts.md
@@ -0,0 +1,77 @@
+# Prompt 12: Generate On-Chain Receipts as NFTs
+
+**Status:** - [ ] Not Started
+
+## Objective
+Issue a unique, non-transferable NFT to the user upon a successful skill purchase, serving as an on-chain receipt and proof of ownership.
+
+## Explanation
+Using NFTs as receipts provides a permanent, verifiable, and user-owned record of their purchase on the blockchain. This can unlock future possibilities like community-gated access or special privileges for skill owners. We can use a service like Metaplex for this.
+
+## Instructions
+1. **Set up NFT Minting Infrastructure:**
+ * This is a significant step. You can use Metaplex's Candy Machine or their newer Core standards. For simple receipts, a direct mint via the Metaplex Umi library might be sufficient.
+ * You'll need a backend wallet with SOL to pay for minting fees.
+
+2. **Modify the Purchase Verification Endpoint:**
+ * In `/api/marketplace/purchase-skill.js`, after successfully verifying the transaction and recording the purchase in the database, trigger the NFT minting process.
+ * The metadata for the NFT should include:
+ * Name: e.g., "Skill Receipt: 'sentiment-analysis'"
+ * Symbol: e.g., "3WS-SKILL"
+ * Description: "This NFT represents ownership of the 'sentiment-analysis' skill for the agent 'AI Market Analyst'."
+ * Attributes: Agent Name, Skill Name, Purchase Date.
+ * Image: A custom image for skill receipts, or maybe the agent's thumbnail.
+
+3. **Mint and Send the NFT:**
+ * The backend will construct and sign the transaction to create the mint account, create the token account for the user, and mint the NFT to that account.
+ * The NFT should ideally be non-transferable to act as a "soul-bound" token representing access, not a speculative asset. This can be set with Metaplex's standards.
+
+4. **Update Database Record:**
+ * After minting, store the NFT's mint address in the `user_agent_skills` table. This links the off-chain record to the on-chain asset.
+
+## Code Example (Conceptual Backend - adding to `purchase-skill.js`)
+
+```javascript
+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
+import { mplCore, createV1, mintV1 } from '@metaplex-foundation/mpl-core';
+import { keypairIdentity, Pda } from '@metaplex-foundation/umi';
+
+// After successfully recording purchase in DB...
+async function mintReceiptNFT(userAddress, agent, skillName) {
+ const umi = createUmi('your_rpc_url').use(mplCore());
+
+ // Use a secure way to load your backend/minter wallet
+ const minterKeypair = ...;
+ umi.use(keypairIdentity(minterKeypair));
+
+ const newMint = Pda.find(umi.context, 'core-mint', [minterKeypair.publicKey, 0]);
+
+ await createV1(umi, {
+ mint: newMint,
+ name: `Skill: ${skillName}`,
+ uri: `https://your-api.com/api/nft-metadata/${agent.id}/${skillName}`,
+ plugins: [
+ // This is conceptual - the exact non-transferable implementation
+ // depends on the Metaplex standard you choose (e.g., locking delegates).
+ ]
+ }).sendAndConfirm(umi);
+
+ await mintV1(umi, {
+ mint: newMint.publicKey,
+ authority: minterKeypair,
+ assetOwner: new PublicKey(userAddress),
+ }).sendAndConfirm(umi);
+
+ return newMint.publicKey;
+}
+
+// In the main handler:
+if (verificationSuccess) {
+ await db.recordSkillPurchase(userId, agentId, skillName);
+ const nftMintAddress = await mintReceiptNFT(userWalletAddress, agent, skillName);
+ await db.updatePurchaseWithNftAddress(purchaseId, nftMintAddress);
+
+ return res.status(200).json({ success: true, message: 'Purchase successful!', receiptNft: nftMintAddress });
+}
+```
+*Note: This is a highly simplified example. NFT minting with Metaplex requires careful setup and handling of accounts and authorities.*
diff --git a/docs/monetization-prompts/13-allow-free-skills.md b/docs/monetization-prompts/13-allow-free-skills.md
new file mode 100644
index 000000000..f184f6036
--- /dev/null
+++ b/docs/monetization-prompts/13-allow-free-skills.md
@@ -0,0 +1,86 @@
+# Prompt 13: Allow Creators to List Skills for Free
+
+**Status:** - [ ] Not Started
+
+## Objective
+Enhance the skill monetization interface to allow creators to explicitly list a skill as "Free" or remove its price, making it available to all users without a purchase.
+
+## Explanation
+Not all skills should require payment. Creators may want to offer some skills for free as a preview or for community-building. The system needs to support toggling a skill between a paid and free state.
+
+## Instructions
+1. **Update the UI for Price Management:**
+ * In the "Skill Monetization" section of `agent-edit.html`, for each skill, add a "Make Free" or "Remove Price" button next to the pricing inputs.
+ * If a skill currently has a price, this button should be active. If it's already free, the button can be disabled or hidden.
+ * The UI should visually indicate that a skill is free (e.g., by displaying "Free" instead of price inputs).
+
+2. **Create a Backend Endpoint for Removing Prices:**
+ * Create a new API endpoint, e.g., `api/agents/remove-skill-price.js`.
+ * This endpoint must be authenticated and verify that the user is the agent's creator.
+ * It should accept `agentId` and `skillName`.
+ * The handler will `DELETE` the corresponding record from the `agent_skill_prices` table.
+
+3. **Connect Frontend to Backend:**
+ * In the JavaScript for the agent edit page, add an event listener for the "Remove Price" button.
+ * When clicked, it should call the new `DELETE` endpoint.
+ * On success, update the UI for that skill to show it as free and clear the price input fields.
+
+## Code Example (JavaScript for `agent-edit.html`)
+
+```javascript
+// Inside the event listener for the skill pricing list
+$('skill-pricing-list').addEventListener('click', async (e) => {
+ // ... (handle 'set-price-btn' clicks)
+
+ if (e.target.classList.contains('remove-price-btn')) {
+ const skillName = e.target.dataset.skillName;
+
+ // Optional: Ask for confirmation
+ if (!confirm(`Are you sure you want to make the skill "${skillName}" free?`)) {
+ return;
+ }
+
+ const response = await fetch('/api/agents/remove-skill-price', {
+ method: 'POST', // Or DELETE, depending on your API design
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ agentId: currentAgentId,
+ skillName,
+ }),
+ });
+
+ if (response.ok) {
+ showToast('Skill is now free!', 'success');
+ // Re-render the pricing section to reflect the change
+ // Or dynamically update the specific row
+ const priceInput = document.querySelector(`input[data-skill-name="${skillName}"]`);
+ priceInput.value = '';
+ } else {
+ showToast('Failed to update skill.', 'error');
+ }
+ }
+});
+```
+
+## Code Example (Backend - `api/agents/remove-skill-price.js`)
+
+```javascript
+import { getDB } from './_lib/db';
+
+export default async function handler(req, res) {
+ // Assume user is authenticated and is the agent owner
+ const { agentId, skillName } = req.body;
+
+ const db = getDB();
+ try {
+ await db.query(
+ 'DELETE FROM agent_skill_prices WHERE agent_id = $1 AND skill_name = $2',
+ [agentId, skillName]
+ );
+ res.status(200).json({ success: true, message: 'Skill price removed.' });
+ } catch (error) {
+ console.error('Failed to remove skill price:', error);
+ res.status(500).json({ error: 'Failed to update skill.' });
+ }
+}
+```
diff --git a/docs/monetization-prompts/13-platform-fee-logic.md b/docs/monetization-prompts/13-platform-fee-logic.md
new file mode 100644
index 000000000..60c91f452
--- /dev/null
+++ b/docs/monetization-prompts/13-platform-fee-logic.md
@@ -0,0 +1,66 @@
+# Prompt 13: Platform Fee Logic
+
+## Objective
+Implement the logic to automatically take a platform fee from each skill purchase transaction.
+
+## Explanation
+A platform fee is a common monetization strategy. This involves splitting the payment from the buyer into two parts: one for the creator and one for the platform. This logic should be handled securely on the backend when the transaction is created.
+
+## Instructions
+1. **Configure Platform Wallet:**
+ * Store the platform's fee-collecting wallet address in a secure configuration file or environment variable on your backend. Do not hardcode it in the API logic.
+
+2. **Define Platform Fee Rate:**
+ * Define the platform's fee percentage (e.g., `5%` or `0.05`) in the same configuration.
+
+3. **Update the "Create Transaction" Endpoint:**
+ * In your `POST /api/transactions/create-skill-purchase` endpoint:
+ * After fetching the skill price, calculate the fee amount (e.g., `feeAmount = price * platformFeeRate`).
+ * Calculate the creator's proceeds (`creatorAmount = price - feeAmount`). Ensure you are working with integers to avoid floating-point issues.
+ * Add a **second** SPL Token Transfer instruction to the Solana transaction.
+ * The first instruction will transfer `creatorAmount` from the buyer to the creator.
+ * The second instruction will transfer `feeAmount` from the buyer to the platform's wallet.
+ * The transaction will now contain two separate transfer instructions. The Solana runtime will execute them atomically.
+
+4. **Update the "Verify Transaction" Endpoint:**
+ * Your verification logic at `POST /api/skills/purchase/verify` must also be updated.
+ * It should now look for **two** transfer instructions in the fetched transaction.
+ * It must verify that both transfers are correct: the right amount to the right creator, and the right fee amount to the right platform wallet. Verification fails if either is incorrect.
+
+## Code Example (Create Transaction Endpoint with Fee)
+
+```javascript
+// ... inside /api/transactions/create-skill-purchase
+
+const PLATFORM_FEE_RATE = 0.05; // 5%
+const PLATFORM_WALLET = new PublicKey(process.env.PLATFORM_WALLET_ADDRESS);
+
+const price = priceInfo.amount;
+const feeAmount = Math.round(price * PLATFORM_FEE_RATE);
+const creatorAmount = price - feeAmount;
+
+// ... get buyerUsdcAccount, creatorUsdcAccount, etc.
+const platformUsdcAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, usdcMint, PLATFORM_WALLET);
+
+const transaction = new Transaction()
+ .add(
+ // Instruction 1: Payment to Creator
+ createTransferInstruction(
+ buyerUsdcAccount.address,
+ creatorUsdcAccount.address,
+ buyer,
+ creatorAmount
+ )
+ )
+ .add(
+ // Instruction 2: Fee to Platform
+ createTransferInstruction(
+ buyerUsdcAccount.address,
+ platformUsdcAccount.address,
+ buyer,
+ feeAmount
+ )
+ );
+
+// ... set feePayer, blockhash, and serialize
+```
diff --git a/docs/monetization-prompts/14-creator-dashboard-backend.md b/docs/monetization-prompts/14-creator-dashboard-backend.md
new file mode 100644
index 000000000..504c8ab8f
--- /dev/null
+++ b/docs/monetization-prompts/14-creator-dashboard-backend.md
@@ -0,0 +1,57 @@
+# Prompt 14: Creator Dashboard - Backend
+
+## Objective
+Create the backend API endpoints required to power a dashboard for creators to track their sales and earnings.
+
+## Explanation
+To empower creators, we need to give them visibility into their performance. This involves creating secure, read-only endpoints that aggregate sales data from the database.
+
+## Instructions
+1. **Design API Endpoints:**
+ * Plan a few key endpoints for the creator dashboard. For example:
+ * `GET /api/creator/dashboard/stats`: Returns key stats like total revenue, total sales, and average sale price.
+ * `GET /api/creator/dashboard/sales-history`: Returns a paginated list of individual sales, including skill name, date, and amount earned.
+ * `GET /api/creator/dashboard/sales-by-skill`: Returns an aggregate of sales grouped by skill name.
+
+2. **Implement `stats` Endpoint:**
+ * This endpoint should be protected by authentication.
+ * It needs to query your transaction or unlocked skills database.
+ * To get total revenue, you'll need to join your `unlocked_skills` table with `agent_skill_prices` and filter by the agents owned by the current user (`req.user.id`).
+ * Sum the prices of all skills sold. Remember to subtract the platform fee from the creator's view of revenue.
+ * Return the aggregated data as a JSON object.
+
+3. **Implement `sales-history` Endpoint:**
+ * This endpoint will also perform a join similar to the stats endpoint.
+ * Instead of aggregating, it will return a list of individual sales records.
+ * Implement pagination using `LIMIT` and `OFFSET` in your SQL query (or the equivalent in your ORM) to handle potentially large numbers of sales.
+ * Return the list and pagination metadata (e.g., `total_pages`, `current_page`).
+
+## Database Query Example (PostgreSQL for Stats)
+
+```sql
+-- This query calculates total revenue and sales for a specific creator (user_id = $1)
+SELECT
+ -- Sum of prices, adjusted for platform fee (e.g., 5%)
+ SUM(prices.amount * (1 - 0.05)) AS total_revenue,
+ COUNT(unlocked.id) AS total_sales
+FROM
+ unlocked_skills AS unlocked
+JOIN
+ agents ON unlocked.agent_id = agents.id
+JOIN
+ agent_skill_prices AS prices ON unlocked.agent_id = prices.agent_id AND unlocked.skill_name = prices.skill_name
+WHERE
+ -- Filter for sales of agents owned by the logged-in creator
+ agents.creator_id = $1;
+```
+
+## API Response Example (`/stats`)
+
+```json
+{
+ "totalRevenue": 85500000,
+ "totalSales": 92,
+ "topSellingSkill": "AdvancedDataAnalysis",
+ "currency": "USDC"
+}
+```
diff --git a/docs/monetization-prompts/14-skill-gating-logic.md b/docs/monetization-prompts/14-skill-gating-logic.md
new file mode 100644
index 000000000..0077c6ac0
--- /dev/null
+++ b/docs/monetization-prompts/14-skill-gating-logic.md
@@ -0,0 +1,77 @@
+# Prompt 14: Implement Skill Gating Logic
+
+**Status:** - [ ] Not Started
+
+## Objective
+Enforce access control for skills, preventing users from using or executing a paid skill unless they have purchased it.
+
+## Explanation
+Skill gating is the core of the monetization feature. Once a skill is marked as paid, the system must check for ownership before allowing it to be executed. This check should happen both on the backend (for security) and frontend (for a better user experience).
+
+## Instructions
+1. **Backend Gating:**
+ * Identify the API endpoint that executes or "performs" a skill (e.g., `/api/agent-actions.js` or a similar handler for `perform-skill`).
+ * Before executing a skill, this endpoint must perform a check:
+ * Is the skill a paid skill for this agent? (Query `agent_skill_prices`).
+ * If it is paid, does the logged-in user own it? (Query `user_agent_skills`).
+ * If the user does not own the paid skill, return a `403 Forbidden` error with a clear message like "You must purchase this skill to use it."
+
+2. **Frontend UI Gating:**
+ * The UI should visually indicate that a skill is locked if it's paid and not owned.
+ * For example, on the agent detail page or in a chat interface where skills can be triggered, the button or control for a locked skill should be disabled or styled differently.
+ * When a user tries to interact with a locked skill, the UI should guide them to purchase it (e.g., by showing a tooltip or popping up the purchase modal).
+
+## Code Example (Backend - e.g., in `/api/agent-actions.js`)
+
+```javascript
+// Inside the handler for performing a skill
+export default async function handler(req, res) {
+ // Assume user is authenticated
+ const userId = req.user.id;
+ const { agentId, skillName, args } = req.body;
+
+ const db = getDB();
+
+ // Check if the skill is priced
+ const skillPrice = await db.getSkillPrice(agentId, skillName);
+
+ if (skillPrice) {
+ // It's a paid skill, so check for ownership
+ const hasOwnership = await db.checkSkillOwnership(userId, agentId, skillName);
+ if (!hasOwnership) {
+ return res.status(403).json({
+ error: 'Access Denied',
+ message: 'You must purchase this skill to use it.'
+ });
+ }
+ }
+
+ // If we get here, the user has access. Proceed with skill execution.
+ // ... (rest of the skill execution logic)
+}
+```
+
+## Code Example (Frontend UI - Conceptual)
+
+```javascript
+// When rendering a list of skill buttons for an agent to use
+function renderSkillButtons(agent, purchasedSkills) {
+ const container = document.getElementById('agent-skill-buttons');
+
+ container.innerHTML = agent.skills.map(skill => {
+ const isPaid = !!agent.skill_prices[skill.name];
+ const isOwned = purchasedSkills.includes(skill.name);
+ const isLocked = isPaid && !isOwned;
+
+ if (isLocked) {
+ return `<button class="skill-btn locked" title="Purchase this skill to use it.">
+ ${escapeHtml(skill.name)} (Locked)
+ </button>`;
+ } else {
+ return `<button class="skill-btn" data-skill-name="${skill.name}">
+ ${escapeHtml(skill.name)}
+ </button>`;
+ }
+ }).join('');
+}
+```
diff --git a/docs/monetization-prompts/15-creator-earnings-dashboard.md b/docs/monetization-prompts/15-creator-earnings-dashboard.md
new file mode 100644
index 000000000..c95b8a372
--- /dev/null
+++ b/docs/monetization-prompts/15-creator-earnings-dashboard.md
@@ -0,0 +1,84 @@
+# Prompt 15: Create a Creator Dashboard for Earnings
+
+**Status:** - [ ] Not Started
+
+## Objective
+Develop a dashboard page for creators to track their sales and earnings from the skills they've monetized.
+
+## Explanation
+To create a healthy ecosystem, creators need visibility into how their paid skills are performing. A dedicated dashboard provides them with key metrics like total revenue, number of sales, and a breakdown of earnings per skill.
+
+## Instructions
+1. **Design the Dashboard UI:**
+ * Create a new page, e.g., `creator-dashboard.html`.
+ * This page should be accessible to logged-in users.
+ * Design sections for:
+ * **Key Metrics:** Total revenue, total sales, number of monetized skills.
+ * **Earnings Breakdown:** A table or list showing each monetized skill, its price, number of sales, and total revenue generated.
+ * **Transaction History:** A list of recent sales, including the skill, date, and amount.
+
+2. **Create Backend Endpoints for Dashboard Data:**
+ * Create an endpoint `/api/creators/me/dashboard-stats`.
+ * This authenticated endpoint will fetch and aggregate data for the logged-in user:
+ * Query the `agent_skill_prices` table for all skills priced by the creator.
+ * For each priced skill, query the `user_agent_skills` table to count the number of sales.
+ * Calculate total revenue and other key metrics.
+ * The endpoint should return a JSON object with all the data needed to populate the dashboard.
+ * You might want a separate, paginated endpoint for the detailed transaction history.
+
+3. **Connect Frontend to Backend:**
+ * In the JavaScript for `creator-dashboard.html`, make a request to the new dashboard endpoint when the page loads.
+ * Use the returned data to populate the different sections of the dashboard.
+ * Use a library for charts (e.g., Chart.js) to visualize earnings over time if desired.
+
+## Code Example (Backend - `/api/creators/me/dashboard-stats.js`)
+
+```javascript
+import { getDB } from './_lib/db';
+
+export default async function handler(req, res) {
+ // Assume user is authenticated and we have their user_id and wallet address
+ const creatorId = req.user.id;
+
+ const db = getDB();
+ try {
+ // Get all agents owned by the creator
+ const creatorAgents = await db.query('SELECT id FROM agents WHERE creator_id = $1', [creatorId]);
+ const agentIds = creatorAgents.map(a => a.id);
+
+ // Get all sales for those agents
+ const sales = await db.query(
+ `SELECT asp.skill_name, asp.amount, a.name as agent_name
+ FROM user_agent_skills uas
+ JOIN agent_skill_prices asp ON uas.agent_id = asp.agent_id AND uas.skill_name = asp.skill_name
+ JOIN agents a ON uas.agent_id = a.id
+ WHERE uas.agent_id = ANY($1::uuid[])`,
+ [agentIds]
+ );
+
+ let totalRevenue = 0;
+ let totalSales = sales.length;
+ const skillBreakdown = {};
+
+ for (const sale of sales) {
+ totalRevenue += parseInt(sale.amount, 10);
+ const key = `${sale.agent_name} - ${sale.skill_name}`;
+ if (!skillBreakdown[key]) {
+ skillBreakdown[key] = { sales: 0, revenue: 0 };
+ }
+ skillBreakdown[key].sales++;
+ skillBreakdown[key].revenue += parseInt(sale.amount, 10);
+ }
+
+ res.status(200).json({
+ totalRevenue,
+ totalSales,
+ skillBreakdown,
+ });
+
+ } catch (error) {
+ console.error('Failed to fetch dashboard stats:', error);
+ res.status(500).json({ error: 'Failed to fetch stats.' });
+ }
+}
+```
diff --git a/docs/monetization-prompts/15-skill-pricing-management-ui.md b/docs/monetization-prompts/15-skill-pricing-management-ui.md
new file mode 100644
index 000000000..6688edd44
--- /dev/null
+++ b/docs/monetization-prompts/15-skill-pricing-management-ui.md
@@ -0,0 +1,70 @@
+# Prompt 15: Skill Pricing Management - UI
+
+## Objective
+Create a user interface on the agent creation/editing page that allows creators to set and update prices for their skills.
+
+## Explanation
+Creators need a simple and intuitive way to manage the prices of their skills. This involves adding new form elements to the page where they configure their agents.
+
+## Instructions
+1. **Design the UI:**
+ * On the page where a creator edits their agent (e.g., `agent-edit.html`), locate the section where skills are listed or added.
+ * For each skill listed, add a price input field and a currency selector (for now, this can be a disabled dropdown showing "USDC").
+ * If a skill is meant to be free, the creator should be able to leave the price field blank or set it to 0.
+ * Add a "Save Prices" or "Update Agent" button to submit the changes.
+
+2. **Implement Frontend Logic:**
+ * When the agent edit page loads, it should fetch the agent's details, including the existing `skill_prices` map.
+ * Use this data to populate the price input fields for each skill.
+ * When the "Save" button is clicked, gather all the skill names and their new prices from the input fields.
+ * Structure this data into a map, e.g., `{ "skill_one": 10.50, "skill_two": 0 }`.
+ * Make a `PUT` request to a new backend API endpoint to save these prices.
+
+## HTML Example (Inside an agent edit form)
+
+```html
+<div id="skill-pricing-section">
+ <h3>Manage Skill Prices</h3>
+
+ <!-- This would be dynamically generated -->
+ <div class="skill-price-entry">
+ <label for="price-skill_one">Skill One</label>
+ <input type="number" id="price-skill_one" name="skill_prices[skill_one]" placeholder="e.g., 5.00">
+ <span>USDC</span>
+ </div>
+
+ <div class="skill-price-entry">
+ <label for="price-skill_two">Skill Two</label>
+ <input type="number" id="price-skill_two" name="skill_prices[skill_two]" placeholder="Leave blank for Free">
+ <span>USDC</span>
+ </div>
+
+ <button id="save-prices-btn">Save Prices</button>
+</div>
+```
+
+## JavaScript Example (on Save button click)
+
+```javascript
+document.getElementById('save-prices-btn').addEventListener('click', async () => {
+ const prices = {};
+ const agentId = /* get agent ID from page */;
+
+ document.querySelectorAll('.skill-price-entry').forEach(entry => {
+ const input = entry.querySelector('input[type="number"]');
+ const skillName = input.name.match(/\[(.*?)\]/)[1]; // Extracts "skill_one"
+ const price = parseFloat(input.value) || 0;
+
+ // Convert to smallest unit (e.g., 1 USDC = 1,000,000)
+ prices[skillName] = price * 1e6;
+ });
+
+ await fetch(`/api/agents/${agentId}/prices`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ prices })
+ });
+
+ // Show success message
+});
+```
diff --git a/docs/monetization-prompts/16-skill-pricing-management-api.md b/docs/monetization-prompts/16-skill-pricing-management-api.md
new file mode 100644
index 000000000..8ce459253
--- /dev/null
+++ b/docs/monetization-prompts/16-skill-pricing-management-api.md
@@ -0,0 +1,81 @@
+# Prompt 16: Skill Pricing Management - API
+
+## Objective
+Create the backend API endpoint to allow creators to save the prices they set for their skills.
+
+## Explanation
+This endpoint will receive the pricing information from the UI and persist it in the `agent_skill_prices` database table. It needs to be secure and handle updates efficiently.
+
+## Instructions
+1. **Create the Database Table (if not exists):**
+ * You should have a table `agent_skill_prices`. If not, create it.
+ * Columns: `id`, `agent_id`, `skill_name`, `amount` (use a numeric type that can handle large integers, like `BIGINT`), `currency_mint`.
+ * Create a unique constraint on `(agent_id, skill_name)`.
+
+2. **Create the API Endpoint:**
+ * Create a new endpoint, e.g., `PUT /api/agents/:id/prices`.
+ * The `:id` parameter will be the agent's ID.
+ * Protect this endpoint with authentication middleware.
+
+3. **Implement Authorization and Validation:**
+ * Verify that the authenticated user (`req.user.id`) is the actual creator of the agent with the given `:id`. If not, return `403 Forbidden`.
+ * The request body will contain a `prices` object (a map of skill names to amounts).
+ * Validate this object: ensure it's a map, keys are strings, and values are non-negative integers.
+
+4. **Implement Database Logic (Upsert):**
+ * Iterate through the `prices` map from the request body.
+ * For each skill, perform an "upsert" operation in the `agent_skill_prices` table:
+ * If a row already exists for that `agent_id` and `skill_name`, `UPDATE` its `amount`.
+ * If it doesn't exist, `INSERT` a new row.
+ * If a skill's price is set to 0, you can either store it as 0 or `DELETE` the corresponding row, effectively making it a free skill. Deleting is often cleaner.
+
+## SQL Upsert Example (PostgreSQL)
+
+```sql
+INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
+VALUES ($1, $2, $3, $4)
+ON CONFLICT (agent_id, skill_name)
+DO UPDATE SET amount = EXCLUDED.amount;
+```
+
+## API Logic Example (Node.js)
+
+```javascript
+// PUT /api/agents/:id/prices
+export default async function handler(req, res) {
+ // Assume auth middleware has run
+ const agentId = parseInt(req.query.id);
+ const creatorId = req.user.id;
+
+ // 1. Authorization
+ const agent = await db.getAgent(agentId);
+ if (agent.creator_id !== creatorId) {
+ return res.status(403).json({ message: "You are not the creator of this agent." });
+ }
+
+ const { prices } = req.body; // e.g., { "skill_one": 5000000 }
+
+ // 2. Database updates in a transaction
+ const dbClient = await db.getClient();
+ try {
+ await dbClient.query('BEGIN');
+ for (const skillName in prices) {
+ const amount = prices[skillName];
+ if (amount > 0) {
+ // Perform UPSERT
+ await dbClient.query(upsertSql, [agentId, skillName, amount, 'USDC_MINT_ADDRESS']);
+ } else {
+ // Perform DELETE for skills set to 0
+ await dbClient.query(deleteSql, [agentId, skillName]);
+ }
+ }
+ await dbClient.query('COMMIT');
+ res.status(200).json({ message: "Prices updated successfully." });
+ } catch (e) {
+ await dbClient.query('ROLLBACK');
+ res.status(500).json({ message: "Failed to update prices." });
+ } finally {
+ dbClient.release();
+ }
+}
+```
diff --git a/docs/monetization-prompts/16-support-multiple-currencies.md b/docs/monetization-prompts/16-support-multiple-currencies.md
new file mode 100644
index 000000000..be86ea30f
--- /dev/null
+++ b/docs/monetization-prompts/16-support-multiple-currencies.md
@@ -0,0 +1,64 @@
+# Prompt 16: Implement Different Currencies (SOL, etc.)
+
+**Status:** - [ ] Not Started
+
+## Objective
+Extend the skill monetization feature to support payments in different SPL tokens, starting with SOL (as Wrapped SOL).
+
+## Explanation
+Currently, the system is hardcoded for USDC. To provide more flexibility for creators and users, the platform should support a selection of popular SPL tokens for pricing and payment.
+
+## Instructions
+1. **Update Database Schema:**
+ * The `agent_skill_prices` table already has a `currency_mint` column, which is great. Ensure your database queries and API responses handle this correctly.
+
+2. **Modify Creator UI for Pricing:**
+ * In the "Skill Monetization" section of `agent-edit.html`, change the currency selector from a static element to a dropdown menu.
+ * Populate this dropdown with a list of supported currencies (e.g., "USDC", "SOL", "BONK"). This list can be hardcoded for now.
+ * When a creator selects a currency, store the corresponding mint address along with the price.
+
+3. **Update Frontend Purchase Logic:**
+ * In `src/marketplace.js`, when constructing the purchase transaction, the mint address should not be hardcoded. It should be read from the `skillPrice.currency_mint` property.
+ * The UI in the purchase modal should also dynamically display the correct currency symbol and amount.
+ * **Special Handling for SOL:** Since SOL is the native token, payments in SOL are not standard SPL token transfers. The easiest way to handle this is to use Wrapped SOL (WSOL). The user's wallet will need to wrap SOL into WSOL before transferring. The `@solana/spl-token` library provides functions for this, and it can be done in the same transaction as the transfer.
+
+## Code Example (Frontend - `spl-token-transfer.js` logic update)
+
+```javascript
+// Inside the purchase confirmation logic
+import { NATIVE_MINT } from '@solana/spl-token'; // The mint address for WSOL
+
+// ...
+const currencyMint = new PublicKey(priceInfo.currency_mint);
+
+const transaction = new Transaction();
+let userTokenAccount = await getAssociatedTokenAddress(currencyMint, userPublicKey);
+
+// Special handling if the currency is SOL (i.e., WSOL)
+if (currencyMint.equals(NATIVE_MINT)) {
+ const userWsolAccountInfo = await connection.getAccountInfo(userTokenAccount);
+
+ // If the user doesn't have a WSOL account, or not enough WSOL,
+ // we need to create one and/or wrap some SOL.
+ if (!userWsolAccountInfo || userWsolAccountInfo.data.length === 0) {
+ // Add instruction to create the associated token account for WSOL
+ }
+
+ // You might need to check the user's SOL balance and add an instruction
+ // to wrap the required amount of SOL into WSOL.
+ // This involves transferring SOL to the WSOL account and calling a sync instruction.
+}
+
+// The transfer instruction remains the same, but now works with any currency mint
+transaction.add(
+ createTransferInstruction(
+ userTokenAccount,
+ creatorTokenAccount,
+ userPublicKey,
+ priceInfo.amount
+ )
+);
+
+// ... send and confirm transaction
+```
+*Note: Handling Wrapped SOL adds significant complexity. You need to manage account creation and wrapping SOL within the same transaction, which requires careful balance management and instruction ordering.*
diff --git a/docs/monetization-prompts/17-affiliate-program.md b/docs/monetization-prompts/17-affiliate-program.md
new file mode 100644
index 000000000..01f52a1db
--- /dev/null
+++ b/docs/monetization-prompts/17-affiliate-program.md
@@ -0,0 +1,77 @@
+# Prompt 17: Affiliate and Referral Program
+
+**Status:** - [ ] Not Started
+
+## Objective
+Design and implement an affiliate program where users can earn a commission for referring new customers who purchase skills.
+
+## Explanation
+A referral program can be a powerful growth engine. By rewarding users for promoting agents and skills, you can incentivize word-of-mouth marketing and expand the platform's reach.
+
+## Instructions
+1. **Database Schema Changes:**
+ * Create a `referrals` table to track referral relationships.
+ * Columns: `id`, `referrer_user_id`, `referred_user_id`, `created_at`.
+ * Add a `referrer_user_id` column to the `user_agent_skills` table to link a purchase to a specific referral. This can be nullable.
+
+2. **Generate Unique Referral Links:**
+ * In the user's profile, provide a unique referral link (e.g., `three.ws/marketplace?ref=user_id`).
+ * When a new user signs up after visiting a referral link, store the referrer's ID in a cookie.
+ * When the new user signs up, read the cookie and create a record in the `referrals` table.
+
+3. **Attribute Purchases to Referrers:**
+ * When a user makes a purchase, the backend should check if they were referred.
+ * If so, populate the `referrer_user_id` in the `user_agent_skills` record.
+
+4. **Payout Logic for Referrers:**
+ * Modify the creator payout cron job (`/api/cron/process-payouts.js`) or smart contract.
+ * When processing a sale that has a referrer, the payment needs to be split three ways: creator, platform, and referrer.
+ * Define the commission rates (e.g., 5% for the referrer).
+
+5. **Referral Dashboard for Users:**
+ * Create a section in the user's dashboard to track their referrals.
+ * Display stats like number of sign-ups from their link, number of purchases made by their referrals, and total commission earned.
+
+## Code Example (Conceptual - Purchase Endpoint Modification)
+
+```javascript
+// In /api/marketplace/purchase-skill.js
+export default async function handler(req, res) {
+ const userId = req.user.id;
+ // ...
+
+ // Check for a referrer ID, which might be stored in the user's session
+ // or looked up from the 'referrals' table.
+ const referrerId = await db.findReferrerForUser(userId);
+
+ // ... (Transaction verification logic)
+
+ if (verificationSuccess) {
+ // Pass referrerId when recording the purchase
+ await db.recordSkillPurchase(userId, agentId, skillName, referrerId);
+ // ...
+ }
+}
+```
+
+## Code Example (Conceptual - Payout Logic Modification)
+
+```javascript
+// In the payout cron job
+for (const purchase of pendingPurchases) {
+ const creatorBase = purchase.amount * (1 - PLATFORM_FEE_PERCENT / 100);
+ let creatorShare = creatorBase;
+
+ if (purchase.referrer_id) {
+ const referrerCommission = purchase.amount * (REFERRAL_COMMISSION_PERCENT / 100);
+ creatorShare -= referrerCommission;
+
+ // Add to referrer's payout
+ const referrer = await db.getUser(purchase.referrer_id);
+ payouts[referrer.wallet_address] = (payouts[referrer.wallet_address] || 0) + referrerCommission;
+ }
+
+ // Add to creator's payout
+ payouts[purchase.creator_address] = (payouts[purchase.creator_address] || 0) + creatorShare;
+}
+```
diff --git a/docs/monetization-prompts/17-creator-payout-settings-ui.md b/docs/monetization-prompts/17-creator-payout-settings-ui.md
new file mode 100644
index 000000000..31e889f78
--- /dev/null
+++ b/docs/monetization-prompts/17-creator-payout-settings-ui.md
@@ -0,0 +1,77 @@
+# Prompt 17: Creator Payout Settings - UI
+
+## Objective
+Create a user interface in the user's settings or profile page for them to manage their payout wallet address.
+
+## Explanation
+To receive payments, creators need a secure and simple way to input and update their Solana wallet address. This UI should provide clear instructions and validation.
+
+## Instructions
+1. **Design the UI:**
+ * Choose a suitable location for this setting, such as a "Payouts" or "Monetization" tab in the user's main profile/settings page.
+ * Add a new section titled "Payout Wallet".
+ * Include an input field for the Solana wallet address.
+ * Add a "Save" button.
+ * Display the currently saved address (if any) and provide clear helper text, e.g., "This is the Solana wallet where you will receive payments for skill purchases."
+ * Add a warning about the importance of using the correct address.
+
+2. **Implement Frontend Logic:**
+ * When the page loads, fetch the user's current settings, including their `payout_wallet_address`, and populate the input field.
+ * When the user clicks "Save":
+ * Get the value from the input field.
+ * Perform client-side validation to check if it looks like a valid Solana address (e.g., check length and characters). A full validation on the backend is still required.
+ * Make a `PUT` request to the backend endpoint (`/api/users/payout-settings`) with the new address.
+ * Display a success or error message to the user based on the API response.
+
+## HTML Example (in a user settings page)
+
+```html
+<div class="settings-section">
+ <h3>Payout Wallet</h3>
+ <p class="helper-text">Enter the Solana wallet address where you want to receive payments.</p>
+
+ <div class="form-group">
+ <label for="payout-wallet">Solana Wallet Address</label>
+ <input type="text" id="payout-wallet" placeholder="Enter your Solana public key">
+ <small>Warning: Ensure this address is correct. Payments sent to a wrong address cannot be recovered.</small>
+ </div>
+
+ <button id="save-payout-btn">Save Wallet Address</button>
+ <div id="payout-status-message"></div>
+</div>
+```
+
+## JavaScript Example (on Save button click)
+
+```javascript
+document.getElementById('save-payout-btn').addEventListener('click', async () => {
+ const walletAddress = document.getElementById('payout-wallet').value;
+ const statusEl = document.getElementById('payout-status-message');
+
+ // Basic client-side check
+ if (walletAddress.length < 32 || walletAddress.length > 44) {
+ statusEl.textContent = 'Please enter a valid Solana address.';
+ statusEl.style.color = 'red';
+ return;
+ }
+
+ try {
+ const response = await fetch('/api/users/payout-settings', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ payout_wallet_address: walletAddress }),
+ });
+
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.message);
+ }
+
+ statusEl.textContent = 'Payout address updated successfully!';
+ statusEl.style.color = 'green';
+ } catch (error) {
+ statusEl.textContent = `Error: ${error.message}`;
+ statusEl.style.color = 'red';
+ }
+});
+```
diff --git a/docs/monetization-prompts/18-creator-dashboard-ui.md b/docs/monetization-prompts/18-creator-dashboard-ui.md
new file mode 100644
index 000000000..07fb69a15
--- /dev/null
+++ b/docs/monetization-prompts/18-creator-dashboard-ui.md
@@ -0,0 +1,93 @@
+# Prompt 18: Creator Dashboard - UI
+
+## Objective
+Build the frontend for the creator dashboard, visualizing the sales and earnings data provided by the backend APIs.
+
+## Explanation
+A visual dashboard is essential for creators to understand their performance at a glance. We will create a new page that consumes the creator dashboard APIs and presents the data using charts and tables.
+
+## Instructions
+1. **Create the Dashboard Page:**
+ * Create a new HTML file, e.g., `creator-dashboard.html`.
+ * Create a corresponding JavaScript file, e.g., `src/creator-dashboard.js`.
+
+2. **Fetch and Display Key Stats:**
+ * On page load, make a request to the `GET /api/creator/dashboard/stats` endpoint.
+ * Display the returned stats (total revenue, total sales) in prominent "stat cards" at the top of the page.
+ * Remember to format the revenue from the smallest unit to a human-readable number.
+
+3. **Display Sales History:**
+ * Make a request to the `GET /api/creator/dashboard/sales-history` endpoint.
+ * Render the returned list of sales in a table. The table should include columns like "Date", "Skill Name", "Agent", "Price", and "Earnings".
+
+4. **Add a Chart (Optional but recommended):**
+ * Include a charting library like Chart.js or D3.
+ * Make a request to an endpoint that provides time-series data (e.g., `GET /api/creator/dashboard/revenue-over-time`). You may need to create this endpoint.
+ * Render a line or bar chart showing daily or weekly earnings.
+
+## HTML Structure Example (`creator-dashboard.html`)
+
+```html
+<body>
+ <h1>Creator Dashboard</h1>
+
+ <div id="stats-grid">
+ <div class="stat-card">
+ <h4>Total Revenue</h4>
+ <p id="total-revenue-stat">$0.00</p>
+ </div>
+ <div class="stat-card">
+ <h4>Total Sales</h4>
+ <p id="total-sales-stat">0</p>
+ </div>
+ </div>
+
+ <div id="sales-chart-container">
+ <canvas id="sales-chart"></canvas>
+ </div>
+
+ <div id="sales-history-container">
+ <h3>Recent Sales</h3>
+ <table id="sales-history-table">
+ <thead>
+ <tr>
+ <th>Date</th>
+ <th>Skill</th>
+ <th>Earnings</th>
+ </tr>
+ </thead>
+ <tbody>
+ <!-- Rows will be injected by JavaScript -->
+ </tbody>
+ </table>
+ </div>
+</body>
+```
+
+## JavaScript Example (`src/creator-dashboard.js`)
+
+```javascript
+async function initDashboard() {
+ // Fetch and display stats
+ const statsRes = await fetch('/api/creator/dashboard/stats');
+ const stats = await statsRes.json();
+ document.getElementById('total-revenue-stat').textContent = `$${(stats.totalRevenue / 1e6).toFixed(2)}`;
+ document.getElementById('total-sales-stat').textContent = stats.totalSales;
+
+ // Fetch and render sales history table
+ const historyRes = await fetch('/api/creator/dashboard/sales-history');
+ const history = await historyRes.json();
+ const tableBody = document.querySelector('#sales-history-table tbody');
+ tableBody.innerHTML = history.sales.map(sale => `
+ <tr>
+ <td>${new Date(sale.date).toLocaleDateString()}</td>
+ <td>${escapeHtml(sale.skillName)}</td>
+ <td>$${(sale.earnings / 1e6).toFixed(2)}</td>
+ </tr>
+ `).join('');
+
+ // Logic to initialize chart would go here
+}
+
+initDashboard();
+```
diff --git a/docs/monetization-prompts/18-subscription-model.md b/docs/monetization-prompts/18-subscription-model.md
new file mode 100644
index 000000000..7aeec68d1
--- /dev/null
+++ b/docs/monetization-prompts/18-subscription-model.md
@@ -0,0 +1,56 @@
+# Prompt 18: Skill Subscription Model
+
+**Status:** - [ ] Not Started
+
+## Objective
+Implement a subscription model where users can pay a recurring fee for access to a set of skills from a creator, or all skills on the platform.
+
+## Explanation
+Subscriptions provide a predictable revenue stream for creators and the platform. This model can be attractive to power users who want access to a wide range of premium skills without making individual purchases. This could be implemented using a system like Solana Pay or by integrating with a dedicated NFT subscription service.
+
+## Instructions
+1. **Database Schema for Subscriptions:**
+ * Create a `subscriptions` table:
+ * Columns: `id`, `user_id`, `subscription_tier_id`, `start_date`, `end_date`, `status` (e.g., 'active', 'cancelled').
+ * Create a `subscription_tiers` table:
+ * Columns: `id`, `creator_id` (nullable, for creator-specific tiers), `name`, `price`, `currency_mint`, `duration_days`.
+
+2. **UI for Subscribing:**
+ * Create a new "Subscriptions" page.
+ * Display available subscription tiers (e.g., "Pro Tier - All Skills", "Creator X's All-Access Pass").
+ * Add a "Subscribe" button for each tier.
+
+3. **Handle Recurring Payments:**
+ * This is the most complex part. On-chain recurring payments on Solana are not as straightforward as with traditional payment systems.
+ * **Option 1: Solana Pay.** Integrate with Solana Pay to allow users to approve recurring transactions. This still requires user action for each payment period.
+ * **Option 2: Subscription-as-an-NFT.** A user mints an NFT that represents their subscription. The NFT has an expiration date. The dApp checks for a valid (non-expired) subscription NFT in the user's wallet. The user has to manually "renew" by purchasing a new subscription NFT.
+ * **Option 3: Off-chain with Credit Card.** For a hybrid model, use a service like Stripe for recurring billing and then have the backend airdrop a subscription NFT to the user.
+
+4. **Update Skill Gating Logic:**
+ * Modify the skill gating logic from Prompt 14.
+ * Before denying access to a paid skill, the system must also check if the user has an active subscription that grants access to that skill.
+ * This check involves looking for a valid record in the `subscriptions` table or a valid subscription NFT in the user's wallet.
+
+## Code Example (Conceptual - Skill Gating Update)
+
+```javascript
+// In the backend skill execution endpoint
+// ... (after checking for a price)
+
+if (skillPrice) {
+ // Check for direct ownership first
+ const hasOwnership = await db.checkSkillOwnership(userId, agentId, skillName);
+
+ if (!hasOwnership) {
+ // If not owned directly, check for an active subscription
+ const hasActiveSub = await db.checkActiveSubscription(userId, agentId, skillName);
+
+ if (!hasActiveSub) {
+ return res.status(403).json({ error: 'Subscription or purchase required.' });
+ }
+ }
+}
+
+// Proceed with execution
+// ...
+```
diff --git a/docs/monetization-prompts/19-skill-gating-logic.md b/docs/monetization-prompts/19-skill-gating-logic.md
new file mode 100644
index 000000000..21235ebd4
--- /dev/null
+++ b/docs/monetization-prompts/19-skill-gating-logic.md
@@ -0,0 +1,58 @@
+# Prompt 19: Skill Usage Gating
+
+## Objective
+Implement the core logic that prevents users from using a paid skill unless they have successfully purchased it.
+
+## Explanation
+This is where monetization becomes functional. So far, we can sell skills, but there's nothing stopping a user from trying to use them anyway. This "gating" logic must be enforced on the backend to be secure.
+
+## Instructions
+1. **Locate the Skill Execution Logic:**
+ * Find the part of your backend code that is responsible for executing an agent's skill. This might be in a chat API, a general agent interaction endpoint, or a dedicated skill execution endpoint.
+
+2. **Add a Pre-Execution Check:**
+ * Before the skill's code is run, insert a new checking mechanism.
+ * This check needs to know which user is making the request, which agent is being used, and which skill is being invoked.
+
+3. **Perform Ownership Verification:**
+ * Inside the check, first determine if the skill in question is a paid skill. Query the `agent_skill_prices` table for the agent and skill name.
+ * If the skill is **not** in the prices table, it's free. Allow execution to proceed.
+ * If the skill **is** in the prices table, it's a paid skill. You must now query the `unlocked_skills` table.
+ * Check if a row exists in `unlocked_skills` for the current `user_id`, `agent_id`, and `skill_name`.
+ * **If a row exists**, the user owns the skill. Allow execution to proceed.
+ * **If no row exists**, the user does not own the skill. Block the execution and return an error message to the user, e.g., `402 Payment Required`, with a message like "You must purchase this skill to use it."
+
+## Code Example (Backend Skill Execution Endpoint)
+
+```javascript
+// Example of an endpoint that runs a skill
+export default async function handler(req, res) {
+ // Assume auth middleware has run and req.user is available
+ const { agentId, skillName, skillInputs } = req.body;
+ const userId = req.user.id;
+
+ // --- NEW GATING LOGIC ---
+ // 1. Check if the skill is priced
+ const price = await db.getSkillPrice(agentId, skillName);
+
+ if (price) {
+ // It's a paid skill, so check for ownership
+ const isOwned = await db.checkSkillOwnership(userId, agentId, skillName);
+ if (!isOwned) {
+ return res.status(402).json({
+ message: `This is a paid skill. Please purchase it from the marketplace to use it.`
+ });
+ }
+ }
+ // --- END OF GATING LOGIC ---
+
+ // If the logic reaches here, the user is allowed to proceed.
+ // Original skill execution logic follows:
+ try {
+ const result = await executeSkill(agentId, skillName, skillInputs);
+ res.status(200).json({ result });
+ } catch (error) {
+ res.status(500).json({ message: "Skill execution failed." });
+ }
+}
+```
diff --git a/docs/monetization-prompts/20-batch-skill-purchase.md b/docs/monetization-prompts/20-batch-skill-purchase.md
new file mode 100644
index 000000000..d86855ebf
--- /dev/null
+++ b/docs/monetization-prompts/20-batch-skill-purchase.md
@@ -0,0 +1,44 @@
+# Prompt 20: Batch Skill Purchase (Shopping Cart)
+
+## Objective
+Allow users to add multiple skills to a "cart" and purchase them all in a single transaction.
+
+## Explanation
+Purchasing skills one by one can be tedious and costly in terms of transaction fees. A shopping cart feature improves the user experience by allowing a single, consolidated purchase for multiple items.
+
+## Instructions
+1. **Frontend: Cart UI:**
+ * Instead of a "Purchase" button, have an "Add to Cart" button.
+ * Add a cart icon to the site header that shows the number of items.
+ * Clicking the icon opens a cart modal/sidebar, listing the selected skills and the total price.
+ * The cart should have a "Checkout" button.
+
+2. **Frontend: Cart State Management:**
+ * Use `localStorage` or a simple in-memory object to manage the cart's state (the list of skills to be purchased).
+ * When "Add to Cart" is clicked, add the skill's details (`agentId`, `skillName`) to the cart.
+ * When "Checkout" is clicked, pass the list of items in the cart to the backend.
+
+3. **Backend: Update "Create Transaction" Endpoint:**
+ * Modify `POST /api/transactions/create-skill-purchase` to accept an **array** of skills instead of a single skill.
+ * The endpoint will now loop through the array of skills.
+ * For each skill, it calculates the payment due to the respective creator.
+ * It will add a separate `SPL Token Transfer` instruction **for each skill** to the transaction. If a user buys 3 skills from 3 different creators, the transaction will contain 3 transfers (plus 3 platform fee transfers).
+ * The backend returns a single transaction that bundles all these transfers.
+
+4. **Backend: Update "Verify Transaction" Endpoint:**
+ * The verification logic must also be updated to handle multiple items.
+ * It will receive an array of skills that were supposed to be in the transaction.
+ * It must parse the transaction from the blockchain and verify that **all** the expected transfers (to creators and platform) are present and correct.
+ * If verification is successful, it should add a row to the `unlocked_skills` table for **each** purchased skill. This should be done in a database transaction.
+
+## API Request Body Example (for Create Transaction)
+
+```json
+{
+ "buyerPublicKey": "USER_WALLET_ADDRESS",
+ "items": [
+ { "agentId": 123, "skillName": "AdvancedAnalysis" },
+ { "agentId": 456, "skillName": "ImageGeneration" }
+ ]
+}
+```
diff --git a/docs/monetization-prompts/21-skill-subscription-model-backend.md b/docs/monetization-prompts/21-skill-subscription-model-backend.md
new file mode 100644
index 000000000..f591bfe40
--- /dev/null
+++ b/docs/monetization-prompts/21-skill-subscription-model-backend.md
@@ -0,0 +1,64 @@
+# Prompt 21: Skill Subscription Model - Backend
+
+## Objective
+Implement the backend infrastructure for a subscription model, where users pay a recurring fee for access to all of an agent's paid skills.
+
+## Explanation
+Subscriptions provide predictable revenue for creators and value for active users. This is a significant feature requiring new database tables and logic for managing subscription status and recurring payments. We'll focus on the backend setup first. For payments, we could use a service like Helio to manage recurring Solana payments.
+
+## Instructions
+1. **Database Schema Changes:**
+ * Create a new table: `agent_subscriptions`.
+ * Columns: `id`, `user_id`, `agent_id`, `status` (e.g., 'active', 'cancelled', 'past_due'), `expires_at` (Timestamp), `payment_provider_subscription_id` (String).
+ * Add a new table `agent_subscription_plans`: `id`, `agent_id`, `amount`, `currency_mint`, `interval` (e.g., 'month', 'year').
+
+2. **API for Subscription Plans:**
+ * Create CRUD APIs for creators to manage their subscription plans (`/api/agents/:id/subscription-plans`). A creator might offer monthly and yearly tiers.
+
+3. **API for Creating a Subscription:**
+ * Create an endpoint `POST /api/subscriptions/create`.
+ * This endpoint would interact with a recurring payment provider (e.g., Helio). It would create a payment link or subscription plan with the provider and return it to the frontend.
+
+4. **Webhook for Payment Events:**
+ * Create a webhook endpoint `POST /api/webhooks/payments`.
+ * The payment provider will call this webhook to notify your app of events like `subscription.created`, `subscription.payment_succeeded`, `subscription.payment_failed`.
+ * When a `payment_succeeded` event is received, you should:
+ * Find the corresponding subscription in your `agent_subscriptions` table.
+ * Update its `status` to 'active'.
+ * Set the `expires_at` to the end of the new billing period (e.g., now + 30 days).
+
+5. **Update Skill Gating Logic:**
+ * Modify the skill gating logic from Prompt 19.
+ * Before checking for individual skill ownership in `unlocked_skills`, it should first check for an active subscription.
+ * Query the `agent_subscriptions` table for the `user_id` and `agent_id`. If an active subscription exists (`status` = 'active' and `expires_at` > now), allow skill execution.
+
+## Webhook Logic Example
+
+```javascript
+// POST /api/webhooks/payments
+export default async function handler(req, res) {
+ // 1. Verify the webhook signature to ensure it's from the payment provider
+ if (!isSignatureValid(req)) {
+ return res.status(403).send('Invalid signature');
+ }
+
+ const event = req.body;
+
+ // 2. Handle the event
+ switch (event.type) {
+ case 'subscription.payment_succeeded':
+ const subId = event.data.subscription_id;
+ const newExpiry = new Date(event.data.new_expiry_timestamp);
+
+ // Find subscription in DB by payment_provider_subscription_id
+ await db.updateSubscriptionStatus(subId, 'active', newExpiry);
+ break;
+ case 'subscription.payment_failed':
+ // ... handle failed payments, maybe set status to 'past_due'
+ break;
+ }
+
+ // 3. Acknowledge receipt
+ res.status(200).send('Acknowledged');
+}
+```
diff --git a/docs/monetization-prompts/22-skill-subscription-model-frontend.md b/docs/monetization-prompts/22-skill-subscription-model-frontend.md
new file mode 100644
index 000000000..78e41fb4a
--- /dev/null
+++ b/docs/monetization-prompts/22-skill-subscription-model-frontend.md
@@ -0,0 +1,57 @@
+# Prompt 22: Skill Subscription Model - Frontend
+
+## Objective
+Create the user interface for users to discover, purchase, and manage subscriptions to agents.
+
+## Explanation
+Following the backend setup, the frontend needs to present subscription options to users on the agent detail page and provide a way for them to manage their active subscriptions.
+
+## Instructions
+1. **Display Subscription Plans on Agent Page:**
+ * On the agent detail page (`marketplace.html`), add a new section for subscriptions.
+ * Fetch the agent's available subscription plans from the API (`GET /api/agents/:id/subscription-plans`).
+ * Display the plans with their price and billing interval (e.g., "$10 / month").
+ * Add a "Subscribe" button for each plan.
+
+2. **Subscription Purchase Flow:**
+ * When a user clicks "Subscribe", make a request to the backend `POST /api/subscriptions/create` endpoint.
+ * The backend will respond with a URL to the payment provider's checkout page (e.g., a Helio payment link).
+ * Redirect the user to this URL to complete the payment and set up the recurring transaction.
+ * The payment provider will handle the redirect back to your site.
+
+3. **UI State for Subscribed Users:**
+ * When viewing an agent to whom the user is subscribed, the UI should reflect this.
+ * Instead of "Subscribe", show "You are Subscribed".
+ * All paid skills for that agent should automatically appear as "Unlocked". The skill gating logic on the backend will already handle access.
+
+4. **Subscription Management Page:**
+ * Create a new "My Subscriptions" page for logged-in users.
+ * This page will list all their active subscriptions.
+ * For each subscription, it should show the agent, the price, and the next renewal date.
+ * Include a "Manage" or "Cancel" button. This would typically link to the customer portal provided by the payment service (like Helio or Stripe) where users can manage their payment methods and cancellations.
+
+## JavaScript Example (Subscribe Button Click)
+
+```javascript
+// On agent detail page, for a "Subscribe" button
+subscribeButton.addEventListener('click', async () => {
+ try {
+ const response = await fetch('/api/subscriptions/create', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ planId: selectedPlan.id })
+ });
+
+ if (!response.ok) throw new Error('Could not create subscription.');
+
+ const { checkoutUrl } = await response.json();
+
+ // Redirect user to the payment page
+ window.location.href = checkoutUrl;
+
+ } catch (error) {
+ console.error('Subscription failed:', error);
+ alert('Failed to initiate subscription.');
+ }
+});
+```
diff --git a/docs/monetization-prompts/23-email-receipts.md b/docs/monetization-prompts/23-email-receipts.md
new file mode 100644
index 000000000..00d99ba42
--- /dev/null
+++ b/docs/monetization-prompts/23-email-receipts.md
@@ -0,0 +1,66 @@
+# Prompt 23: Email Receipts and Notifications
+
+## Objective
+Integrate an email service to send users receipts for their purchases and notifications for subscription events.
+
+## Explanation
+Professional platforms communicate with users via email for important events. Sending a receipt after a purchase confirms the transaction and provides a record for the user. Email notifications are also crucial for managing subscriptions.
+
+## Instructions
+1. **Choose and Integrate an Email Service Provider:**
+ * Sign up for a transactional email service like SendGrid, Postmark, or Resend.
+ * Obtain an API key and configure it securely on your backend (using environment variables).
+ * Install the provider's SDK in your backend service.
+
+2. **Send One-Time Purchase Receipts:**
+ * In your backend's transaction verification endpoint (`/api/skills/purchase/verify`), after successfully recording the skill ownership:
+ * Call a new function, e.g., `sendPurchaseReceiptEmail`.
+ * This function should use the email service's SDK to send an email to the user.
+ * The email should be based on a template and include details like the user's name, skill name, agent name, price paid, and transaction signature.
+
+3. **Send Subscription-Related Emails:**
+ * In your payments webhook (`/api/webhooks/payments`), trigger emails for key events:
+ * **`subscription.created`**: Send a "Welcome" email confirming the subscription start.
+ * **`subscription.payment_succeeded`**: Send a monthly/yearly receipt for the renewal payment.
+ * **`subscription.payment_failed`**: Send a notification that the payment failed and they need to update their payment information.
+ * **Upcoming Renewal Reminder**: Set up a scheduled job (e.g., a cron job) that runs daily to find subscriptions expiring in a few days and send a reminder email.
+
+## Code Example (Sending a receipt with Resend)
+
+```javascript
+// utils/email.js
+import { Resend } from 'resend';
+
+const resend = new Resend(process.env.RESEND_API_KEY);
+
+export async function sendPurchaseReceiptEmail(user, purchaseDetails) {
+ try {
+ await resend.emails.send({
+ from: 'Your App <[email protected]>',
+ to: user.email,
+ subject: 'Your Skill Purchase Receipt',
+ html: `
+ <h1>Receipt</h1>
+ <p>Hi ${user.name},</p>
+ <p>Thank you for purchasing the skill: <strong>${purchaseDetails.skillName}</strong>.</p>
+ <p>Price: ${purchaseDetails.price} USDC</p>
+ <p>Transaction: ${purchaseDetails.signature}</p>
+ `,
+ });
+ } catch (error) {
+ console.error('Failed to send email:', error);
+ }
+}
+
+
+// In the /api/skills/purchase/verify endpoint after success
+import { sendPurchaseReceiptEmail } from 'utils/email';
+
+// ...
+if (isVerified) {
+ await recordSkillOwnership(...);
+ await sendPurchaseReceiptEmail(req.user, { ... }); // Fire-and-forget
+ res.status(200).json({ message: "Verification successful." });
+}
+// ...
+```
diff --git a/docs/monetization-prompts/24-admin-monetization-dashboard.md b/docs/monetization-prompts/24-admin-monetization-dashboard.md
new file mode 100644
index 000000000..f5c0d3cb1
--- /dev/null
+++ b/docs/monetization-prompts/24-admin-monetization-dashboard.md
@@ -0,0 +1,62 @@
+# Prompt 24: Admin Monetization Dashboard
+
+## Objective
+Create a secure, internal dashboard for platform administrators to monitor the health and performance of the entire marketplace economy.
+
+## Explanation
+While creators have their own dashboards, platform admins need a high-level view to understand overall trends, spot potential issues, and manage the ecosystem. This is an internal tool, not for public users.
+
+## Instructions
+1. **Create a Secure Admin Area:**
+ * Build a new section of the application that is only accessible to users with an 'admin' role. This requires role-based access control (RBAC) in your user authentication system.
+
+2. **Backend API for Admin Stats:**
+ * Create a new set of protected API endpoints, e.g., under `/api/admin/stats/`.
+ * These endpoints will perform platform-wide aggregations.
+ * **Key metrics to expose:**
+ * **Gross Transaction Volume (GTV):** Total value of all transactions processed.
+ * **Platform Revenue:** Total fees collected by the platform.
+ * **Top Earning Creators:** A list of creators ranked by their total earnings.
+ * **Top Selling Skills/Agents:** A list of the most purchased skills and agents.
+ * **New Subscriptions/Cancellations:** A time-series chart showing subscription growth.
+
+3. **Frontend UI for Admin Dashboard:**
+ * Create a new UI for the admin area.
+ * Use data visualization components (charts, tables, stat cards) to present the data fetched from the admin APIs.
+ * The UI should allow filtering by date ranges to analyze performance over time.
+
+4. **Add Management Tools (Advanced):**
+ * Beyond just viewing data, an admin dashboard can include tools for:
+ * **Refunding a purchase:** A button to trigger a refund process (this is complex and involves on-chain transactions and database updates).
+ * **Disabling a skill from sale:** A toggle to remove a problematic skill from the marketplace.
+ * **Managing user roles.**
+
+## Admin API Response Example (`/api/admin/stats/overview`)
+
+```json
+{
+ "dateRange": {
+ "start": "2026-01-01T00:00:00.000Z",
+ "end": "2026-05-04T23:59:59.999Z"
+ },
+ "grossTransactionVolume": 12500000000,
+ "platformRevenue": 625000000,
+ "activeSubscriptions": 1240,
+ "newUsers": 5300
+}
+```
+
+## Database Query Example (PostgreSQL for GTV)
+
+```sql
+-- Calculates Gross Transaction Volume and Platform Revenue between two dates
+SELECT
+ SUM(prices.amount) AS gross_transaction_volume,
+ SUM(prices.amount * 0.05) AS platform_revenue -- Assuming 5% fee
+FROM
+ unlocked_skills AS unlocked
+JOIN
+ agent_skill_prices AS prices ON unlocked.agent_id = prices.agent_id AND unlocked.skill_name = prices.skill_name
+WHERE
+ unlocked.created_at BETWEEN $1 AND $2; -- $1 and $2 are date range parameters
+```
diff --git a/docs/monetization-prompts/25-user-experience-onboarding.md b/docs/monetization-prompts/25-user-experience-onboarding.md
new file mode 100644
index 000000000..46e5f0825
--- /dev/null
+++ b/docs/monetization-prompts/25-user-experience-onboarding.md
@@ -0,0 +1,59 @@
+# Prompt 25: User Experience & Onboarding
+
+## Objective
+Refine the overall user experience for the monetization features and create clear onboarding materials for creators.
+
+## Explanation
+A powerful system is only effective if people understand how to use it. This final step focuses on documentation, in-app guidance, and polishing the user interface to make the monetization features intuitive for both buyers and sellers.
+
+## Instructions
+1. **Create a Creator Onboarding Guide:**
+ * Write a clear, concise guide in your `docs` folder that explains how a creator can start monetizing their skills.
+ * **Topics to cover:**
+ * How to set up their payout wallet.
+ * How to set prices for their skills.
+ * How subscriptions work.
+ * An explanation of the platform fee.
+ * A link to their creator dashboard and an explanation of the metrics.
+
+2. **Add In-App Guidance (Tooltips & Helpers):**
+ * Go through the creator-facing UIs (payout settings, skill pricing) and add tooltips or helper text to explain complex concepts.
+ * For example, next to the payout wallet input, add a tooltip explaining what a Solana wallet is and where to get one.
+ * On the skill pricing page, explain the units (e.g., "Enter price in USDC").
+
+3. **Refine the Buyer Experience:**
+ * Review the entire purchase flow from the buyer's perspective. Is it clear and smooth?
+ * Ensure error messages are helpful. Instead of a generic "Transaction Failed", provide more context if possible (e.g., "Transaction failed. You may not have enough USDC in your wallet.").
+ * Add a section to the user's profile where they can see a history of all the skills they've purchased.
+
+4. **Create a Marketing/Landing Page:**
+ * Design a section on your main landing page that advertises the new creator monetization features.
+ * Highlight the benefits for creators (earn revenue) and for users (access powerful new capabilities).
+ * This will help attract new creators to your platform.
+
+## Example: Onboarding Doc Snippet (`/docs/monetizing-your-agent.md`)
+
+```markdown
+---
+title: Monetizing Your Agent
+---
+
+## Introduction
+
+Welcome to the creator monetization program! This guide will walk you through setting up your account to sell your agent's skills on the marketplace.
+
+### Step 1: Set Up Your Payout Wallet
+
+Before you can earn, you need to tell us where to send your funds.
+
+1. Navigate to your **Settings > Payouts** page.
+2. You will need a Solana wallet. If you don't have one, we recommend Phantom or Solflare.
+3. Copy your public wallet address and paste it into the "Payout Wallet Address" field.
+4. Click "Save". All your earnings will now be sent to this address.
+
+**Important**: Double-check this address. Payments sent to an incorrect address are irreversible.
+
+### Step 2: Pricing Your Skills
+
+...
+```
diff --git a/docs/monetization/02-api-set-skill-price.md b/docs/monetization/02-api-set-skill-price.md
new file mode 100644
index 000000000..75dcc2f98
--- /dev/null
+++ b/docs/monetization/02-api-set-skill-price.md
@@ -0,0 +1,84 @@
+# Prompt 2: API for Creators to Set Skill Prices
+
+## Objective
+Create a secure API endpoint for agent creators to set, update, and remove prices for their skills.
+
+## Explanation
+To enable monetization, creators need a way to manage the prices of their skills. This endpoint will allow them to programmatically define which skills are paid and how much they cost. It must be secure, ensuring only the agent's owner can modify prices.
+
+## Instructions
+1. **Create API Route:**
+ * Set up a new route: `POST /api/agents/:id/skills/price`.
+ * This route should handle setting or updating the price for a single skill.
+
+2. **Authentication and Authorization:**
+ * Protect this endpoint. Ensure that a user is authenticated.
+ * Verify that the authenticated user is the owner of the agent specified by `:id`. If not, return a `403 Forbidden` error.
+
+3. **Request Body Validation:**
+ * The request body should be a JSON object with the following structure:
+ ```json
+ {
+ "skill_name": "your-skill-name",
+ "amount": 1000000,
+ "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
+ }
+ ```
+ * Validate the `skill_name`, `amount` (must be a non-negative integer), and `currency_mint`.
+
+4. **Database Interaction:**
+ * Implement logic to "upsert" this data into the `agent_skill_prices` table.
+ * If a price for that `agent_id` and `skill_name` already exists, update it.
+ * If it doesn't exist, insert a new row.
+ * If `amount` is `0` or `null`, you should delete the corresponding row from `agent_skill_prices` to make the skill free again.
+
+5. **Response:**
+ * On success, return a `200 OK` status with a confirmation message.
+ * On failure (validation, auth, etc.), return an appropriate error status and message.
+
+## Code Example (Backend - `api/agents/[id]/skills/price.js`)
+
+```javascript
+// Example using an Express-like framework
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ return res.status(405).json({ error: 'Method Not Allowed' });
+ }
+
+ const { id: agentId } = req.query;
+ const { skill_name, amount, currency_mint } = req.body;
+
+ // 1. Get authenticated user (e.g., from a session or token)
+ const user = await getAuthenticatedUser(req);
+ if (!user) {
+ return res.status(401).json({ error: 'Unauthorized' });
+ }
+
+ // 2. Verify ownership of the agent
+ const agent = await db.getAgentById(agentId);
+ if (!agent || agent.creator_id !== user.id) {
+ return res.status(403).json({ error: 'Forbidden' });
+ }
+
+ // 3. Validate input
+ if (!skill_name || !currency_mint || amount == null || amount < 0) {
+ return res.status(400).json({ error: 'Invalid input' });
+ }
+
+ try {
+ // 4. Upsert or delete price in the database
+ if (amount > 0) {
+ await db.upsertSkillPrice({ agent_id: agentId, skill_name, amount, currency_mint });
+ } else {
+ await db.deleteSkillPrice({ agent_id: agentId, skill_name });
+ }
+
+ // 5. Return success
+ res.status(200).json({ message: 'Skill price updated successfully.' });
+ } catch (error) {
+ console.error('Error updating skill price:', error);
+ res.status(500).json({ error: 'Internal Server Error' });
+ }
+}
+```
diff --git a/docs/monetization/02-purchase-skill-button.md b/docs/monetization/02-purchase-skill-button.md
new file mode 100644
index 000000000..3c8d11f88
--- /dev/null
+++ b/docs/monetization/02-purchase-skill-button.md
@@ -0,0 +1,78 @@
+# Prompt 2: "Purchase Skill" Button
+
+## Objective
+Add a "Purchase" button to the agent detail page for skills that have a price. This button should be the primary call-to-action for monetizing skills.
+
+## Explanation
+Building on the previous prompt where we displayed the skill price, we now need to add an interactive element for users to initiate a purchase. The button should appear next to paid skills and should be disabled or hidden for skills the user already owns (though ownership functionality will be built in a later step).
+
+## Instructions
+1. **Update the Frontend UI (`src/marketplace.js`):**
+ * In the `renderDetail` function, where you iterate over skills, add a conditional button.
+ * If a skill has a price (`skillPrices[name]`), render a `<button>` element.
+ * For now, we will not implement the click handler, but we should add placeholder classes and data attributes that we'll use later to wire up the payment flow.
+ * Give the button a class like `purchase-skill-btn`.
+ * Store the skill's name in a data attribute, e.g., `data-skill-name="${name}"`.
+
+2. **Style the Button (`marketplace.css`):**
+ * Add styling for the `purchase-skill-btn` to make it stand out.
+ * It should be visually appealing and clearly indicate that it's a purchase action. Use an accent color and consider adding an icon (e.g., a shopping cart or a lock icon).
+
+## Code Example (Frontend - `src/marketplace.js`)
+
+```javascript
+// Inside renderDetail function, modifying the skills mapping
+
+const skillPrices = a.skill_prices || {};
+$('d-skills').innerHTML = skillsArr.length
+ ? skillsArr.map((s) => {
+ const name = typeof s === 'string' ? s : (s.name || '');
+ const price = skillPrices[name];
+
+ let actionHtml = '';
+ if (price) {
+ const priceInUsdc = (price.amount / 1e6).toFixed(2);
+ const priceBadge = `<span class="price-badge price-paid">${priceInUsdc} USDC</span>`;
+ // For now, isOwned is a placeholder. We will implement this logic later.
+ const isOwned = false;
+ if (isOwned) {
+ actionHtml = '<span class="skill-owned">✓ Owned</span>';
+ } else {
+ actionHtml = `<button class="purchase-skill-btn" data-skill-name="${escapeHtml(name)}">Purchase</button>`;
+ }
+ return `<span class="skill-entry">${escapeHtml(name)}${priceBadge}${actionHtml}</span>`;
+ } else {
+ const freeBadge = `<span class="price-badge price-free">Free</span>`;
+ return `<span class="skill-entry">${escapeHtml(name)}${freeBadge}</span>`;
+ }
+ }).join(' ')
+ : '<div>This Agent has no skills defined.</div>';
+```
+
+## CSS Example (`marketplace.css`)
+
+```css
+.purchase-skill-btn {
+ margin-left: 8px;
+ padding: 4px 10px;
+ font-size: 11px;
+ font-weight: 600;
+ border-radius: 5px;
+ background-color: var(--accent);
+ color: #fff;
+ border: 1px solid var(--accent);
+ cursor: pointer;
+ transition: background-color 0.2s;
+}
+
+.purchase-skill-btn:hover {
+ filter: brightness(1.1);
+}
+
+.skill-owned {
+ margin-left: 8px;
+ font-size: 11px;
+ color: #a7f3d0;
+ font-weight: 600;
+}
+```
diff --git a/docs/monetization/02-user-wallet-connection.md b/docs/monetization/02-user-wallet-connection.md
new file mode 100644
index 000000000..d3ac8c27a
--- /dev/null
+++ b/docs/monetization/02-user-wallet-connection.md
@@ -0,0 +1,108 @@
+# Prompt 2: User Wallet Connection
+
+## Objective
+Integrate a "Connect Wallet" feature into the marketplace header, allowing users to connect their Solana wallets to the application. This is a foundational step for enabling on-chain interactions like purchasing skills.
+
+## Explanation
+To allow users to purchase premium skills, they first need a way to connect their cryptocurrency wallet. We will use a vanilla JavaScript implementation compatible with the Solana wallet-adapter standards to present a "Connect Wallet" button. This will handle the core logic of connecting to browser-based wallets like Phantom.
+
+## Instructions
+1. **Add a Wallet Library:**
+ * We will use a CDN version of a suitable library to simplify dependencies. Add this to `marketplace.html` in the `<head>` section:
+ ```html
+ <script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>
+ ```
+
+2. **Update the Marketplace Header:**
+ * In `marketplace.html`, add a "Connect Wallet" button to the header section. We will give it a unique ID to attach our script to it.
+ * `<button id="connectWalletBtn" class="connect-wallet-btn">Connect Wallet</button>`
+
+3. **Implement Wallet Connection Logic:**
+ * Create a new file `public/wallet-connector.js` to encapsulate the wallet connection logic.
+ * This script will check for the presence of a Solana wallet in the browser (like Phantom), handle the connection request, and update the UI to reflect the connection status.
+
+## Code Example (`public/wallet-connector.js`)
+
+```javascript
+document.addEventListener('DOMContentLoaded', () => {
+ const connectWalletBtn = document.getElementById('connectWalletBtn');
+ let walletPublicKey = null;
+
+ const getProvider = () => {
+ if ('phantom' in window) {
+ const provider = window.phantom?.solana;
+ if (provider?.isPhantom) {
+ return provider;
+ }
+ }
+ // Add other wallet providers here if needed
+ return null;
+ };
+
+ const updateUI = () => {
+ if (walletPublicKey) {
+ const key = walletPublicKey.toBase58();
+ connectWalletBtn.textContent = `Connected: ${key.slice(0, 4)}...${key.slice(-4)}`;
+ connectWalletBtn.disabled = true;
+ } else {
+ connectWalletBtn.textContent = 'Connect Wallet';
+ connectWalletBtn.disabled = false;
+ }
+ };
+
+ connectWalletBtn.addEventListener('click', async () => {
+ const provider = getProvider();
+ if (provider) {
+ try {
+ const resp = await provider.connect();
+ walletPublicKey = resp.publicKey;
+ updateUI();
+
+ provider.on('disconnect', () => {
+ walletPublicKey = null;
+ updateUI();
+ });
+ } catch (err) {
+ console.error('Failed to connect to wallet', err);
+ alert('Could not connect to wallet. Please try again.');
+ }
+ } else {
+ alert('Solana wallet not found! Please install Phantom Wallet.');
+ window.open('https://phantom.app/', '_blank');
+ }
+ });
+
+ // Check for eager connection
+ const provider = getProvider();
+ if (provider && provider.isConnected) {
+ // Will be null if not connected
+ walletPublicKey = provider.publicKey;
+ updateUI();
+ }
+});
+```
+
+## CSS Example (`/public/marketplace.css`)
+
+```css
+.connect-wallet-btn {
+ background-color: var(--accent, #6a5cff);
+ color: white;
+ border: none;
+ padding: 8px 16px;
+ border-radius: 6px;
+ cursor: pointer;
+ font-weight: 600;
+ font-size: 13px;
+ transition: filter 0.15s ease;
+}
+
+.connect-wallet-btn:hover {
+ filter: brightness(1.1);
+}
+
+.connect-wallet-btn:disabled {
+ background-color: #3a3a4a;
+ cursor: not-allowed;
+}
+```
diff --git a/docs/monetization/03-skill-purchase-flow-ui.md b/docs/monetization/03-skill-purchase-flow-ui.md
new file mode 100644
index 000000000..db82ef516
--- /dev/null
+++ b/docs/monetization/03-skill-purchase-flow-ui.md
@@ -0,0 +1,117 @@
+# Prompt 3: Skill Purchase Flow UI
+
+## Objective
+Implement the UI flow for purchasing a skill. When a user clicks on a paid skill on the agent detail page, a confirmation modal should appear displaying the skill name, price, and a "Buy Now" button.
+
+## Explanation
+After connecting their wallet, the next step is for users to be able to initiate a purchase. This task focuses on creating the frontend modal that serves as the confirmation step before creating and sending the on-chain transaction. This modal prevents accidental purchases and provides a clear summary of the transaction to the user.
+
+## Instructions
+1. **Create the Purchase Modal HTML:**
+ * In `marketplace.html`, add the HTML structure for a modal dialog. It should be hidden by default.
+ * The modal should have placeholders for the skill name, price, and action buttons.
+
+2. **Add Event Listeners:**
+ * In `src/marketplace.js`, modify the `renderDetail` function. When rendering skills, attach a click event listener to the skill entries.
+ * If a clicked skill is paid, the event listener should populate the purchase modal with the skill's data (name, price) and make the modal visible.
+
+3. **Style the Modal:**
+ * In `/public/marketplace.css`, add CSS rules to style the modal, its backdrop, and content to match the site's aesthetic.
+
+## HTML Example (`marketplace.html`)
+
+```html
+<!-- Add this somewhere inside the <body> tag -->
+<div id="purchaseModal" class="modal-backdrop" style="display: none;">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h2>Confirm Purchase</h2>
+ <button id="closePurchaseModal" class="modal-close-btn">&times;</button>
+ </div>
+ <div class="modal-body">
+ <p>You are about to purchase the skill:</p>
+ <h3 id="modalSkillName"></h3>
+ <p>Price:</p>
+ <h3 id="modalSkillPrice"></h3>
+ </div>
+ <div class="modal-footer">
+ <button id="confirmPurchaseBtn" class="modal-action-btn">Buy Now</button>
+ </div>
+ </div>
+</div>
+```
+
+## JavaScript Logic (`src/marketplace.js`)
+
+```javascript
+// Inside renderDetail or a suitable scope
+const purchaseModal = document.getElementById('purchaseModal');
+const closePurchaseModalBtn = document.getElementById('closePurchaseModal');
+const confirmPurchaseBtn = document.getElementById('confirmPurchaseBtn');
+const modalSkillName = document.getElementById('modalSkillName');
+const modalSkillPrice = document.getElementById('modalSkillPrice');
+
+function openPurchaseModal(skillName, price) {
+ modalSkillName.textContent = skillName;
+ modalSkillPrice.textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;
+ purchaseModal.style.display = 'flex';
+ // Store data for the next step
+ confirmPurchaseBtn.dataset.skillName = skillName;
+}
+
+function closePurchaseModal() {
+ purchaseModal.style.display = 'none';
+}
+
+closePurchaseModalBtn.addEventListener('click', closePurchaseModal);
+window.addEventListener('click', (event) => {
+ if (event.target === purchaseModal) {
+ closePurchaseModal();
+ }
+});
+
+// In your skill rendering loop:
+const skillEl = document.createElement('span');
+skillEl.className = 'skill-entry';
+// ... set content ...
+if (price) {
+ skillEl.addEventListener('click', () => openPurchaseModal(name, price));
+}
+```
+
+## CSS Example (`/public/marketplace.css`)
+
+```css
+.modal-backdrop {
+ position: fixed;
+ inset: 0;
+ background-color: rgba(0, 0, 0, 0.7);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 1000;
+}
+.modal-content {
+ background: var(--panel, #14141c);
+ padding: 24px;
+ border-radius: 12px;
+ border: 1px solid var(--border, #1f1f29);
+ width: min(400px, 90vw);
+}
+.modal-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ border-bottom: 1px solid var(--border, #1f1f29);
+ padding-bottom: 12px;
+ margin-bottom: 12px;
+}
+.modal-header h2 { margin: 0; font-size: 18px; }
+.modal-close-btn { background: none; border: none; color: #eee; font-size: 24px; cursor: pointer; }
+.modal-footer { margin-top: 24px; text-align: right; }
+.modal-action-btn {
+ background-color: var(--accent, #6a5cff);
+ color: white;
+ /* ... other button styles */
+}
+```
diff --git a/docs/monetization/03-solana-pay-backend.md b/docs/monetization/03-solana-pay-backend.md
new file mode 100644
index 000000000..c5d2a9f35
--- /dev/null
+++ b/docs/monetization/03-solana-pay-backend.md
@@ -0,0 +1,110 @@
+# Prompt 3: Solana Pay Integration (Backend)
+
+## Objective
+Create a backend API endpoint that generates a Solana Pay transaction request when a user decides to purchase a skill.
+
+## Explanation
+To securely handle payments, we will use Solana Pay. This standard allows us to create a transaction on the backend and present it to the user's mobile wallet for approval. This prompt focuses on creating the API endpoint that prepares this transaction. The endpoint will receive a skill name, look up its price, and construct a transaction to transfer the correct amount of USDC from the buyer to the seller.
+
+## Instructions
+1. **Create a New API Endpoint:**
+ * In the `api/payments/` directory, create a new file named `prepare-skill-purchase.js`.
+ * This endpoint should handle `POST` requests and expect a `skillName` and `agentId` in the request body.
+
+2. **Implement the Endpoint Logic:**
+ * The endpoint needs to perform several actions:
+ * Authenticate the user to identify the buyer.
+ * From the `agentId`, look up the agent and its creator.
+ * From the creator's profile, retrieve their payout wallet address.
+ * From `skillName` and `agentId`, query the `agent_skill_prices` table to get the skill's price (amount and currency). For now, we'll assume USDC.
+ * Construct a Solana transaction using the `@solana/web3.js` library to transfer the specified amount of USDC from the buyer to the creator.
+ * Return the transaction details in the format required by the Solana Pay spec. This includes the transaction itself (serialized), a message, and a label.
+
+3. **Dependencies:**
+ * You will need to add `@solana/pay` and `@solana/spl-token` to your backend dependencies if they are not already present.
+
+## Code Example (Backend - `api/payments/prepare-skill-purchase.js`)
+
+```javascript
+// api/payments/prepare-skill-purchase.js
+import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
+import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';
+import { findCreatorPayoutWallet, findSkillPrice } from '../_lib/db'; // Placeholder for DB functions
+
+const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d');
+const PLATFORM_WALLET = new PublicKey('YourPlatformWalletAddressHere'); // Your platform's treasury wallet
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ return res.status(405).json({ error: 'Method Not Allowed' });
+ }
+
+ try {
+ // User must be authenticated (logic not shown)
+ const buyerPublicKey = new PublicKey(req.user.solana_wallet);
+
+ const { agentId, skillName } = req.body;
+ if (!agentId || !skillName) {
+ return res.status(400).json({ error: 'agentId and skillName are required' });
+ }
+
+ const priceInfo = await findSkillPrice(agentId, skillName);
+ if (!priceInfo) {
+ return res.status(404).json({ error: 'Skill or price not found' });
+ }
+
+ const creatorPayoutWallet = await findCreatorPayoutWallet(agentId);
+ if (!creatorPayoutWallet) {
+ return res.status(500).json({ error: 'Creator payout wallet not configured' });
+ }
+
+ const connection = new Connection(process.env.SOLANA_RPC_URL);
+ const { blockhash } = await connection.getLatestBlockhash();
+
+ const transaction = new Transaction({
+ recentBlockhash: blockhash,
+ feePayer: buyerPublicKey,
+ });
+
+ const buyerUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, buyerPublicKey);
+ const creatorUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, new PublicKey(creatorPayoutWallet));
+
+ // Assuming a 5% platform fee
+ const platformFee = Math.floor(priceInfo.amount * 0.05);
+ const creatorAmount = priceInfo.amount - platformFee;
+
+ // Transfer to creator
+ transaction.add(
+ createTransferInstruction(
+ buyerUsdcAddress,
+ creatorUsdcAddress,
+ buyerPublicKey,
+ creatorAmount
+ )
+ );
+
+ // Transfer to platform
+ const platformUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, PLATFORM_WALLET);
+ transaction.add(
+ createTransferInstruction(
+ buyerUsdcAddress,
+ platformUsdcAddress,
+ buyerPublicKey,
+ platformFee
+ )
+ );
+
+ const serializedTransaction = transaction.serialize({ requireAllSignatures: false });
+
+ res.status(200).json({
+ transaction: serializedTransaction.toString('base64'),
+ message: `Purchase skill "${skillName}" for ${(priceInfo.amount / 1e6).toFixed(2)} USDC`,
+ label: 'three.ws Agent Skill',
+ });
+
+ } catch (error) {
+ console.error('Error preparing skill purchase:', error);
+ res.status(500).json({ error: 'Internal Server Error' });
+ }
+}
+```
diff --git a/docs/monetization/03-ui-manage-skill-prices.md b/docs/monetization/03-ui-manage-skill-prices.md
new file mode 100644
index 000000000..3a6d3342e
--- /dev/null
+++ b/docs/monetization/03-ui-manage-skill-prices.md
@@ -0,0 +1,98 @@
+# Prompt 3: UI for Skill Price Management
+
+## Objective
+Create a user interface within the agent editing page that allows creators to easily set, update, and remove prices for their skills.
+
+## Explanation
+With the backend API in place, creators need a visual tool to manage their skill pricing. This UI will be added to the `agent-edit.html` page, providing an intuitive way to toggle a skill as "paid" and set its price without needing to interact with the API directly.
+
+## Instructions
+1. **Locate the Correct File:**
+ * Open `agent-edit.html`. This page contains the forms for editing an agent's properties.
+
+2. **Add a "Monetization" Section:**
+ * Find where skills or agent profile prompts are rendered. This is likely in the "Publish" tab (`id="panel-publish"`).
+ * Add a new section for skill pricing. You could list the agent's available skills (fetched from the agent's metadata) and provide pricing controls for each.
+
+3. **Implement UI Controls for Each Skill:**
+ * For each skill, display its name.
+ * Add a checkbox or toggle switch labeled "Paid Skill".
+ * When the "Paid Skill" toggle is enabled, show two input fields:
+ * An `input type="number"` for the `amount` (in a user-friendly unit like USDC, not lamports).
+ * A (potentially hidden or disabled) field for the `currency_mint`, which could default to USDC for now.
+ * When the toggle is disabled, hide the price inputs.
+
+4. **Handle Form Submission:**
+ * When the creator saves their changes on the `agent-edit` page, your JavaScript should gather the pricing data for each skill.
+ * For each skill that is marked as "paid", make a call to the `POST /api/agents/:id/skills/price` endpoint created in the previous prompt.
+ * Remember to convert the user-friendly amount (e.g., 1.5 USDC) back to the base unit (e.g., 1,500,000 lamports for a 6-decimal currency) before sending it to the API.
+ * If a skill is marked as free (or was paid and is now free), send a request with `amount: 0` to remove the price.
+
+## Code Example (Frontend - `agent-edit.html` script)
+
+```javascript
+// Inside the script tag of agent-edit.html
+
+// Assume 'agent.skills' is an array of skill names and 'currentPrices' is a map from the API
+function renderSkillPricingUI(skills, currentPrices) {
+ const container = document.getElementById('skill-pricing-container'); // You'll need to create this container
+ container.innerHTML = '<h3>Skill Pricing</h3>';
+
+ skills.forEach(skillName => {
+ const price = currentPrices[skillName];
+ const isPaid = !!price;
+ const amountInUSDC = isPaid ? (price.amount / 1e6).toFixed(2) : '1.00';
+
+ const skillRow = document.createElement('div');
+ skillRow.className = 'form-group skill-price-row';
+ skillRow.innerHTML = `
+ <label class="form-label">${escapeHtml(skillName)}</label>
+ <div class="skill-price-controls">
+ <input type="checkbox" class="paid-toggle" data-skill="${escapeHtml(skillName)}" ${isPaid ? 'checked' : ''}>
+ <span class="toggle-label">Paid</span>
+ <div class="price-inputs" style="${isPaid ? '' : 'display: none;'}">
+ <input type="number" class="price-amount" value="${amountInUSDC}" step="0.01" min="0">
+ <span>USDC</span>
+ </div>
+ </div>
+ `;
+ container.appendChild(skillRow);
+ });
+
+ // Add event listeners for toggles
+ container.querySelectorAll('.paid-toggle').forEach(toggle => {
+ toggle.addEventListener('change', (e) => {
+ const inputs = e.target.closest('.skill-price-controls').querySelector('.price-inputs');
+ inputs.style.display = e.target.checked ? 'flex' : 'none';
+ });
+ });
+}
+
+// On save, you would iterate through these controls:
+async function saveSkillPrices(agentId) {
+ const rows = document.querySelectorAll('.skill-price-row');
+ for (const row of rows) {
+ const toggle = row.querySelector('.paid-toggle');
+ const skillName = toggle.dataset.skill;
+ const amountInput = row.querySelector('.price-amount');
+
+ let amountInLamports = 0;
+ if (toggle.checked) {
+ const amountInUSDC = parseFloat(amountInput.value);
+ if (!isNaN(amountInUSDC) && amountInUSDC > 0) {
+ amountInLamports = Math.round(amountInUSDC * 1e6); // Convert to lamports
+ }
+ }
+
+ await fetch(`/api/agents/${agentId}/skills/price`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ skill_name: skillName,
+ amount: amountInLamports,
+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // Assuming USDC
+ })
+ });
+ }
+}
+```
diff --git a/docs/monetization/04-backend-price-validation.md b/docs/monetization/04-backend-price-validation.md
new file mode 100644
index 000000000..c0038f237
--- /dev/null
+++ b/docs/monetization/04-backend-price-validation.md
@@ -0,0 +1,74 @@
+# Prompt 4: Backend Price Validation Logic
+
+## Objective
+Implement robust server-side validation for skill prices to ensure data integrity and prevent invalid pricing information from being stored.
+
+## Explanation
+While the frontend can guide users, the backend must be the ultimate authority on data validity. This prompt focuses on strengthening the `POST /api/agents/:id/skills/price` endpoint by adding comprehensive validation logic for the incoming price data.
+
+## Instructions
+1. **Locate the API Endpoint:**
+ * Open the file for the `POST /api/agents/:id/skills/price` endpoint (e.g., `api/agents/[id]/skills/price.js`).
+
+2. **Enhance Validation Logic:**
+ * Before interacting with the database, ensure the request body contains all required fields (`skill_name`, `amount`, `currency_mint`).
+ * **Amount Validation:**
+ * Verify that `amount` is a non-negative integer. Floating-point numbers or negative values should be rejected with a `400 Bad Request` error.
+ * Consider setting a maximum allowed price to prevent abuse or user error (e.g., max 100,000,000,000 lamports or 100,000 USDC).
+ * **Currency Mint Validation:**
+ * Check if `currency_mint` is a valid Solana public key.
+ * For now, you might enforce that it must be the official USDC mint address on the target network (Mainnet or Devnet). Create a whitelist of accepted mints.
+ * **Skill Name Validation:**
+ * Verify that the `skill_name` provided in the request actually corresponds to a real skill defined in the agent's configuration. If not, reject the request.
+
+3. **Return Specific Error Messages:**
+ * Provide clear and specific error messages in the JSON response when validation fails. This helps the frontend display meaningful error feedback to the user.
+ * Example error responses:
+ * `{ "error": "Amount must be a non-negative integer." }`
+ * `{ "error": "Invalid currency mint address." }`
+ * `{ "error": "Skill 'invalid-skill' not found for this agent." }`
+
+## Code Example (Backend - API Endpoint)
+
+```javascript
+// Inside your /api/agents/:id/skills/price endpoint handler
+
+// Whitelist of accepted currency mints
+const ALLOWED_CURRENCIES = {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC Mainnet
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', // USDC Devnet
+};
+const MAX_PRICE_LAMPORTS = 100000 * 1e6; // Max 100,000 USDC
+
+// --- Inside the handler function, after auth ---
+
+const { skill_name, amount, currency_mint } = req.body;
+
+// 1. Basic field presence
+if (!skill_name || amount == null || !currency_mint) {
+ return res.status(400).json({ error: 'Missing required fields: skill_name, amount, currency_mint' });
+}
+
+// 2. Amount validation
+if (!Number.isInteger(amount) || amount < 0) {
+ return res.status(400).json({ error: 'Amount must be a non-negative integer.' });
+}
+if (amount > MAX_PRICE_LAMPORTS) {
+ return res.status(400).json({ error: `Price cannot exceed ${MAX_PRICE_LAMPORTS / 1e6} USDC.` });
+}
+
+// 3. Currency mint validation
+const network = process.env.SOLANA_NETWORK || 'mainnet'; // Or however you determine the network
+if (currency_mint !== ALLOWED_CURRENCIES[network]) {
+ return res.status(400).json({ error: 'Invalid or unsupported currency.' });
+}
+
+// 4. Skill name validation (assuming agent object has a skills array)
+const agent = await db.getAgentById(agentId); // You should have this from auth step
+const agentSkills = agent.meta?.skills || []; // Adjust based on your agent data structure
+if (!agentSkills.some(s => (typeof s === 'string' ? s : s.name) === skill_name)) {
+ return res.status(400).json({ error: `Skill '${skill_name}' is not defined for this agent.` });
+}
+
+// If all checks pass, proceed to database logic...
+```
diff --git a/docs/monetization/04-backend-purchase-endpoint.md b/docs/monetization/04-backend-purchase-endpoint.md
new file mode 100644
index 000000000..822757acb
--- /dev/null
+++ b/docs/monetization/04-backend-purchase-endpoint.md
@@ -0,0 +1,87 @@
+# Prompt 4: Backend Purchase Endpoint
+
+## Objective
+Create a backend API endpoint that generates the necessary Solana transaction for a user to purchase a skill. This endpoint will not execute the transaction but will prepare it for the user to sign on the frontend.
+
+## Explanation
+The purchase process must be secure and initiated by the server. This endpoint (`/api/marketplace/skills/purchase`) will be responsible for fetching the skill's price, identifying the creator's treasury wallet, and constructing an unsigned Solana transfer transaction. This transaction is then sent back to the frontend, which will request the user's signature.
+
+## Instructions
+1. **Create New API File:**
+ * Create a new file in `api/marketplace/skills/purchase.js`. This will contain the logic for the new endpoint.
+
+2. **Endpoint Logic:**
+ * The endpoint should accept a POST request with the `agentId` and `skillName`.
+ * It must also know the `purchaser`'s public key, which should be sent from the frontend.
+ * **Security:** The endpoint must verify the agent and skill exist and have a valid price.
+ * It needs to look up the agent creator's treasury wallet address.
+ * Using the Solana `@solana/web3.js` library, construct a transaction that transfers the correct amount of the specified currency (e.g., USDC) from the `purchaser` to the creator's treasury wallet.
+ * The endpoint should serialize the transaction, but *not* sign it, and return it to the frontend as a base64-encoded string.
+
+## Code Example (`api/marketplace/skills/purchase.js`)
+
+```javascript
+import { Connection, PublicKey, SystemProgram, Transaction, clusterApiUrl } from '@solana/web3.js';
+import { supabase } from '../../_lib/supabase'; // Assuming Supabase for DB
+import { json, error } from '../../_lib/http'; // Assuming helper for responses
+
+// Mock get-token-address library for USDC on Solana
+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d';
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ return error(res, 405, 'Method Not Allowed');
+ }
+
+ const { agentId, skillName, purchaserPublicKey } = req.body;
+
+ if (!agentId || !skillName || !purchaserPublicKey) {
+ return error(res, 400, 'Missing required fields.');
+ }
+
+ // 1. Fetch skill price and agent creator's treasury wallet from DB
+ const { data: priceData, error: priceError } = await supabase
+ .from('agent_skill_prices')
+ .select('amount, currency_mint, agents(creator_treasury_wallet)')
+ .eq('agent_id', agentId)
+ .eq('skill_name', skillName)
+ .single();
+
+ if (priceError || !priceData) {
+ return error(res, 404, 'Skill price not found.');
+ }
+
+ const { amount, currency_mint, agents: { creator_treasury_wallet } } = priceData;
+
+ if (!creator_treasury_wallet) {
+ return error(res, 500, 'Creator has not configured a payout wallet.');
+ }
+
+ // For this example, we assume native SOL transfer for simplicity
+ // A real implementation would handle SPL tokens like USDC, which is more complex.
+ const connection = new Connection(clusterApiUrl('devnet'));
+ const purchaser = new PublicKey(purchaserPublicKey);
+ const recipient = new PublicKey(creator_treasury_wallet);
+
+ const transaction = new Transaction().add(
+ SystemProgram.transfer({
+ fromPubkey: purchaser,
+ toPubkey: recipient,
+ lamports: amount, // Assuming amount is in lamports for SOL transfer
+ })
+ );
+
+ // Set the recent blockhash
+ transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
+ transaction.feePayer = purchaser;
+
+ // Serialize the transaction and convert to base64
+ const serializedTransaction = transaction.serialize({
+ requireAllSignatures: false, // User will sign it
+ }).toString('base64');
+
+ return json(res, {
+ transaction: serializedTransaction,
+ });
+}
+```
diff --git a/docs/monetization/04-solana-pay-frontend-qr.md b/docs/monetization/04-solana-pay-frontend-qr.md
new file mode 100644
index 000000000..ae138c0d5
--- /dev/null
+++ b/docs/monetization/04-solana-pay-frontend-qr.md
@@ -0,0 +1,99 @@
+# Prompt 4: Solana Pay QR Code (Frontend)
+
+## Objective
+Integrate the frontend with the new payment endpoint to display a Solana Pay QR code when a user clicks the "Purchase" button.
+
+## Explanation
+With the backend endpoint ready to generate transactions, we need to update the frontend to request this transaction and display it as a QR code. This allows users to scan the code with their mobile Solana wallet to approve the purchase. We'll use the official `@solana/pay` JavaScript library to generate the QR code.
+
+## Instructions
+1. **Add Frontend Dependency:**
+ * Add the `@solana/pay` library to your frontend `package.json` and install it.
+
+2. **Create a Payment Modal:**
+ * In `marketplace.html` (or your main HTML file), create the HTML structure for a modal dialog. This modal will be hidden by default and will contain the QR code, transaction details, and a spinner.
+
+3. **Implement the Frontend Logic (`src/marketplace.js`):**
+ * Add a delegated event listener to the page that listens for clicks on buttons with the `purchase-skill-btn` class.
+ * When a button is clicked:
+ * Show the payment modal and a loading spinner.
+ * Get the `skillName` and `agentId` from data attributes.
+ * Make a `POST` request to your `/api/payments/prepare-skill-purchase` endpoint.
+ * On success, use the `createQR` function from `@solana/pay` to generate the QR code from the transaction URL.
+ * Mount the QR code SVG element into the modal. Hide the spinner.
+ * Display the transaction message and amount.
+ * Handle any errors from the API call by showing an error message in the modal.
+
+## Code Example (`src/marketplace.js`)
+
+```javascript
+import { createQR } from '@solana/pay';
+
+// ... other imports
+
+function renderPaymentModal(url) {
+ const modal = $('payment-modal'); // Assuming you have a modal element
+ const qrCodeContainer = modal.querySelector('.qr-code-container');
+ const spinner = modal.querySelector('.spinner');
+
+ qrCodeContainer.innerHTML = '';
+ spinner.hidden = true;
+
+ const qr = createQR(url, 300, 'transparent'); // size, background color
+ qr.append(qrCodeContainer);
+
+ modal.showModal(); // Using <dialog> element's API
+}
+
+async function handlePurchaseClick(event) {
+ const button = event.target.closest('.purchase-skill-btn');
+ if (!button) return;
+
+ const skillName = button.dataset.skillName;
+ const agentId = $('d-id').textContent; // Assuming agent ID is available
+
+ const modal = $('payment-modal');
+ modal.querySelector('.spinner').hidden = false;
+ modal.showModal();
+
+ try {
+ const response = await fetch('/api/payments/prepare-skill-purchase', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ agentId, skillName }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`API Error: ${response.statusText}`);
+ }
+
+ const { transaction, message } = await response.json();
+
+ // The Solana Pay URL is constructed from the API response
+ const url = `solana:${encodeURIComponent(transaction)}`;
+
+ renderPaymentModal(url, message);
+
+ } catch (error) {
+ console.error('Purchase failed:', error);
+ modal.querySelector('.error-message').textContent = 'Failed to prepare transaction. Please try again.';
+ modal.querySelector('.spinner').hidden = true;
+ }
+}
+
+document.body.addEventListener('click', handlePurchaseClick);
+```
+
+## HTML Modal Example
+
+```html
+<!-- Add this to your main HTML file -->
+<dialog id="payment-modal">
+ <h2>Complete Your Purchase</h2>
+ <div class="spinner"></div>
+ <div class="qr-code-container"></div>
+ <p class="payment-message"></p>
+ <p class="error-message"></p>
+ <button class="close-modal-btn">Close</button>
+</dialog>
+```
diff --git a/docs/monetization/05-frontend-transaction-signing.md b/docs/monetization/05-frontend-transaction-signing.md
new file mode 100644
index 000000000..76f45d943
--- /dev/null
+++ b/docs/monetization/05-frontend-transaction-signing.md
@@ -0,0 +1,68 @@
+# Prompt 5: Frontend Transaction Signing
+
+## Objective
+Implement the frontend logic to take the serialized transaction from the backend, have the user sign it with their connected wallet, and send it to the Solana network.
+
+## Explanation
+This is the crucial step where the user approves the purchase. The frontend receives the base64-encoded transaction from the backend purchase endpoint. It then needs to decode it, present it to the user's wallet for signing, and upon approval, submit the signed transaction to the blockchain for confirmation.
+
+## Instructions
+1. **Add Frontend API Call:**
+ * In `src/marketplace.js`, within the event handler for the "Buy Now" button in the purchase modal, make a `fetch` POST request to your new `/api/marketplace/skills/purchase` endpoint.
+ * Send the `agentId`, `skillName`, and the connected user's public key in the request body.
+
+2. **Sign and Send Transaction:**
+ * On a successful response from the API, you will receive the serialized transaction.
+ * You need to deserialize it, request the user's wallet to sign it, and then send the raw, signed transaction to the Solana network.
+
+## Code Example (`src/marketplace.js`)
+
+```javascript
+import { Connection, Transaction, clusterApiUrl } from '@solana/web3.js';
+
+// Inside the confirmPurchaseBtn click listener
+confirmPurchaseBtn.addEventListener('click', async () => {
+ const skillName = confirmPurchaseBtn.dataset.skillName;
+ // Assume `agent` and `walletPublicKey` are available in this scope
+ const agentId = agent.id;
+ const purchaserPublicKey = walletPublicKey.toBase58();
+
+ try {
+ // 1. Get transaction from the backend
+ const response = await fetch('/api/marketplace/skills/purchase', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ agentId, skillName, purchaserPublicKey }),
+ });
+
+ if (!response.ok) {
+ const errData = await response.json();
+ throw new Error(errData.error || 'Failed to prepare transaction.');
+ }
+
+ const { transaction: base64Transaction } = await response.json();
+
+ // 2. Deserialize, sign, and send
+ const provider = getProvider(); // The wallet provider from prompt 2
+ const connection = new Connection(clusterApiUrl('devnet'));
+
+ const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));
+
+ // 3. Request user to sign
+ const { signature } = await provider.signAndSendTransaction(transaction, connection);
+
+ // 4. Confirm transaction
+ await connection.confirmTransaction(signature, 'confirmed');
+
+ alert(`Purchase successful! Transaction: ${signature}`);
+
+ // Next step: Call another backend endpoint to formally unlock the skill
+ // This will be covered in another prompt.
+ closePurchaseModal();
+
+ } catch (error) {
+ console.error('Purchase failed:', error);
+ alert(`Purchase failed: ${error.message}`);
+ }
+});
+```
diff --git a/docs/monetization/05-transaction-confirmation-backend.md b/docs/monetization/05-transaction-confirmation-backend.md
new file mode 100644
index 000000000..0a711e68e
--- /dev/null
+++ b/docs/monetization/05-transaction-confirmation-backend.md
@@ -0,0 +1,94 @@
+# Prompt 5: Transaction Confirmation (Backend)
+
+## Objective
+Implement a backend mechanism to verify that a Solana Pay transaction has been successfully processed and confirmed on the blockchain.
+
+## Explanation
+After the user approves the transaction in their wallet, we need a reliable way to confirm its success on the backend. The Solana Pay spec provides a mechanism for this. The wallet will make a `GET` request to the same URL it used for the `POST`, and our backend should verify the transaction signature provided by the wallet.
+
+## Instructions
+1. **Modify the Payment Endpoint (`api/payments/prepare-skill-purchase.js`):**
+ * Our endpoint needs to handle both `POST` (to create the transaction) and `GET` (to verify it).
+ * **For the `POST` request:** When creating the transaction, you must associate it with a unique reference `PublicKey`. This reference key allows you to look up the transaction later. Generate a new keypair for each transaction: `const reference = new Keypair().publicKey;`. Add this reference to the `transfer` instruction. Store this reference in your database, linked to the user, skill, and agent.
+ * **For the `GET` request:** The wallet will include the transaction `signature` in the query string. Your handler should:
+ * Find the transaction on the blockchain using the `signature`.
+ * Verify that the transaction was successful and contains the expected transfers (to the creator and the platform).
+ * Crucially, verify that the transaction includes the `reference` public key you generated, proving it's for this specific purchase.
+ * If everything checks out, proceed to the next step: granting the user access to the skill.
+
+## Code Example (Backend - `api/payments/prepare-skill-purchase.js`)
+
+This example shows the conceptual additions. You'll need to integrate this with your database logic.
+
+```javascript
+// ... imports including Keypair
+import { Keypair } from '@solana/web3.js';
+import { findTransaction, verifyTransaction } from '@solana/pay';
+
+// ... DB function placeholders
+import { savePurchaseReference, findPurchaseByReference, grantSkillToUser } from '../_lib/db';
+
+export default async function handler(req, res) {
+ const connection = new Connection(process.env.SOLANA_RPC_URL);
+
+ if (req.method === 'POST') {
+ // ... POST logic from prompt 3 ...
+
+ // 1. Generate a reference keypair
+ const reference = new Keypair().publicKey;
+
+ // 2. Add it to the transaction so you can find it later
+ // This is a simplified example; typically added to the transfer instruction
+ transaction.add(
+ SystemProgram.transfer({
+ fromPubkey: buyerPublicKey,
+ toPubkey: reference, // Using reference here is for lookup
+ lamports: 0,
+ })
+ );
+
+ // 3. Save reference to DB before sending tx to user
+ await savePurchaseReference(reference.toBase58(), { userId: req.user.id, agentId, skillName });
+
+ // ... continue serializing and sending transaction
+ } else if (req.method === 'GET') {
+ try {
+ const { reference, signature } = req.query;
+ if (!reference || !signature) {
+ return res.status(400).json({ error: 'Missing reference or signature' });
+ }
+
+ // Find the purchase details from your DB using the reference
+ const purchaseDetails = await findPurchaseByReference(reference);
+ if (!purchaseDetails) {
+ return res.status(404).json({ error: 'Purchase reference not found' });
+ }
+
+ // Use Solana Pay's helper to find and verify the transaction
+ const { transaction, status } = await findTransaction(connection, new PublicKey(signature));
+
+ if (status !== 'confirmed') {
+ return res.status(400).json({ error: 'Transaction not confirmed' });
+ }
+
+ // You should add more robust verification here:
+ // - Check the amounts transferred
+ // - Check the destination addresses
+ // - Check that the buyer was the fee payer
+ console.log('Transaction verified successfully!');
+
+ // Grant access to the skill
+ await grantSkillToUser(purchaseDetails.userId, purchaseDetails.skillName);
+
+ res.status(200).json({ status: 'ok', message: 'Purchase confirmed!' });
+
+ } catch (error) {
+ console.error('Verification failed:', error);
+ res.status(500).json({ error: 'Verification failed' });
+ }
+ } else {
+ res.status(405).json({ error: 'Method Not Allowed' });
+ }
+}
+
+```
diff --git a/docs/monetization/05-ui-toggle-for-paid-skills.md b/docs/monetization/05-ui-toggle-for-paid-skills.md
new file mode 100644
index 000000000..b075a7906
--- /dev/null
+++ b/docs/monetization/05-ui-toggle-for-paid-skills.md
@@ -0,0 +1,86 @@
+# Prompt 5: UI Toggle for Paid Skills
+
+## Objective
+Enhance the skill price management UI with dynamic toggles that intuitively show and hide price input fields.
+
+## Explanation
+This prompt focuses on the frontend user experience for creators. Instead of showing price inputs at all times, we'll use a checkbox or toggle switch for each skill. This makes the interface cleaner and the act of setting a price a more deliberate choice.
+
+## Instructions
+1. **File to Edit:**
+ * Continue working in `agent-edit.html` and its associated JavaScript.
+
+2. **Refine the UI Structure:**
+ * For each skill listed in the pricing management section, ensure you have the following HTML structure:
+ * The skill name.
+ * A checkbox/toggle: `<input type="checkbox" class="paid-toggle">`.
+ * A container for the price inputs (e.g., a `<div>`) that is initially hidden if the skill is free.
+
+3. **Implement JavaScript Logic:**
+ * Add an event listener to all `.paid-toggle` checkboxes.
+ * When a checkbox is checked (toggled on):
+ * The associated price input container should become visible (e.g., `style.display = 'flex'`).
+ * You might want to focus the amount input field to encourage the user to enter a price.
+ * When a checkbox is unchecked (toggled off):
+ * The price input container should be hidden (`style.display = 'none'`).
+
+4. **Initial State:**
+ * When the UI is first rendered, the state of each checkbox and the visibility of the price inputs must reflect the current pricing data fetched from the backend. If a skill has a price, its checkbox should be checked and its price inputs should be visible.
+
+## Code Example (Frontend - `agent-edit.html` script)
+
+This builds upon the example from Prompt 3.
+
+```html
+<!-- Example HTML structure for one skill row within agent-edit.html -->
+<div class="form-group skill-price-row">
+ <label class="form-label">summarize-text</label>
+ <div class="skill-price-controls">
+ <input type="checkbox" class="paid-toggle" id="toggle-summarize-text" data-skill="summarize-text">
+ <label for="toggle-summarize-text" class="toggle-label">Paid Skill</label>
+
+ <div class="price-inputs" style="display: none;">
+ <input type="number" class="price-amount" value="1.00" step="0.01" min="0">
+ <span>USDC</span>
+ </div>
+ </div>
+</div>
+```
+
+```css
+/* Add some basic styling for the toggle and inputs in your CSS */
+.skill-price-controls {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+.price-inputs {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+}
+```
+
+```javascript
+// JavaScript to handle the dynamic visibility
+
+document.addEventListener('DOMContentLoaded', () => {
+ // Assume renderSkillPricingUI() has been called and the HTML is on the page
+
+ const container = document.getElementById('skill-pricing-container');
+
+ container.addEventListener('change', (e) => {
+ if (e.target.classList.contains('paid-toggle')) {
+ const controls = e.target.closest('.skill-price-controls');
+ const priceInputs = controls.querySelector('.price-inputs');
+
+ if (e.target.checked) {
+ priceInputs.style.display = 'flex';
+ priceInputs.querySelector('.price-amount').focus();
+ } else {
+ priceInputs.style.display = 'none';
+ }
+ }
+ });
+});
+```
diff --git a/docs/monetization/06-granting-skill-access.md b/docs/monetization/06-granting-skill-access.md
new file mode 100644
index 000000000..895e68006
--- /dev/null
+++ b/docs/monetization/06-granting-skill-access.md
@@ -0,0 +1,69 @@
+# Prompt 6: Granting Skill Access (Backend)
+
+## Objective
+Upon successful purchase confirmation, create a database record that grants the user permanent access to the purchased skill.
+
+## Explanation
+This is the final step in the backend purchase flow. After the payment is verified, the system needs to record that the user now owns the skill. This is typically done by adding an entry to a linking table in the database, for example, `user_skill_ownership`. This record will be the source of truth for determining what premium content a user can access.
+
+## Instructions
+1. **Database Schema:**
+ * If it doesn't exist, design and create a `user_skill_ownership` table.
+ * Essential columns would be `id`, `user_id`, `agent_id`, `skill_name`, and `created_at`.
+ * The combination of `user_id` and `skill_name` (and perhaps `agent_id` if skills are not globally unique) should be unique.
+
+2. **Create a Database Function (`_lib/db.js`):**
+ * Write a function, `grantSkillToUser(userId, agentId, skillName)`, that inserts a new record into the `user_skill_ownership` table.
+ * This function should handle potential errors, such as the user already owning the skill (which shouldn't happen if the purchase button is correctly disabled, but is good for data integrity).
+
+3. **Integrate into Confirmation Flow:**
+ * In the `GET` handler of your `api/payments/prepare-skill-purchase.js` endpoint, after the transaction has been successfully verified (as per the previous prompt), call your new `grantSkillToUser` function.
+ * Pass the authenticated user's ID and the skill details that you retrieved from your database using the transaction `reference`.
+
+## Database Schema Example (SQL)
+
+```sql
+CREATE TABLE user_skill_ownership (
+ id SERIAL PRIMARY KEY,
+ user_id UUID NOT NULL REFERENCES users(id),
+ agent_id UUID NOT NULL REFERENCES agents(id),
+ skill_name VARCHAR(255) NOT NULL,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(user_id, agent_id, skill_name)
+);
+
+-- Add an index for efficient lookups
+CREATE INDEX idx_user_skill_ownership_user_id ON user_skill_ownership(user_id);
+```
+
+## Code Example (Backend - `_lib/db.js`)
+
+```javascript
+// This is a conceptual example using a generic DB client like 'pg' or 'slonik'
+import { db } from './database-client';
+
+export async function grantSkillToUser(userId, agentId, skillName) {
+ try {
+ const result = await db.query(
+ `
+ INSERT INTO user_skill_ownership (user_id, agent_id, skill_name)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (user_id, agent_id, skill_name) DO NOTHING
+ RETURNING id;
+ `,
+ [userId, agentId, skillName]
+ );
+
+ if (result.rows.length > 0) {
+ console.log(`Granted skill '${skillName}' for agent '${agentId}' to user '${userId}'`);
+ return true;
+ } else {
+ console.warn(`User '${userId}' already owns skill '${skillName}' for agent '${agentId}'`);
+ return false; // Already owned
+ }
+ } catch (error) {
+ console.error('Error in grantSkillToUser:', error);
+ throw error;
+ }
+}
+```
diff --git a/docs/monetization/06-marketplace-filters.md b/docs/monetization/06-marketplace-filters.md
new file mode 100644
index 000000000..23edd25a1
--- /dev/null
+++ b/docs/monetization/06-marketplace-filters.md
@@ -0,0 +1,81 @@
+# Prompt 6: Marketplace Filters for Paid/Free Skills
+
+## Objective
+Add filtering options to the marketplace page (`marketplace.html`) to allow users to easily discover agents with paid skills, free skills, or both.
+
+## Explanation
+As the marketplace grows, users will need tools to find the agents that fit their needs and budget. A simple filter for monetization status (Free vs. Paid) is a crucial discovery feature.
+
+## Instructions
+1. **Modify Marketplace UI:**
+ * Open `marketplace.html`.
+ * Locate the filtering section of the page (where category or search filters might already exist).
+ * Add a new set of controls for filtering by price. A dropdown menu or a set of radio buttons would work well.
+ * Options: "All", "Paid Skills", "Free Skills".
+
+2. **Update Frontend JavaScript:**
+ * Open `src/marketplace.js` (or wherever the marketplace frontend logic resides).
+ * Modify the function that fetches the list of agents (e.g., `searchAgents` or `loadAgents`).
+ * This function should now read the value of your new price filter.
+ * Pass the selected filter value as a query parameter in the API request to the backend. For example:
+ * `/api/marketplace/agents?pricing=paid`
+ * `/api/marketplace/agents?pricing=free`
+ * `/api/marketplace/agents` (for "All")
+
+3. **Update Backend API:**
+ * Open the backend file that handles agent listings for the marketplace (e.g., `api/marketplace/agents.js`).
+ * The endpoint should now check for the `pricing` query parameter.
+ * **If `pricing=paid`:** Modify your database query to only return agents that have at least one entry in the `agent_skill_prices` table. This may require a `JOIN` or a subquery.
+ * **If `pricing=free`:** Modify your query to only return agents that have zero entries in the `agent_skill_prices` table. This may require a `LEFT JOIN` and a `WHERE ... IS NULL` check.
+ * **If the parameter is absent:** Return all agents as before.
+
+## Code Example (Frontend - `marketplace.html`)
+
+```html
+<!-- Add to the filter section in marketplace.html -->
+<div class="filter-group">
+ <label for="filter-pricing">Pricing</label>
+ <select id="filter-pricing">
+ <option value="all">All</option>
+ <option value="paid">Paid Skills</option>
+ <option value="free">Free Skills</option>
+ </select>
+</div>
+```
+
+## Code Example (Frontend - `src/marketplace.js`)
+
+```javascript
+// Inside the function that triggers the agent search
+function fetchAndRenderAgents() {
+ const pricingFilter = document.getElementById('filter-pricing').value;
+
+ const queryParams = new URLSearchParams();
+ if (pricingFilter !== 'all') {
+ queryParams.set('pricing', pricingFilter);
+ }
+ // ... add other filters like search query, category ...
+
+ const url = `/api/marketplace/agents?${queryParams.toString()}`;
+
+ fetch(url)
+ .then(res => res.json())
+ .then(data => {
+ renderAgentGrid(data.agents);
+ });
+}
+```
+
+## Code Example (Backend - SQL Query Idea)
+
+```sql
+-- For pricing=paid
+SELECT agents.* FROM agents
+INNER JOIN agent_skill_prices ON agents.id = agent_skill_prices.agent_id
+GROUP BY agents.id;
+
+-- For pricing=free
+SELECT agents.* FROM agents
+LEFT JOIN agent_skill_prices ON agents.id = agent_skill_prices.agent_id
+WHERE agent_skill_prices.agent_id IS NULL;
+```
diff --git a/docs/monetization/06-verifying-purchase-and-unlocking-skill.md b/docs/monetization/06-verifying-purchase-and-unlocking-skill.md
new file mode 100644
index 000000000..5e6f8d51c
--- /dev/null
+++ b/docs/monetization/06-verifying-purchase-and-unlocking-skill.md
@@ -0,0 +1,89 @@
+# Prompt 6: Verifying Purchase and Unlocking Skill
+
+## Objective
+Create a backend system to verify that a skill purchase transaction was successful on-chain and then formally grant the user access to that skill in the database.
+
+## Explanation
+After the frontend submits the transaction to the Solana network, it gets a transaction signature. The frontend then sends this signature to our backend. The backend's job is to use this signature to query the Solana blockchain, confirm the transaction was successfully processed and finalized, and then update our application's database to reflect that the user now owns the skill. This is a critical step for security and ensuring users get what they paid for.
+
+## Instructions
+1. **Create a Verification Endpoint:**
+ * Create a new API endpoint, e.g., `/api/marketplace/skills/verify-purchase`.
+ * This endpoint will accept a POST request containing the `transactionSignature`, `agentId`, and `skillName`.
+
+2. **Backend Verification Logic:**
+ * The endpoint will use the Solana `@solana/web3.js` library to connect to the cluster.
+ * It will call `connection.getTransaction(transactionSignature)` to fetch the transaction details.
+ * The backend must parse the transaction to ensure it matches what was expected:
+ * Was the transfer from the correct buyer?
+ * Was it to the correct creator treasury?
+ * Was the amount correct?
+ * Was the currency (mint) correct?
+ * This verification prevents users from sending fake transaction signatures or signatures for unrelated transactions.
+
+3. **Update the Database:**
+ * If the on-chain transaction is fully verified, the backend will add a new record to a `user_purchased_skills` table.
+ * This table should link a user ID to the agent ID and skill name they purchased.
+
+## Database Schema (`user_purchased_skills`)
+
+```sql
+CREATE TABLE user_purchased_skills (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID REFERENCES auth.users(id) NOT NULL,
+ agent_id UUID REFERENCES agents(id) NOT NULL,
+ skill_name TEXT NOT NULL,
+ purchased_at TIMESTAMPTZ DEFAULT NOW(),
+ transaction_signature TEXT NOT NULL,
+ UNIQUE(user_id, agent_id, skill_name)
+);
+```
+
+## Code Example (`api/marketplace/skills/verify-purchase.js`)
+
+```javascript
+import { Connection, clusterApiUrl } from '@solana/web3.js';
+import { supabase } from '../../_lib/supabase';
+import { json, error } from '../../_lib/http';
+
+export default async function handler(req, res) {
+ const { transactionSignature, agentId, skillName } = req.body;
+ // Assume we get userId from session/token
+ const { userId } = await getUserFromRequest(req);
+
+ if (!userId) return error(res, 401, 'Unauthorized');
+
+ const connection = new Connection(clusterApiUrl('devnet'));
+
+ // 1. Confirm the transaction is valid and finalized
+ const tx = await connection.getTransaction(transactionSignature, { maxSupportedTransactionVersion: 0 });
+
+ if (!tx || !tx.meta || tx.meta.err) {
+ return error(res, 400, 'Transaction not found or failed.');
+ }
+
+ // 2. Perform deep verification (omitted for brevity, but crucial)
+ // - Check sender, receiver, amount, mint etc. match expected values
+ // - This prevents re-using old signatures or sending malicious ones.
+
+ // 3. If verified, record the purchase in the database
+ const { error: dbError } = await supabase
+ .from('user_purchased_skills')
+ .insert({
+ user_id: userId,
+ agent_id: agentId,
+ skill_name: skillName,
+ transaction_signature: transactionSignature,
+ });
+
+ if (dbError) {
+ // Handle potential unique constraint violation (user trying to re-verify)
+ if (dbError.code === '23505') {
+ return json(res, { success: true, message: 'Skill already unlocked.' });
+ }
+ return error(res, 500, 'Failed to record purchase.');
+ }
+
+ return json(res, { success: true, message: 'Skill unlocked successfully!' });
+}
+```
diff --git a/docs/monetization/07-creator-dashboard-monetization-tab.md b/docs/monetization/07-creator-dashboard-monetization-tab.md
new file mode 100644
index 000000000..e86b55e0f
--- /dev/null
+++ b/docs/monetization/07-creator-dashboard-monetization-tab.md
@@ -0,0 +1,93 @@
+# Prompt 7: Creator Dashboard Monetization Tab
+
+## Objective
+Create the basic structure for a new "Monetization" tab within the agent creator's dashboard, where they will manage skill pricing and view earnings.
+
+## Explanation
+To empower creators to sell their skills, they need a dedicated space within the application to manage their monetization settings. This first step involves creating the UI shell for this new section. We will add a new tab to the agent editing interface and create the container where the pricing and earnings components will live.
+
+## Instructions
+1. **Add Tab to Dashboard UI:**
+ * Locate the HTML file for the agent editing/dashboard page (e.g., `agent-edit.html`).
+ * Add a new tab button for "Monetization" alongside existing tabs like "Profile" or "Skills".
+ * Add a corresponding tab panel container that will be shown when the Monetization tab is active.
+
+2. **Implement Tab Switching Logic:**
+ * In the corresponding JavaScript file (e.g., `src/agent-edit.js`), update the tab switching logic to handle the new Monetization tab.
+ * When the Monetization tab is clicked, its panel should become visible, and others should be hidden.
+
+3. **Create Placeholder Content:**
+ * Inside the Monetization tab panel, add placeholder sections for "Skill Pricing" and "Earnings". This sets the stage for future prompts where we will build out these features.
+
+## HTML Example (`agent-edit.html`)
+
+```html
+<!-- In the tab list -->
+<div class="tabs">
+ <button class="tab-link" data-tab="profile">Profile</button>
+ <button class="tab-link" data-tab="skills">Skills</button>
+ <button class="tab-link" data-tab="monetization">Monetization</button>
+</div>
+
+<!-- In the tab content area -->
+<div class="tab-content-wrapper">
+ <div id="profile" class="tab-content">...</div>
+ <div id="skills" class="tab-content">...</div>
+ <div id="monetization" class="tab-content" style="display: none;">
+ <h2>Monetization</h2>
+ <div class="card">
+ <h3>Skill Pricing</h3>
+ <p>Set the price for your agent's premium skills.</p>
+ <div id="skill-pricing-container">
+ <!-- Pricing UI will go here -->
+ </div>
+ </div>
+ <div class="card">
+ <h3>Earnings</h3>
+ <p>View your sales and manage payouts.</p>
+ <div id="earnings-container">
+ <!-- Earnings dashboard will go here -->
+ </div>
+ </div>
+ <div class="card">
+ <h3>Payout Wallet</h3>
+ <p>Set the Solana wallet address where you will receive payments.</p>
+ <div id="treasury-wallet-container">
+ <label for="treasuryWallet">Your Solana Wallet Address:</label>
+ <input type="text" id="treasuryWallet" placeholder="Enter public key...">
+ <button id="saveTreasuryWallet">Save</button>
+ </div>
+ </div>
+ </div>
+</div>
+```
+
+## JavaScript Example (`src/agent-edit.js`)
+
+```javascript
+document.addEventListener('DOMContentLoaded', () => {
+ const tabs = document.querySelectorAll('.tab-link');
+ const contents = document.querySelectorAll('.tab-content');
+
+ tabs.forEach(tab => {
+ tab.addEventListener('click', () => {
+ const target = tab.getAttribute('data-tab');
+
+ // Hide all content
+ contents.forEach(content => {
+ content.style.display = 'none';
+ });
+
+ // Show target content
+ document.getElementById(target).style.display = 'block';
+
+ // Update active tab style
+ tabs.forEach(t => t.classList.remove('active'));
+ tab.classList.add('active');
+ });
+ });
+
+ // Default to the first tab
+ tabs[0].click();
+});
+```
diff --git a/docs/monetization/07-marketplace-paid-indicator.md b/docs/monetization/07-marketplace-paid-indicator.md
new file mode 100644
index 000000000..714c8b12c
--- /dev/null
+++ b/docs/monetization/07-marketplace-paid-indicator.md
@@ -0,0 +1,87 @@
+# Prompt 7: Visual Indicator for Paid Agents in Marketplace
+
+## Objective
+Add a visual badge or indicator to agent cards in the main marketplace grid to quickly show users which agents offer paid skills.
+
+## Explanation
+While filters are useful, users browsing the full list of agents should be able to identify monetized agents at a glance. A simple, clear visual indicator (like a "$" icon or a "Premium" badge) on the agent card will significantly improve scannability.
+
+## Instructions
+1. **Modify Backend API:**
+ * The marketplace agent list endpoint (`/api/marketplace/agents`) needs to provide a flag indicating if an agent has any paid skills.
+ * When querying the list of agents, perform a `JOIN` or a subquery with `agent_skill_prices`.
+ * For each agent in the response, add a boolean field, such as `has_paid_skills: true` or `false`.
+ * *Optimization Note:* This is more efficient than the frontend making a separate request for each agent.
+
+2. **Update Frontend UI:**
+ * Open `src/marketplace.js`, and find the function that renders the grid of agent cards (e.g., `renderAgentGrid`).
+ * Inside the loop that creates each agent card, check for the new `agent.has_paid_skills` flag.
+ * If the flag is `true`, add an HTML element for the badge to the card's template.
+
+3. **Add CSS Styling:**
+ * Open `/marketplace.css` (or the relevant stylesheet).
+ * Add styles for your new badge to make it stand out. Position it in a corner of the agent card, for example.
+
+## Code Example (Backend - SQL Query Idea)
+
+```sql
+-- A query to fetch agents and a flag indicating if they have priced skills
+SELECT
+ agents.*,
+ (CASE WHEN COUNT(agent_skill_prices.skill_name) > 0 THEN TRUE ELSE FALSE END) AS has_paid_skills
+FROM
+ agents
+LEFT JOIN
+ agent_skill_prices ON agents.id = agent_skill_prices.agent_id
+GROUP BY
+ agents.id;
+```
+
+## Code Example (Frontend - `src/marketplace.js`)
+
+```javascript
+// Inside your function that renders the agent grid (e.g., renderAgentGrid)
+
+function renderAgentCard(agent) {
+ const card = document.createElement('div');
+ card.className = 'agent-card';
+
+ const premiumBadge = agent.has_paid_skills
+ ? '<div class="premium-badge" title="Offers paid skills">⚡</div>'
+ : '';
+
+ card.innerHTML = `
+ <div class="card-thumbnail" style="background-image: url('${escapeHtml(agent.thumbnail_url)}')">
+ ${premiumBadge}
+ </div>
+ <div class="card-body">
+ <h3 class="card-title">${escapeHtml(agent.name)}</h3>
+ <p class="card-description">${escapeHtml(agent.description)}</p>
+ </div>
+ `;
+ return card;
+}
+```
+
+## Code Example (CSS - `/marketplace.css`)
+
+```css
+.agent-card .card-thumbnail {
+ position: relative;
+ /* ... existing styles ... */
+}
+
+.premium-badge {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ background-color: rgba(253, 224, 71, 0.9); /* Same as --paid-bg but more opaque */
+ color: #18181b; /* Dark text for contrast */
+ padding: 1px 6px;
+ font-size: 14px;
+ font-weight: 700;
+ border-radius: 6px;
+ line-height: 1.4;
+ box-shadow: 0 1px 3px rgba(0,0,0,0.3);
+}
+```
diff --git a/docs/monetization/07-real-time-ui-update.md b/docs/monetization/07-real-time-ui-update.md
new file mode 100644
index 000000000..afb3aafe4
--- /dev/null
+++ b/docs/monetization/07-real-time-ui-update.md
@@ -0,0 +1,88 @@
+# Prompt 7: Real-time UI Update on Purchase
+
+## Objective
+Update the agent detail page UI in real-time to reflect a successful skill purchase without requiring a page refresh.
+
+## Explanation
+A seamless user experience requires immediate feedback. After a user approves the transaction on their phone, the webpage should detect the successful purchase and automatically update the UI. It should change the "Purchase" button to an "Owned" status indicator. We can achieve this by having the frontend poll a confirmation endpoint while the payment modal is open.
+
+## Instructions
+1. **Create a Polling Endpoint (Backend):**
+ * Create a new, simple endpoint, e.g., `/api/payments/check-purchase-status`.
+ * This endpoint will take a transaction `reference` ID as a query parameter.
+ * It will check the `user_skill_ownership` table to see if the record for that purchase exists.
+ * It should return a status, e.g., `{ status: 'confirmed' }` or `{ status: 'pending' }`.
+
+2. **Implement Polling (Frontend - `src/marketplace.js`):**
+ * When you first make the `POST` request to prepare the transaction, the response should include the unique `reference` ID.
+ * Once the QR code is displayed, start a polling mechanism (e.g., using `setInterval`).
+ * Every 2-3 seconds, make a `GET` request to `/api/payments/check-purchase-status?reference=<reference_id>`.
+ * If the status comes back as `confirmed`:
+ * Stop the polling (`clearInterval`).
+ * Close the payment modal.
+ * Re-render the skills section or dynamically update the specific skill entry in the DOM to show the "Owned" state.
+ * Show a success notification (toast).
+ * The polling should also have a timeout (e.g., 5 minutes) to prevent it from running forever if something goes wrong.
+
+## Code Example (Frontend - `src/marketplace.js`)
+
+```javascript
+// Inside handlePurchaseClick, after the POST request succeeds
+const { transaction, message, reference } = await response.json(); // Backend must return reference
+
+const url = `solana:${encodeURIComponent(transaction)}`;
+renderPaymentModal(url, message);
+
+// Start polling for confirmation
+const pollInterval = setInterval(async () => {
+ try {
+ const statusRes = await fetch(`/api/payments/check-purchase-status?reference=${reference}`);
+ const { status } = await statusRes.json();
+
+ if (status === 'confirmed') {
+ clearInterval(pollInterval);
+ $('payment-modal').close();
+ showToast('Purchase successful!', 'success');
+
+ // Find the button and replace it with an 'Owned' span
+ const button = document.querySelector(`.purchase-skill-btn[data-skill-name="${skillName}"]`);
+ if (button) {
+ const ownedSpan = document.createElement('span');
+ ownedSpan.className = 'skill-owned';
+ ownedSpan.textContent = '✓ Owned';
+ button.replaceWith(ownedSpan);
+ }
+ }
+ } catch (err) {
+ // Silently ignore polling errors, or stop polling after too many failures
+ console.warn('Polling error:', err);
+ }
+}, 2500);
+
+// Add a timeout to stop polling after 5 minutes
+setTimeout(() => {
+ clearInterval(pollInterval);
+}, 300000);
+```
+
+## Backend Status Endpoint (`api/payments/check-purchase-status.js`)
+
+```javascript
+import { findOwnershipByReference } from '../_lib/db'; // Placeholder DB function
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') return res.status(405).end();
+
+ const { reference } = req.query;
+ if (!reference) return res.status(400).json({ error: 'Reference required' });
+
+ // This DB function needs to link the reference to the ownership record
+ const isOwned = await findOwnershipByReference(reference);
+
+ if (isOwned) {
+ return res.status(200).json({ status: 'confirmed' });
+ } else {
+ return res.status(200).json({ status: 'pending' });
+ }
+}
+```
diff --git a/docs/monetization/08-detect-paid-skill-usage.md b/docs/monetization/08-detect-paid-skill-usage.md
new file mode 100644
index 000000000..8ebf510f1
--- /dev/null
+++ b/docs/monetization/08-detect-paid-skill-usage.md
@@ -0,0 +1,83 @@
+# Prompt 8: Detect Paid Skill Usage in Chat
+
+## Objective
+In the chat interface, implement logic to detect when a user attempts to use a skill that requires payment.
+
+## Explanation
+This is the entry point for the payment flow within the chat itself. When the user's prompt is interpreted by the AI and mapped to a specific skill, the system needs to check if that skill has an associated price before attempting to execute it.
+
+## Instructions
+1. **Modify Chat Backend/Orchestrator:**
+ * Identify the part of your application that receives the AI model's response, which indicates the intent to use a skill. This could be in `/api/chat.js` or a similar backend orchestrator.
+ * Before executing the skill, this orchestrator needs access to the agent's skill pricing information.
+ * When fetching the agent's details at the beginning of a chat session, make sure to also fetch its `skill_prices` (as implemented in Prompt 1) and keep them available in the session's context.
+
+2. **Implement the Price Check:**
+ * After the AI model decides which skill to use (e.g., `skill_name: "generate-image"`), but *before* executing the skill's logic, perform a check:
+ ```javascript
+ const skillPrices = agent.skill_prices || {};
+ const price = skillPrices[skillToExecute.name];
+
+ if (price && price.amount > 0) {
+ // This is a paid skill.
+ // Halt execution and proceed to the payment flow.
+ } else {
+ // This is a free skill.
+ // Proceed with normal execution.
+ }
+ ```
+
+3. **Check for Existing Access Grants:**
+ * Before flagging a skill as needing payment, you must first check if the user *already has access*. This requires a new database lookup.
+ * Query the `skill_access_grants` table (which will be created in a later prompt) for a valid grant for the current `user_id`, `agent_id`, and `skill_name`.
+ * A grant is valid if `expires_at` is in the future or `uses_left` is greater than 0.
+ * If a valid grant exists, treat the skill as free and proceed with execution. If not, proceed to the payment flow.
+
+4. **Signal to the Frontend:**
+ * If payment is required, the backend should not execute the skill. Instead, it must send a specific message back to the chat UI.
+ * This can be a special message type in your WebSocket or SSE stream, or a structured JSON response via HTTP.
+ * The message must contain the necessary information to render a payment modal: `skill_name`, `amount`, `currency_mint`.
+
+## Code Example (Backend - `/api/chat.js` or similar)
+
+```javascript
+// Inside the main chat processing logic, after receiving the AI's intent to use a skill
+
+async function processUserMessage(message, agent, user) {
+ // ... logic to get AI response ...
+ const { skillToExecute, parameters } = ai.interpret(message);
+
+ if (skillToExecute) {
+ const skillPrices = agent.skill_prices || {};
+ const price = skillPrices[skillToExecute.name];
+
+ if (price && price.amount > 0) {
+ // Paid skill detected. First, check if user already has access.
+ const hasAccess = await db.checkForValidSkillGrant({
+ userId: user.id,
+ agentId: agent.id,
+ skillName: skillToExecute.name
+ });
+
+ if (!hasAccess) {
+ // No access. Signal to frontend to start payment flow.
+ return {
+ type: 'payment_required',
+ data: {
+ skill_name: skillToExecute.name,
+ amount: price.amount,
+ currency_mint: price.currency_mint
+ }
+ };
+ }
+ // User has access, fall through to execution.
+ }
+
+ // Free skill or user has access, execute it.
+ const result = await executeSkill(skillToExecute.name, parameters);
+ return { type: 'message', data: { text: result } };
+ }
+
+ // ... handle regular text response ...
+}
+```
diff --git a/docs/monetization/08-set-skill-prices-ui.md b/docs/monetization/08-set-skill-prices-ui.md
new file mode 100644
index 000000000..30d07097c
--- /dev/null
+++ b/docs/monetization/08-set-skill-prices-ui.md
@@ -0,0 +1,102 @@
+# Prompt 8: "Set Skill Prices" UI
+
+## Objective
+Create a user interface within the agent creation/editing page (`agent-edit.html`) that allows creators to set prices for their agent's skills.
+
+## Explanation
+To enable monetization, creators need a simple and intuitive way to manage the prices of their skills. This task involves building the UI components (input fields, selectors) where a creator can assign a price and currency to each skill associated with their agent.
+
+## Instructions
+1. **Modify Agent Edit Page (`agent-edit.html`):**
+ * Locate the section where skills are listed or added for an agent.
+ * For each skill listed, add input fields for `price` and a dropdown for `currency`.
+
+2. **Structure the UI:**
+ * The UI should be clear. Next to each skill name, add:
+ * An `<input type="number">` for the price. It should have `step="0.01"` and `min="0"` for decimal values.
+ * A `<select>` dropdown for the currency. Initially, this can be hardcoded to just "USDC". In the future, it could be populated with other SPL tokens.
+ * A "Save Prices" button at the end of the section.
+
+3. **Fetch Existing Prices:**
+ * When the agent edit page loads, it fetches the agent's data. This data should now include any previously saved skill prices.
+ * The UI should be populated with these existing prices when the page loads.
+
+## HTML Example (Inside `agent-edit.html`)
+
+```html
+<!-- Inside the form for editing an agent -->
+<div id="skills-pricing-section">
+ <h3>Monetize Skills</h3>
+ <p>Set a price for your skills. Leave the price as 0 for a free skill.</p>
+ <div id="skill-price-list">
+ <!-- This list will be populated dynamically by JavaScript -->
+ </div>
+ <button type="button" id="save-skill-prices-btn">Save Prices</button>
+</div>
+```
+
+## JavaScript for Rendering (`src/agent-edit.js`)
+
+```javascript
+// Function to render the skill price inputs
+function renderSkillPricing(agent) {
+ const skills = agent.skills || [];
+ const prices = agent.skill_prices || {};
+ const container = document.getElementById('skill-price-list');
+
+ if (!skills.length) {
+ container.innerHTML = '<p>Add skills to your agent to set their prices.</p>';
+ return;
+ }
+
+ container.innerHTML = skills.map(skill => {
+ const skillName = skill.name || skill;
+ const price = prices[skillName] ? (prices[skillName].amount / 1e6) : 0;
+ const currency = prices[skillName] ? prices[skillName].currency_mint : 'USDC';
+
+ return `
+ <div class="skill-price-entry" data-skill-name="${escapeHtml(skillName)}">
+ <label for="price-${escapeHtml(skillName)}">${escapeHtml(skillName)}</label>
+ <input
+ type="number"
+ id="price-${escapeHtml(skillName)}"
+ class="skill-price-input"
+ value="${price}"
+ min="0"
+ step="0.01"
+ placeholder="e.g., 1.99"
+ />
+ <select class="skill-currency-select">
+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d" ${currency === 'USDC' ? 'selected' : ''}>USDC</option>
+ <!-- Other currencies can be added later -->
+ </select>
+ </div>
+ `;
+ }).join('');
+}
+
+// In your page load logic:
+// const agentData = await fetchAgentData(agentId);
+// renderSkillPricing(agentData);
+```
+
+## CSS for Styling
+
+```css
+.skill-price-entry {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin-bottom: 8px;
+}
+.skill-price-entry label {
+ flex: 1;
+ font-weight: 500;
+}
+.skill-price-input, .skill-currency-select {
+ padding: 6px 8px;
+ border-radius: 4px;
+ border: 1px solid var(--border);
+ background: var(--panel);
+}
+```
diff --git a/docs/monetization/09-backend-set-skill-prices.md b/docs/monetization/09-backend-set-skill-prices.md
new file mode 100644
index 000000000..b831ed8d3
--- /dev/null
+++ b/docs/monetization/09-backend-set-skill-prices.md
@@ -0,0 +1,114 @@
+# Prompt 9: Backend for Setting Skill Prices
+
+## Objective
+Create the backend API endpoint for agent creators to save the prices for their skills.
+
+## Explanation
+The UI for setting skill prices needs a corresponding backend endpoint to persist the data. This endpoint will receive the agent ID, skill name, price, and currency, and it will update the `agent_skill_prices` database table accordingly. This requires proper authentication to ensure only the agent's creator can modify prices.
+
+## Instructions
+1. **Create New API File:**
+ * Create a new file, for example, at `api/agents/[id]/pricing.js`. This creates a route like `/api/agents/AGENT_ID/pricing`.
+
+2. **Endpoint Logic (POST/PUT):**
+ * The endpoint should handle POST or PUT requests.
+ * It needs to authenticate the request to ensure the logged-in user is the creator of the agent specified by the ID in the URL.
+ * The request body should contain `skillName`, `amount`, and `currencyMint`.
+ * The logic will perform an "upsert" operation on the `agent_skill_prices` table:
+ * If a price for that agent and skill already exists, it will be updated.
+ * If it doesn't exist, a new record will be created.
+
+3. **Endpoint Logic (GET):**
+ * The same endpoint should handle GET requests to fetch all existing prices for a given agent, which is used by the UI in the previous prompt.
+
+## Database Schema (`agent_skill_prices`)
+
+```sql
+CREATE TABLE agent_skill_prices (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID REFERENCES agents(id) NOT NULL,
+ skill_name TEXT NOT NULL,
+ amount BIGINT NOT NULL, -- Price in smallest unit (e.g., lamports)
+ currency_mint TEXT NOT NULL, -- e.g., PublicKey of the SPL token
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ UNIQUE(agent_id, skill_name)
+);
+
+-- Policy: Only agent creator can manage prices
+CREATE POLICY "Creators can manage their agent skill prices"
+ON agent_skill_prices
+FOR ALL
+USING (auth.uid() = (SELECT creator_id FROM agents WHERE id = agent_id));
+```
+
+## Code Example (`api/agents/[id]/pricing.js`)
+
+```javascript
+import { supabase } from '../../_lib/supabase';
+import { json, error } from '../../_lib/http';
+import { getAuthUser } from '../../_lib/auth';
+
+export default async function handler(req, res) {
+ const { id: agentId } = req.query;
+ const user = await getAuthUser(req);
+
+ if (!user) {
+ return error(res, 401, 'Unauthorized');
+ }
+
+ // Verify ownership
+ const { data: agent, error: agentError } = await supabase
+ .from('agents')
+ .select('creator_id')
+ .eq('id', agentId)
+ .single();
+
+ if (agentError || agent.creator_id !== user.id) {
+ return error(res, 403, 'You do not own this agent.');
+ }
+
+ if (req.method === 'POST') {
+ const { skillName, amount, currencyMint } = req.body;
+
+ if (!skillName || amount == null || !currencyMint) {
+ return error(res, 400, 'Missing required pricing information.');
+ }
+
+ const { data, error: upsertError } = await supabase
+ .from('agent_skill_prices')
+ .upsert({
+ agent_id: agentId,
+ skill_name: skillName,
+ amount: amount,
+ currency_mint: currencyMint,
+ }, { onConflict: 'agent_id, skill_name' })
+ .select();
+
+ if (upsertError) {
+ return error(res, 500, 'Failed to save price.');
+ }
+ return json(res, data[0]);
+
+ } else if (req.method === 'GET') {
+ const { data, error: fetchError } = await supabase
+ .from('agent_skill_prices')
+ .select('*')
+ .eq('agent_id', agentId);
+
+ if (fetchError) {
+ return error(res, 500, 'Failed to fetch prices.');
+ }
+
+ // Reshape into a map for easier frontend use
+ const prices = data.reduce((acc, price) => {
+ acc[price.skill_name] = { amount: price.amount, currency_mint: price.currency_mint };
+ return acc;
+ }, {});
+
+ return json(res, prices);
+ }
+
+ return error(res, 405, 'Method Not Allowed');
+}
+```
diff --git a/docs/monetization/09-payment-required-modal.md b/docs/monetization/09-payment-required-modal.md
new file mode 100644
index 000000000..96bca9efd
--- /dev/null
+++ b/docs/monetization/09-payment-required-modal.md
@@ -0,0 +1,101 @@
+# Prompt 9: "Payment Required" Modal in Chat
+
+## Objective
+Create a modal dialog in the chat UI that appears when a user needs to pay for a skill, clearly presenting the price and prompting for action.
+
+## Explanation
+When the backend signals that a skill requires payment, the frontend must stop the normal message flow and present the user with a clear choice. This modal is the centerpiece of the in-chat purchasing experience.
+
+## Instructions
+1. **File to Edit:**
+ * Open the main JavaScript/Svelte/React component file for your chat interface (e.g., `chat/src/App.svelte` or similar).
+
+2. **Create the Modal HTML/Structure:**
+ * Add the HTML for a modal dialog. It should be hidden by default.
+ * The modal should contain:
+ * A title, e.g., "Premium Skill".
+ * A descriptive text, e.g., "The skill 'generate-image' requires a one-time payment to use."
+ * A display for the price (e.g., "Price: 1.00 USDC").
+ * A "Pay and Continue" button.
+ * A "Cancel" button or close icon.
+
+3. **Implement Frontend Logic:**
+ * Listen for the `payment_required` message from your backend (as designed in Prompt 8).
+ * When this message is received:
+ * Populate the modal with the `skill_name` and `price` information from the message data. Remember to format the amount from lamports to a user-friendly decimal format.
+ * Make the modal visible.
+
+4. **Handle Button Clicks:**
+ * **Cancel:** If the user clicks "Cancel" or closes the modal, hide the modal and perhaps send a "payment cancelled" message to the chat history.
+ * **Pay and Continue:** If the user clicks the pay button:
+ * Keep the modal open but show a loading/spinner state.
+ * Trigger the frontend payment flow function (which will be built in the next prompt). This function will orchestrate the API calls and wallet interaction.
+
+## Code Example (Frontend - Svelte Component)
+
+```svelte
+<!-- In your main chat component, e.g., App.svelte -->
+
+{#if paymentRequired}
+<div class="modal-backdrop">
+ <div class="modal">
+ <h3>Premium Skill</h3>
+ <p>
+ The skill <strong>{paymentDetails.skill_name}</strong> requires a payment to continue.
+ </p>
+ <div class="price-display">
+ Price: <span>{(paymentDetails.amount / 1e6).toFixed(2)} USDC</span>
+ </div>
+
+ {#if isLoadingPayment}
+ <div class="spinner">Processing...</div>
+ {:else}
+ <div class="modal-actions">
+ <button on:click={cancelPayment}>Cancel</button>
+ <button class="primary" on:click={initiatePayment}>Pay and Continue</button>
+ </div>
+ {/if}
+ </div>
+</div>
+{/if}
+
+<script>
+ let paymentRequired = false;
+ let paymentDetails = {};
+ let isLoadingPayment = false;
+
+ // Function to be called when backend sends 'payment_required'
+ function onPaymentRequired(details) {
+ paymentDetails = details;
+ paymentRequired = true;
+ isLoadingPayment = false;
+ }
+
+ function cancelPayment() {
+ paymentRequired = false;
+ // Optionally add a "Cancelled" message to the chat history
+ }
+
+ async function initiatePayment() {
+ isLoadingPayment = true;
+ try {
+ // This function will be implemented in the next prompt
+ const result = await handlePaymentFlow(paymentDetails);
+ if (result.success) {
+ paymentRequired = false;
+ // The backend will now re-run the skill and send the result.
+ } else {
+ // Handle payment failure, show an error
+ isLoadingPayment = false;
+ }
+ } catch (err) {
+ // Handle errors from the payment flow
+ isLoadingPayment = false;
+ }
+ }
+</script>
+
+<style>
+ /* Add styles for .modal-backdrop, .modal, .price-display, etc. */
+</style>
+```
diff --git a/docs/monetization/09-save-skill-prices-backend.md b/docs/monetization/09-save-skill-prices-backend.md
new file mode 100644
index 000000000..c7b03071d
--- /dev/null
+++ b/docs/monetization/09-save-skill-prices-backend.md
@@ -0,0 +1,100 @@
+# Prompt 9: Save Skill Prices (Backend)
+
+## Objective
+Create a backend API endpoint that allows agent creators to save the prices they have set for their skills.
+
+## Explanation
+After a creator sets up the prices for their skills in the UI (from the previous prompt), we need a secure endpoint to save this information to the database. This endpoint will receive a list of skills and their prices, validate the data, and update the `agent_skill_prices` table.
+
+## Instructions
+1. **Database Schema:**
+ * Ensure you have an `agent_skill_prices` table.
+ * Columns should include `id`, `agent_id`, `skill_name`, `amount` (as a `bigint` to store lamports), and `currency_mint` (as a string).
+ * The combination of `agent_id` and `skill_name` should be unique.
+
+2. **Create the API Endpoint:**
+ * Create a new file, e.g., `api/agents/[id]/skill-prices.js`.
+ * This endpoint should handle `POST` or `PUT` requests.
+ * It must be protected, ensuring only the agent's creator can update the prices.
+
+3. **Implement the Endpoint Logic:**
+ * The request body should contain an object or array of skill prices, like: `[{ skillName: 'DataAnalysis', price: 1.99, currency: 'USDC' }, ...]`.
+ * The handler should:
+ * Authenticate the user and verify they own the agent specified by `:id`.
+ * Iterate through the submitted skill prices.
+ * For each skill, convert the price (e.g., 1.99 USDC) into its smallest unit (lamports, e.g., 1,990,000).
+ * Perform an "upsert" operation on the `agent_skill_prices` table:
+ * If a price for that `agent_id` and `skill_name` already exists, `UPDATE` it.
+ * If it doesn't exist, `INSERT` a new row.
+ * Return a success response.
+
+## SQL for `agent_skill_prices` Table
+
+```sql
+CREATE TABLE agent_skill_prices (
+ id SERIAL PRIMARY KEY,
+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
+ skill_name VARCHAR(255) NOT NULL,
+ amount BIGINT NOT NULL, -- e.g., 1_990_000 for 1.99 USDC
+ currency_mint VARCHAR(255) NOT NULL,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(agent_id, skill_name)
+);
+```
+
+## Code Example (Backend - `api/agents/[id]/skill-prices.js`)
+
+```javascript
+import { db } from '../../_lib/database-client';
+import { verifyAgentOwnership } from '../../_lib/auth';
+
+const USDC_DECIMALS = 6;
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') return res.status(405).end();
+
+ try {
+ const agentId = req.query.id;
+ const userId = req.user.id; // From auth middleware
+
+ // 1. Verify ownership
+ if (!await verifyAgentOwnership(userId, agentId)) {
+ return res.status(403).json({ error: 'You do not own this agent.' });
+ }
+
+ const { prices } = req.body; // Expects: [{ skillName, price, currencyMint }]
+ if (!Array.isArray(prices)) {
+ return res.status(400).json({ error: 'Invalid prices format.' });
+ }
+
+ // 2. Use a transaction to update all prices atomically
+ await db.tx(async t => {
+ for (const item of prices) {
+ const { skillName, price, currencyMint } = item;
+
+ // 3. Convert to lamports (smallest unit)
+ const amountInLamports = Math.round(parseFloat(price) * (10 ** USDC_DECIMALS));
+
+ await t.query(
+ `
+ INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (agent_id, skill_name) DO UPDATE SET
+ amount = EXCLUDED.amount,
+ currency_mint = EXCLUDED.currency_mint,
+ updated_at = CURRENT_TIMESTAMP;
+ `,
+ [agentId, skillName, amountInLamports, currencyMint]
+ );
+ }
+ });
+
+ res.status(200).json({ message: 'Skill prices updated successfully.' });
+
+ } catch (error) {
+ console.error('Error saving skill prices:', error);
+ res.status(500).json({ error: 'Internal Server Error' });
+ }
+}
+```
diff --git a/docs/monetization/10-backend-prepare-payment.md b/docs/monetization/10-backend-prepare-payment.md
new file mode 100644
index 000000000..14b969f24
--- /dev/null
+++ b/docs/monetization/10-backend-prepare-payment.md
@@ -0,0 +1,101 @@
+# Prompt 10: Backend Endpoint to Prepare Payment
+
+## Objective
+Create a backend endpoint that prepares a Solana transaction for the user to sign to pay for a skill.
+
+## Explanation
+This is a critical security step. The server, not the client, must construct the transaction. This prevents tampering with the payment amount or destination. This endpoint will generate an unsigned transaction that transfers the correct amount from the user to the appropriate account and return it to the client for signing.
+
+## Instructions
+1. **Create API Route:**
+ * Set up a new endpoint: `POST /api/payments/prepare-skill-payment`.
+ * This endpoint must be authenticated.
+
+2. **Request Body:**
+ * The endpoint should accept a JSON body with `agent_id` and `skill_name`.
+
+3. **Backend Logic:**
+ * **Fetch Price:** Using `agent_id` and `skill_name`, look up the price (`amount` and `currency_mint`) from the `agent_skill_prices` table. If no price is found, return an error.
+ * **Identify Payer and Receiver:**
+ * The **payer** is the authenticated user making the request. Get their public key.
+ * The **receiver** is the agent's associated treasury or holdings account. This address should be stored with the agent's data.
+ * **Construct the Transaction:**
+ * Using the Solana Web3.js library (`@solana/web3.js`), create a new `Transaction`.
+ * Add a `spl-token` `createTransfer` instruction.
+ * **Source:** The user's Associated Token Account (ATA) for the given `currency_mint`.
+ * **Destination:** The agent's treasury ATA for the same `currency_mint`.
+ * **Amount:** The `amount` from the database.
+ * **Owner:** The user's public key.
+ * **Set Blockhash and Fee Payer:**
+ * Get a recent blockhash from the Solana cluster.
+ * Set the `recentBlockhash` and `feePayer` (the user) on the transaction.
+ * **Create Payment Record:**
+ * Create a record in a new `skill_payments` table with a `pending` status. Include `user_id`, `agent_id`, `skill_name`, `amount`, and the transaction's blockhash for later reference. Store a unique ID for this payment intent.
+ * **Serialize and Respond:**
+ * Serialize the *unsigned* transaction and encode it (e.g., in Base64).
+ * Return the serialized transaction and the unique payment ID to the frontend.
+
+## Code Example (Backend - `/api/payments/prepare-skill-payment.js`)
+
+```javascript
+import { Transaction, SystemProgram, PublicKey } from '@solana/web3.js';
+import { createTransferInstruction } from '@solana/spl-token';
+import { getAssociatedTokenAddress } from '@solana/spl-token';
+
+// --- Inside your API handler ---
+
+const { agent_id, skill_name } = req.body;
+const user = await getAuthenticatedUser(req);
+
+// 1. Fetch skill price and agent details
+const priceInfo = await db.getSkillPrice(agent_id, skill_name);
+const agent = await db.getAgentById(agent_id);
+if (!priceInfo || !agent) {
+ return res.status(404).json({ error: 'Skill or agent not found.' });
+}
+
+// 2. Define parties
+const payerPublicKey = new PublicKey(user.solana_pubkey);
+const receiverPublicKey = new PublicKey(agent.treasury_address); // The agent's main treasury wallet
+const currencyMint = new PublicKey(priceInfo.currency_mint);
+
+// 3. Find the ATAs for the token transfer
+const payerAta = await getAssociatedTokenAddress(currencyMint, payerPublicKey);
+const receiverAta = await getAssociatedTokenAddress(currencyMint, receiverPublicKey);
+
+// 4. Create the transfer instruction
+const transferInstruction = createTransferInstruction(
+ payerAta, // from
+ receiverAta, // to
+ payerPublicKey, // from's owner
+ priceInfo.amount // amount
+);
+
+// 5. Create the transaction
+const connection = new Connection(process.env.SOLANA_RPC_URL);
+const { blockhash } = await connection.getRecentBlockhash();
+
+const transaction = new Transaction({
+ recentBlockhash: blockhash,
+ feePayer: payerPublicKey,
+}).add(transferInstruction);
+
+// 6. Create a pending payment record
+const paymentIntent = await db.createPaymentIntent({
+ userId: user.id,
+ agentId: agent.id,
+ skillName: skill_name,
+ amount: priceInfo.amount,
+ reference: blockhash, // Use blockhash or a new UUID as a reference
+});
+
+// 7. Serialize and respond
+const serializedTransaction = transaction.serialize({
+ requireAllSignatures: false,
+}).toString('base64');
+
+res.status(200).json({
+ paymentId: paymentIntent.id,
+ transaction: serializedTransaction,
+});
+```
diff --git a/docs/monetization/10-backend-transaction-verification.md b/docs/monetization/10-backend-transaction-verification.md
new file mode 100644
index 000000000..600d7a31c
--- /dev/null
+++ b/docs/monetization/10-backend-transaction-verification.md
@@ -0,0 +1,104 @@
+---
+status: not-started
+---
+
+# Prompt 10: Backend - Transaction Verification and Fulfillment
+
+## Objective
+Create a backend mechanism to securely verify a Solana transaction and, upon success, record the skill ownership in the database.
+
+## Explanation
+A crucial security step is to verify the payment on the backend *after* the frontend reports it as confirmed. The frontend can be manipulated, so the server must independently fetch the transaction details from the Solana RPC and validate them before granting access to the skill. This is the "fulfillment" step of the purchase.
+
+## Instructions
+1. **Create a Verification API Endpoint:**
+ * Create a new API file, e.g., `api/payments/verify-transaction.js`.
+ * This endpoint will accept a `POST` request at `/api/payments/verify-transaction`.
+ * The frontend will call this endpoint *after* it has successfully confirmed the transaction on its end.
+
+2. **Request Body and Authentication:**
+ * The request body should contain:
+ * `signature`: The transaction signature returned by `sendRawTransaction`.
+ * `agentId`: The agent ID for the skill purchased.
+ * `skillName`: The name of the skill purchased.
+ * This endpoint must be authenticated to get the `userId` of the purchaser.
+
+3. **Backend Verification Logic:**
+ * Inside the API handler:
+ 1. **Fetch Transaction:** Use the Solana `connection.getParsedTransaction(signature)` method to get the transaction details from the RPC.
+ 2. **Prevent Replay Attacks:** Check if this `signature` has already been used to unlock a skill in your `user_unlocked_skills` table. If it exists, return an error. This is critical.
+ 3. **Fetch Skill Price:** Get the expected price (`amount`, `currency_mint`) and the creator's wallet address from your database for the given `agentId` and `skillName`.
+ 4. **Validate Details:** Parse the fetched transaction and verify that:
+ * It was successful (the `meta.err` field in the response is `null`).
+ * It contains a token transfer instruction.
+ * The transfer's `source` address belongs to the authenticated user (`userId`).
+ * The transfer's `destination` address belongs to the agent's creator.
+ * The transfer `amount` matches the expected price from your database.
+ * The transfer `mint` matches the expected currency from your database.
+ 5. **Handle Failure:** If any of these checks fail, return a `400 Bad Request` or `422 Unprocessable Entity` error with a clear message.
+
+4. **Record Ownership:**
+ * If all checks pass, `INSERT` a new row into the `user_unlocked_skills` table with the `userId`, `agentId`, `skillName`, `purchase_tx_signature`, and the price details.
+
+5. **Return Success:**
+ * Return a `200 OK` response to the frontend to confirm that the backend has successfully verified and fulfilled the purchase.
+
+## Code Example (`api/payments/verify-transaction.js`)
+
+```javascript
+import { Connection, PublicKey } from '@solana/web3.js';
+import { json, wrap } from '../_lib/http.js';
+import { getAuth } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+
+const connection = new Connection(process.env.SOLANA_RPC_ENDPOINT);
+
+export default wrap(async (req, res) => {
+ // ... authentication ...
+ const { userId } = await getAuth(req);
+ const { signature, agentId, skillName } = req.body;
+
+ // 1. Check for replay attacks
+ const [existing] = await sql`SELECT id FROM user_unlocked_skills WHERE purchase_tx_signature = ${signature}`;
+ if (existing) {
+ return json(res, 409, { error: 'Transaction has already been used.' });
+ }
+
+ // 2. Fetch expected price and creator info from DB
+ // ... query to get priceInfo and creatorWallet ...
+
+ // 3. Fetch and parse the transaction from Solana RPC
+ const tx = await connection.getParsedTransaction(signature, 'confirmed');
+ if (!tx || tx.meta.err) {
+ return json(res, 400, { error: 'Transaction not found or failed.' });
+ }
+
+ // 4. Validate the transaction details (this is a simplified example)
+ const transfer = tx.transaction.message.instructions.find(
+ (ix) => ix.parsed?.type === 'transfer' && ix.program === 'spl-token'
+ );
+
+ if (!transfer) {
+ return json(res, 400, { error: 'No valid SPL token transfer found.' });
+ }
+
+ const { source, destination, amount } = transfer.parsed.info;
+ // You would also need to verify the owner of the source account matches the user.
+ // This requires more complex parsing of account data.
+
+ const expectedAmount = priceInfo.amount.toString();
+ const expectedDestination = creatorTokenAccountAddress; // You need to derive this
+
+ if (amount !== expectedAmount || destination !== expectedDestination) {
+ return json(res, 400, { error: 'Transaction details do not match expected values.' });
+ }
+
+ // 5. If all checks pass, record the purchase
+ await sql`
+ INSERT INTO user_unlocked_skills (user_id, agent_id, skill_name, purchase_tx_signature, purchase_amount, purchase_currency_mint)
+ VALUES (${userId}, ${agentId}, ${skillName}, ${signature}, ${priceInfo.amount}, ${priceInfo.currency_mint})
+ `;
+
+ return json(res, 200, { success: true, message: 'Skill unlocked.' });
+});
+```
diff --git a/docs/monetization/10-creator-payout-wallet-management.md b/docs/monetization/10-creator-payout-wallet-management.md
new file mode 100644
index 000000000..f07b8bcf6
--- /dev/null
+++ b/docs/monetization/10-creator-payout-wallet-management.md
@@ -0,0 +1,115 @@
+# Prompt 10: Creator Payout Wallet Management
+
+## Objective
+Implement the UI and backend logic for an agent creator to specify their Solana treasury wallet, where they will receive payments from skill sales.
+
+## Explanation
+For creators to receive their earnings, they must provide a valid Solana wallet address. This task involves adding an input field in the monetization dashboard for this address and creating a secure backend endpoint to save it. This address will be stored and associated with the agent, to be used later in the payment transaction logic.
+
+## Instructions
+1. **Add UI in Dashboard:**
+ * In the "Monetization" tab in `agent-edit.html`, use the placeholder from prompt #7. It should contain an `<input>` for the wallet public key and a "Save" button.
+
+2. **Frontend Logic:**
+ * In `src/agent-edit.js`, fetch the agent's current treasury wallet address when the tab loads and populate the input field.
+ * Add a click event listener to the "Save" button. This handler will read the value from the input, perform basic validation (e.g., check if it's a valid Solana public key format), and send it to the backend.
+
+3. **Backend Endpoint:**
+ * Create a new endpoint, for example `/api/agents/[id]/treasury`, to handle updating the treasury wallet.
+ * This endpoint must be secure, verifying that the user making the request is the creator of the agent.
+ * It will take the `treasuryWallet` public key from the request body and update the `creator_treasury_wallet` column on the `agents` table for the specified agent.
+
+## Database Schema (Alter `agents` table)
+
+```sql
+-- Add a new column to the agents table to store the payout address
+ALTER TABLE agents
+ADD COLUMN creator_treasury_wallet TEXT;
+
+-- You might want to add a check constraint for valid base58 format
+-- but this can also be handled at the application layer.
+```
+
+## Code Example (`src/agent-edit.js`)
+
+```javascript
+// Add to the monetization tab logic
+const treasuryInput = document.getElementById('treasuryWallet');
+const saveTreasuryBtn = document.getElementById('saveTreasuryWallet');
+
+async function loadTreasuryWallet(agentId) {
+ const agent = await getAgentData(agentId); // Assuming this function exists
+ if (agent.creator_treasury_wallet) {
+ treasuryInput.value = agent.creator_treasury_wallet;
+ }
+}
+
+saveTreasuryBtn.addEventListener('click', async () => {
+ const agentId = /* get agent id from context */;
+ const newWallet = treasuryInput.value.trim();
+
+ // Basic validation (more robust validation is recommended)
+ if (!newWallet || newWallet.length < 32 || newWallet.length > 44) {
+ alert('Please enter a valid Solana public key.');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/api/agents/${agentId}/treasury`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ treasuryWallet: newWallet }),
+ });
+
+ if (!response.ok) throw new Error('Failed to save wallet address.');
+
+ alert('Payout wallet updated successfully!');
+ } catch (error) {
+ alert(`Error: ${error.message}`);
+ }
+});
+
+// Call loadTreasuryWallet when the tab is shown
+```
+
+## Code Example (`api/agents/[id]/treasury.js`)
+
+```javascript
+import { supabase } from '../../_lib/supabase';
+import { json, error } from '../../_lib/http';
+import { getAuthUser } from '../../_lib/auth';
+
+export default async function handler(req, res) {
+ if (req.method !== 'PUT') return error(res, 405, 'Method Not Allowed');
+
+ const { id: agentId } = req.query;
+ const user = await getAuthUser(req);
+ const { treasuryWallet } = req.body;
+
+ if (!user) return error(res, 401, 'Unauthorized');
+ if (!treasuryWallet) return error(res, 400, 'Missing treasuryWallet');
+
+ // Verify ownership
+ const { data: agent, error: agentError } = await supabase
+ .from('agents')
+ .select('creator_id')
+ .eq('id', agentId)
+ .single();
+
+ if (agentError || agent.creator_id !== user.id) {
+ return error(res, 403, 'Forbidden');
+ }
+
+ // Update the agent's treasury wallet
+ const { error: updateError } = await supabase
+ .from('agents')
+ .update({ creator_treasury_wallet: treasuryWallet })
+ .eq('id', agentId);
+
+ if (updateError) {
+ return error(res, 500, 'Failed to update treasury wallet.');
+ }
+
+ return json(res, { success: true });
+}
+```
diff --git a/docs/monetization/10-creator-payout-wallet.md b/docs/monetization/10-creator-payout-wallet.md
new file mode 100644
index 000000000..f8f02810d
--- /dev/null
+++ b/docs/monetization/10-creator-payout-wallet.md
@@ -0,0 +1,80 @@
+# Prompt 10: Creator Payouts Wallet
+
+## Objective
+Add a field in the user's settings or profile page for creators to specify the Solana wallet address where they want to receive payments for their paid skills.
+
+## Explanation
+To pay creators, we need to know where to send the funds. This task involves adding a UI element and the corresponding backend logic to allow users to save their primary payout wallet address. This address will be used as the destination for all skill purchase transactions.
+
+## Instructions
+1. **Database Schema Update:**
+ * Add a new nullable column to your `users` table, such as `payout_wallet_address` (of type `VARCHAR(255)`).
+
+2. **Update the User Settings UI:**
+ * In the user's profile or dashboard page (e.g., `profile.html`), add a new section for "Payout Information".
+ * Include an `<input type="text">` field for the user to enter their Solana wallet address.
+ * Add a "Save" button for this section.
+
+3. **Frontend Logic:**
+ * When the page loads, fetch the current user's data and populate the input field with their saved `payout_wallet_address`, if it exists.
+ * When the "Save" button is clicked:
+ * Perform basic client-side validation to check if the input looks like a valid Solana address (e.g., check length, base58 characters).
+ * Make a `PUT` or `POST` request to a new backend endpoint to save the address.
+
+4. **Backend Endpoint:**
+ * Create an endpoint, e.g., `/api/users/me/payout-wallet`.
+ * This endpoint should be authenticated.
+ * It will receive the wallet address in the request body.
+ * Perform server-side validation to ensure it's a valid public key.
+ * Update the `payout_wallet_address` column for the authenticated user in the `users` table.
+
+## HTML Example (`profile.html`)
+
+```html
+<div class="settings-section">
+ <h2>Payout Wallet</h2>
+ <p>Enter the Solana wallet address where you'd like to receive payments.</p>
+ <div class="form-group">
+ <label for="payout-wallet">Solana Wallet Address</label>
+ <input type="text" id="payout-wallet" placeholder="Enter your public key">
+ <small id="wallet-error" class="error-text"></small>
+ </div>
+ <button id="save-payout-wallet-btn">Save Wallet Address</button>
+</div>
+```
+
+## Frontend JavaScript Example
+
+```javascript
+import { PublicKey } from '@solana/web3.js';
+
+const saveBtn = document.getElementById('save-payout-wallet-btn');
+const walletInput = document.getElementById('payout-wallet');
+const errorEl = document.getElementById('wallet-error');
+
+saveBtn.addEventListener('click', async () => {
+ const address = walletInput.value.trim();
+ errorEl.textContent = '';
+
+ // Client-side validation
+ try {
+ new PublicKey(address); // Throws an error if invalid
+ } catch (e) {
+ errorEl.textContent = 'Invalid Solana address.';
+ return;
+ }
+
+ // Send to backend
+ const response = await fetch('/api/users/me/payout-wallet', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ walletAddress: address }),
+ });
+
+ if (response.ok) {
+ showToast('Payout wallet updated!', 'success');
+ } else {
+ showToast('Failed to update wallet.', 'error');
+ }
+});
+```
diff --git a/docs/monetization/11-backend-creator-wallet-table.md b/docs/monetization/11-backend-creator-wallet-table.md
new file mode 100644
index 000000000..dd6006a46
--- /dev/null
+++ b/docs/monetization/11-backend-creator-wallet-table.md
@@ -0,0 +1,54 @@
+---
+status: not-started
+---
+
+# Prompt 11: Backend - Creator Wallet Table
+
+## Objective
+Create a database table for agent creators to securely store their Solana payout wallet address.
+
+## Explanation
+To pay creators their share of skill sales, we need to know where to send the funds. A dedicated table, `creator_payout_wallets`, will store a mapping between a `user_id` and their chosen Solana wallet address. This separates the payout wallet from their login credentials or other profile information, providing flexibility and better security.
+
+## Instructions
+1. **Design the Table Schema:**
+ * Name the table `creator_payout_wallets`.
+ * It needs a column to link to the user (`user_id`), which should be unique. This enforces a one-to-one relationship: one user account has one payout wallet.
+ * It needs a column to store the Solana wallet public key (`wallet_address` as `VARCHAR(44)`).
+ * Add a primary key on `user_id` for efficient lookups and to enforce the unique constraint.
+ * Add a foreign key constraint from `user_id` to the `users(id)` table.
+ * Include `created_at` and `updated_at` timestamps.
+
+2. **Create a SQL Migration File:**
+ * Create a new SQL migration file (e.g., `scripts/migrations/004_create_creator_payout_wallets.sql`).
+ * Write the `CREATE TABLE` statement for `creator_payout_wallets`.
+ * Set up the `updated_at` trigger for this new table as you've done for previous tables.
+
+## Code Example (SQL)
+
+```sql
+-- scripts/migrations/004_create_creator_payout_wallets.sql
+
+CREATE TABLE IF NOT EXISTS creator_payout_wallets (
+ user_id INTEGER PRIMARY KEY,
+ -- Solana public key address
+ wallet_address VARCHAR(44) NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT fk_user
+ FOREIGN KEY(user_id)
+ REFERENCES users(id)
+ ON DELETE CASCADE
+);
+
+-- Use the existing trigger function for updated_at
+CREATE TRIGGER set_timestamp
+BEFORE UPDATE ON creator_payout_wallets
+FOR EACH ROW
+EXECUTE PROCEDURE set_updated_at_timestamp();
+
+```
+
+## Note on Data Integrity
+By setting `user_id` as the primary key, we ensure that each user can only have one payout wallet entry. When they want to change their wallet, we will perform an `UPDATE` operation on their existing row rather than inserting a new one.
diff --git a/docs/monetization/11-backend-payout-logic.md b/docs/monetization/11-backend-payout-logic.md
new file mode 100644
index 000000000..d15c37d5b
--- /dev/null
+++ b/docs/monetization/11-backend-payout-logic.md
@@ -0,0 +1,86 @@
+# Prompt 11: Backend Logic for Payouts
+
+## Objective
+Integrate the creator's saved payout wallet address into the skill purchase transaction logic.
+
+## Explanation
+Now that creators can specify their payout wallet, we need to ensure our payment processing logic uses this address as the destination for funds. This task involves modifying the backend Solana Pay endpoint to fetch the creator's payout address and use it when constructing the transaction.
+
+## Instructions
+1. **Create a Database Function (`_lib/db.js`):**
+ * Write a new function, `findCreatorPayoutWallet(agentId)`.
+ * This function should first find the `creator_id` (a `user_id`) from the `agents` table using the `agentId`.
+ * Then, it should query the `users` table to get the `payout_wallet_address` for that `creator_id`.
+ * The function should return the wallet address as a string.
+
+2. **Update the Payment Endpoint (`api/payments/prepare-skill-purchase.js`):**
+ * In the main handler, before you construct the transaction, call your new `findCreatorPayoutWallet` function.
+ * Use the returned wallet address as the `destination` for the main portion of the SPL token transfer.
+ * If no payout wallet is configured for the creator, the transaction should fail with an informative error. This prevents funds from being sent to a null or invalid address.
+
+## Code Example (Backend - `_lib/db.js`)
+
+```javascript
+import { db } from './database-client';
+
+export async function findCreatorPayoutWallet(agentId) {
+ try {
+ const result = await db.one(
+ `
+ SELECT u.payout_wallet_address
+ FROM users u
+ JOIN agents a ON a.creator_id = u.id
+ WHERE a.id = $1;
+ `,
+ [agentId]
+ );
+ return result.payout_wallet_address;
+ } catch (error) {
+ // 'one' will throw an error if no row is found
+ console.error(`Could not find payout wallet for agent ${agentId}:`, error);
+ return null;
+ }
+}
+```
+
+## Updated Payment Endpoint (`api/payments/prepare-skill-purchase.js`)
+
+```javascript
+// ... (imports)
+import { findCreatorPayoutWallet, findSkillPrice } from '../_lib/db';
+
+// ... (handler start)
+
+ try {
+ // ... (authentication and body validation)
+
+ // Find the creator's configured payout wallet
+ const creatorPayoutWalletAddress = await findCreatorPayoutWallet(agentId);
+ if (!creatorPayoutWalletAddress) {
+ return res.status(500).json({
+ error: 'Creator has not configured a payout wallet. Purchase cannot be completed.'
+ });
+ }
+ const creatorPublicKey = new PublicKey(creatorPayoutWalletAddress);
+
+ // ... (find skill price, get blockhash)
+
+ // The rest of the transaction logic now uses creatorPublicKey as the destination
+ const creatorUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, creatorPublicKey);
+
+ // ... (create transfer instructions for creator and platform fee)
+ transaction.add(
+ createTransferInstruction(
+ buyerUsdcAddress,
+ creatorUsdcAddress, // Use the fetched wallet
+ buyerPublicKey,
+ creatorAmount
+ )
+ );
+
+ // ... (rest of the logic)
+
+ } catch (error) {
+ // ... (error handling)
+ }
+```
diff --git a/docs/monetization/11-creator-earnings-dashboard-ui.md b/docs/monetization/11-creator-earnings-dashboard-ui.md
new file mode 100644
index 000000000..f185b2a2f
--- /dev/null
+++ b/docs/monetization/11-creator-earnings-dashboard-ui.md
@@ -0,0 +1,99 @@
+# Prompt 11: Creator Earnings Dashboard UI
+
+## Objective
+Design and implement a basic UI for the creator's "Earnings" dashboard, which will display their total revenue, the number of sales, and a list of recent transactions.
+
+## Explanation
+To provide value to creators, they need visibility into how their skills are performing. This dashboard is the central place for them to track their sales. This task involves creating the frontend components to display this data. The data itself will be fetched from a new backend endpoint (created in the next prompt).
+
+## Instructions
+1. **Design the UI Layout:**
+ * Inside the `#earnings-container` in `agent-edit.html`, create the HTML structure for the earnings dashboard.
+ * Include "stat cards" for key metrics like "Total Revenue", "Total Sales", and "Balance".
+ * Add a table structure for a list of recent transactions, with columns for "Date", "Skill", "Price", and "Transaction ID".
+
+2. **Frontend JavaScript:**
+ * In `src/agent-edit.js`, create a function `renderEarningsDashboard`.
+ * This function will be called when the monetization tab is displayed.
+ * It will make a `fetch` call to a new backend endpoint (e.g., `/api/agents/[id]/earnings`) to get the sales data.
+ * Upon receiving the data, it will populate the stat cards and dynamically generate the rows for the transaction table.
+
+3. **Styling:**
+ * Add styles to `/public/agent-edit.css` to format the stat cards and the transaction table, ensuring it's readable and visually appealing.
+
+## HTML Example (`agent-edit.html` inside `#earnings-container`)
+
+```html
+<div class="earnings-stats">
+ <div class="stat-card">
+ <h4>Total Revenue</h4>
+ <p id="total-revenue-stat">$0.00</p>
+ </div>
+ <div class="stat-card">
+ <h4>Total Sales</h4>
+ <p id="total-sales-stat">0</p>
+ </div>
+ <div class="stat-card">
+ <h4>Withdrawable Balance</h4>
+ <p id="balance-stat">$0.00</p>
+ </div>
+</div>
+
+<h4 class="table-header">Recent Sales</h4>
+<div class="transactions-table">
+ <div class="table-header-row">
+ <div>Date</div>
+ <div>Skill</div>
+ <div>Price</div>
+ <div>Transaction</div>
+ </div>
+ <div id="transactions-list">
+ <!-- Rows will be injected here by JS -->
+ <div class="table-empty-state">No sales yet.</div>
+ </div>
+</div>
+```
+
+## JavaScript Example (`src/agent-edit.js`)
+
+```javascript
+async function renderEarningsDashboard(agentId) {
+ const response = await fetch(`/api/agents/${agentId}/earnings`);
+ const data = await response.json();
+
+ document.getElementById('total-revenue-stat').textContent = `$${(data.totalRevenue / 1e6).toFixed(2)}`;
+ document.getElementById('total-sales-stat').textContent = data.totalSales;
+ document.getElementById('balance-stat').textContent = `$${(data.balance / 1e6).toFixed(2)}`;
+
+ const listContainer = document.getElementById('transactions-list');
+ if (data.recentSales && data.recentSales.length > 0) {
+ listContainer.innerHTML = data.recentSales.map(sale => `
+ <div class="table-row">
+ <div>${new Date(sale.purchased_at).toLocaleDateString()}</div>
+ <div>${escapeHtml(sale.skill_name)}</div>
+ <div>$${(sale.price / 1e6).toFixed(2)}</div>
+ <div>
+ <a href="https://solscan.io/tx/${sale.transaction_signature}?cluster=devnet" target="_blank">
+ ${sale.transaction_signature.slice(0, 6)}...
+ </a>
+ </div>
+ </div>
+ `).join('');
+ } else {
+ listContainer.innerHTML = '<div class="table-empty-state">No sales yet.</div>';
+ }
+}
+```
+
+## CSS Example (`/public/agent-edit.css`)
+
+```css
+.earnings-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px; margin-bottom: 24px; }
+.stat-card { background: #101018; padding: 16px; border-radius: 8px; border: 1px solid var(--border); }
+.stat-card h4 { margin: 0 0 8px; color: var(--muted); font-size: 14px; }
+.stat-card p { margin: 0; font-size: 24px; font-weight: 600; }
+.table-header-row, .table-row { display: grid; grid-template-columns: 1fr 1fr 1fr 2fr; padding: 12px 8px; border-bottom: 1px solid var(--border); }
+.table-header-row { font-weight: bold; color: var(--muted); }
+.table-row a { color: var(--accent); text-decoration: none; }
+.table-row a:hover { text-decoration: underline; }
+```
diff --git a/docs/monetization/11-frontend-payment-flow.md b/docs/monetization/11-frontend-payment-flow.md
new file mode 100644
index 000000000..ac8f3d49a
--- /dev/null
+++ b/docs/monetization/11-frontend-payment-flow.md
@@ -0,0 +1,90 @@
+# Prompt 11: Frontend Payment Flow and Wallet Signing
+
+## Objective
+Implement the client-side logic to receive the prepared transaction from the backend, prompt the user to sign it with their Solana wallet, and send it to the blockchain.
+
+## Explanation
+This prompt connects the UI to the user's wallet (e.g., Phantom, Solflare). It orchestrates the most critical part of the user-facing flow: approving the transaction.
+
+## Instructions
+1. **File to Edit:**
+ * Continue working in your main chat component's JavaScript (e.g., `chat/src/App.svelte`).
+
+2. **Wallet Adapter Integration:**
+ * Ensure you have a Solana wallet adapter library integrated into your project. If not, you will need to add one (e.g., `@solana/wallet-adapter-react`, `@solana/wallet-adapter-base`). The project seems to have some wallet integration already, so tap into that. A function like `detectSolanaWallet()` is mentioned elsewhere.
+
+3. **Create `handlePaymentFlow` Function:**
+ * This async function will be called when the user clicks "Pay and Continue" in the modal.
+ * It should accept the `paymentDetails` (skill\_name, agent\_id, etc.) as an argument.
+
+4. **Step-by-Step Logic within `handlePaymentFlow`:**
+ * **a. Fetch Transaction:** Make a `POST` request to your `/api/payments/prepare-skill-payment` endpoint, sending the `agent_id` and `skill_name`.
+ * **b. Deserialize Transaction:** The API will return a Base64 encoded transaction. You need to deserialize it back into a `Transaction` object.
+ ```javascript
+ import { Transaction } from '@solana/web3.js';
+ const { paymentId, transaction: base64Transaction } = await response.json();
+ const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));
+ ```
+ * **c. Connect to Wallet:** Ensure the user's wallet is connected. If not, prompt them to connect.
+ * **d. Sign and Send:** Use the wallet adapter to sign and send the transaction. This is typically a single function call that both prompts the user in their wallet and, upon approval, sends the transaction to the network.
+ ```javascript
+ const wallet = getSolanaWallet(); // Your project's way of getting the adapter
+ const signature = await wallet.sendTransaction(transaction, connection);
+ ```
+ * **e. Confirm Transaction:** Wait for the transaction to be confirmed by the Solana cluster.
+ ```javascript
+ await connection.confirmTransaction(signature, 'confirmed');
+ ```
+ * **f. Notify Backend:** Once confirmed, make a final API call to your backend to verify the payment (this will be built in the next prompt). Pass the `paymentId` and the `signature`.
+ * **g. Return Status:** Return a success or failure object to the modal's logic.
+
+## Code Example (Frontend - Chat Component)
+
+```javascript
+// This function is called from the modal's "Pay" button
+async function handlePaymentFlow(paymentDetails) {
+ try {
+ // a. Fetch Transaction
+ const prepRes = await fetch('/api/payments/prepare-skill-payment', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ agent_id: agent.id, // Assuming agent is in scope
+ skill_name: paymentDetails.skill_name
+ })
+ });
+ if (!prepRes.ok) throw new Error('Failed to prepare payment.');
+
+ const { paymentId, transaction: base64Transaction } = await prepRes.json();
+
+ // b. Deserialize
+ const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));
+
+ // c. & d. Connect, Sign, and Send
+ const wallet = getSolanaWallet();
+ if (!wallet.connected) await wallet.connect();
+
+ const connection = new Connection(process.env.SOLANA_RPC_URL);
+ const signature = await wallet.sendTransaction(transaction, connection);
+
+ // e. Confirm
+ await connection.confirmTransaction(signature, 'confirmed');
+
+ // f. Notify Backend
+ const confirmRes = await fetch('/api/payments/confirm-skill-payment', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ paymentId, signature })
+ });
+ if (!confirmRes.ok) throw new Error('Payment confirmation failed on server.');
+
+ // g. Return Success
+ return { success: true };
+
+ } catch (error) {
+ console.error("Payment failed:", error);
+ // Optionally display a user-friendly error message
+ return { success: false, error: error.message };
+ }
+}
+```
diff --git a/docs/monetization/12-backend-confirm-payment.md b/docs/monetization/12-backend-confirm-payment.md
new file mode 100644
index 000000000..dab42455a
--- /dev/null
+++ b/docs/monetization/12-backend-confirm-payment.md
@@ -0,0 +1,86 @@
+# Prompt 12: Backend Endpoint to Confirm Payment
+
+## Objective
+Create a backend endpoint to confirm that a user's on-chain payment was successful, and then trigger the logic to grant them access to the skill.
+
+## Explanation
+After the user signs and sends the transaction, the frontend informs the backend. The backend must then verify on-chain that the transaction was successful and matches the expected payment details. This server-side confirmation is a crucial security step to prevent fraudulent access claims.
+
+## Instructions
+1. **Create API Route:**
+ * Set up a new endpoint: `POST /api/payments/confirm-skill-payment`.
+ * This endpoint must be authenticated.
+
+2. **Request Body:**
+ * The endpoint should accept `paymentId` (from the prepare step) and the `signature` of the confirmed transaction.
+
+3. **Backend Logic:**
+ * **a. Retrieve Payment Intent:** Use the `paymentId` to fetch the `pending` payment record from your `skill_payments` table. If not found or not pending, return an error. Verify that the payment intent belongs to the authenticated user.
+ * **b. Fetch and Verify Transaction:**
+ * Use the `signature` to fetch the transaction details from the Solana cluster using `connection.getTransaction(signature)`.
+ * **Crucial Verifications:**
+ * Check that the transaction was successful (`err: null`).
+ * Parse the transaction's instructions. Find the `spl-token` transfer instruction.
+ * Verify the **source**, **destination**, and **amount** from the on-chain transaction match the details stored in your `skill_payments` record. This prevents users from submitting a signature for a different, unrelated transaction.
+ * Verify the transaction's blockhash or a stored reference to prevent replay attacks.
+ * **c. Update Payment Status:** If all verifications pass, update the `skill_payments` record status from `pending` to `completed`.
+ * **d. Grant Skill Access:** Call the logic to create a record in the `skill_access_grants` table for this user and skill (to be fully implemented in a later prompt).
+ * **e. Re-trigger AI Flow:** The chat orchestrator should now re-process the original user message that was paused. Since the access grant now exists, the skill check (Prompt 8) will pass, and the skill will execute. The simplest way to do this is to have the `/confirm` endpoint return a success message, and the frontend, upon seeing this success, resubmits the original chat message.
+ * **f. Respond:** Return a `200 OK` success message.
+
+## Code Example (Backend - `/api/payments/confirm-skill-payment.js`)
+
+```javascript
+// --- Inside your API handler ---
+
+const { paymentId, signature } = req.body;
+const user = await getAuthenticatedUser(req);
+
+// a. Retrieve Payment Intent
+const paymentIntent = await db.getPaymentIntent(paymentId);
+if (!paymentIntent || paymentIntent.status !== 'pending' || paymentIntent.userId !== user.id) {
+ return res.status(404).json({ error: 'Invalid or expired payment session.' });
+}
+
+try {
+ // b. Fetch and Verify Transaction
+ const connection = new Connection(process.env.SOLANA_RPC_URL);
+ const tx = await connection.getTransaction(signature, { maxSupportedTransactionVersion: 0 });
+
+ if (tx.meta.err) {
+ throw new Error('Transaction failed on-chain.');
+ }
+
+ // Find the relevant token transfer instruction (this logic can be complex)
+ // You may need a helper to parse instructions based on program ID
+ const transferInstruction = findSplTransfer(tx.transaction.message.instructions);
+
+ // A simplified check. In reality, you need to parse account keys from the message.
+ const onChainAmount = transferInstruction.data.amount;
+ if (onChainAmount < paymentIntent.amount) {
+ throw new Error('On-chain amount does not match expected amount.');
+ }
+ // ... more checks for source, destination, etc.
+
+ // c. Update Payment Status
+ await db.updatePaymentStatus(paymentId, 'completed', signature);
+
+ // d. Grant Skill Access
+ await db.createSkillAccessGrant({
+ userId: user.id,
+ agentId: paymentIntent.agentId,
+ skillName: paymentIntent.skillName,
+ // Define your access rules, e.g., expires in 24 hours
+ expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
+ });
+
+ // e. Respond for frontend to continue
+ res.status(200).json({ success: true, message: 'Payment confirmed.' });
+
+} catch (error) {
+ console.error('Confirmation error:', error);
+ // Optionally update payment status to 'failed'
+ await db.updatePaymentStatus(paymentId, 'failed');
+ res.status(400).json({ error: 'Payment verification failed.', details: error.message });
+}
+```
diff --git a/docs/monetization/12-backend-for-earnings-data.md b/docs/monetization/12-backend-for-earnings-data.md
new file mode 100644
index 000000000..ca26894ac
--- /dev/null
+++ b/docs/monetization/12-backend-for-earnings-data.md
@@ -0,0 +1,90 @@
+# Prompt 12: Backend for Earnings Data
+
+## Objective
+Create the backend endpoint that calculates and returns the earnings data for an agent creator, including total revenue, sales count, and recent transactions.
+
+## Explanation
+The creator's earnings dashboard needs data to display. This endpoint (`/api/agents/[id]/earnings`) will be responsible for querying the database to aggregate sales data for a specific agent. It will calculate key metrics and retrieve the most recent sales to populate the UI created in the previous prompt.
+
+## Instructions
+1. **Create New API File:**
+ * Create a new file at `api/agents/[id]/earnings.js`.
+
+2. **Endpoint Logic (GET):**
+ * The endpoint must handle a GET request.
+ * It must be authenticated, ensuring the user making the request is the creator of the agent.
+ * The logic will perform several database queries:
+ * Query the `user_purchased_skills` table, filtering by `agent_id`.
+ * To get the revenue, it will need to join with `agent_skill_prices` to get the `amount` for each sale.
+ * Calculate the SUM of the `amount` for total revenue.
+ * Calculate the COUNT of rows for total sales.
+ * Fetch the 10 most recent sales, ordered by `purchased_at` descending.
+ * The endpoint should return a JSON object containing `totalRevenue`, `totalSales`, `balance` (for now, same as revenue), and an array of `recentSales`.
+
+## Code Example (`api/agents/[id]/earnings.js`)
+
+```javascript
+import { supabase } from '../../_lib/supabase';
+import { json, error } from '../../_lib/http';
+import { getAuthUser } from '../../_lib/auth';
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') return error(res, 405, 'Method Not Allowed');
+
+ const { id: agentId } = req.query;
+ const user = await getAuthUser(req);
+
+ if (!user) return error(res, 401, 'Unauthorized');
+
+ // Verify ownership
+ const { data: agent, error: agentError } = await supabase
+ .from('agents')
+ .select('creator_id')
+ .eq('id', agentId)
+ .single();
+
+ if (agentError || agent.creator_id !== user.id) {
+ return error(res, 403, 'Forbidden');
+ }
+
+ // Fetch all sales for this agent
+ const { data: sales, error: salesError } = await supabase
+ .from('user_purchased_skills')
+ .select(`
+ purchased_at,
+ skill_name,
+ transaction_signature,
+ agent_skill_prices ( amount )
+ `)
+ .eq('agent_id', agentId)
+ .order('purchased_at', { ascending: false });
+
+ if (salesError) {
+ return error(res, 500, 'Failed to fetch sales data.');
+ }
+
+ const totalSales = sales.length;
+ const totalRevenue = sales.reduce((acc, sale) => {
+ // The price is on the joined table
+ const price = sale.agent_skill_prices?.amount || 0;
+ return acc + price;
+ }, 0);
+
+ const recentSales = sales.slice(0, 10).map(s => ({
+ purchased_at: s.purchased_at,
+ skill_name: s.skill_name,
+ price: s.agent_skill_prices?.amount || 0,
+ transaction_signature: s.transaction_signature,
+ }));
+
+ // Balance calculation would be more complex with payouts, for now it's total revenue.
+ const balance = totalRevenue;
+
+ return json(res, {
+ totalRevenue,
+ totalSales,
+ balance,
+ recentSales,
+ });
+}
+```
diff --git a/docs/monetization/12-creator-earnings-dashboard.md b/docs/monetization/12-creator-earnings-dashboard.md
new file mode 100644
index 000000000..4b7407cf0
--- /dev/null
+++ b/docs/monetization/12-creator-earnings-dashboard.md
@@ -0,0 +1,81 @@
+# Prompt 12: Creator Earnings and Dashboard
+
+## Status
+- [ ] Not Started
+
+## Objective
+Develop a dashboard for agent creators to view their total earnings and a list of their sales.
+
+## Explanation
+To create a complete ecosystem, creators need visibility into their monetization performance. This prompt outlines the creation of a private dashboard where they can track their earnings.
+
+## Instructions
+1. **Create a Sales/Earnings Table:**
+ * Design a new database table, e.g., `skill_sales`, to log every successful sale.
+ * Columns should include: `id`, `agent_id`, `skill_name`, `buyer_id`, `seller_id`, `amount`, `currency_mint`, `transaction_signature`, and `created_at`.
+
+2. **Log Sales on Purchase:**
+ * Modify the `/api/payments/finalize-purchase` endpoint from Prompt 8.
+ * After recording skill ownership, add another step to insert a record into the new `skill_sales` table.
+
+3. **Create a Backend API for the Dashboard:**
+ * Create a new authenticated endpoint, e.g., `GET /api/creator/dashboard`.
+ * This endpoint should:
+ * Calculate the creator's total earnings by summing the `amount` from the `skill_sales` table, grouped by currency.
+ * Fetch a list of recent sales transactions for the creator.
+
+4. **Build the Frontend Dashboard:**
+ * Create a new page, `creator-dashboard.html`, accessible only to logged-in users.
+ * On this page, fetch data from the new dashboard API.
+ * Display the total earnings and the list of recent sales in a clear and readable format.
+
+## SQL for `skill_sales`
+```sql
+CREATE TABLE skill_sales (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL REFERENCES agents(id),
+ skill_name VARCHAR(255) NOT NULL,
+ buyer_id UUID NOT NULL REFERENCES users(id),
+ seller_id UUID NOT NULL REFERENCES users(id),
+ amount BIGINT NOT NULL,
+ currency_mint VARCHAR(255) NOT NULL,
+ transaction_signature VARCHAR(255) NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX idx_skill_sales_on_seller_id ON skill_sales (seller_id);
+```
+
+## Code Example (Backend - `/api/creator/dashboard.js`)
+```javascript
+// Example using a hypothetical DB utility
+import { db } from './_db.js';
+import { getUserIdFromRequest } from './_auth.js';
+
+export default async function handler(req, res) {
+ const userId = await getUserIdFromRequest(req);
+
+ // 1. Get total earnings
+ const earningsResult = await db.query(
+ `SELECT currency_mint, SUM(amount) as total_earned
+ FROM skill_sales
+ WHERE seller_id = $1
+ GROUP BY currency_mint`,
+ [userId]
+ );
+ const totalEarnings = earningsResult.rows;
+
+ // 2. Get recent sales
+ const salesResult = await db.query(
+ `SELECT skill_name, amount, currency_mint, created_at, transaction_signature
+ FROM skill_sales
+ WHERE seller_id = $1
+ ORDER BY created_at DESC
+ LIMIT 50`,
+ [userId]
+ );
+ const recentSales = salesResult.rows;
+
+ res.status(200).json({ totalEarnings, recentSales });
+}
+```
diff --git a/docs/monetization/12-my-purchased-skills-page.md b/docs/monetization/12-my-purchased-skills-page.md
new file mode 100644
index 000000000..2893af338
--- /dev/null
+++ b/docs/monetization/12-my-purchased-skills-page.md
@@ -0,0 +1,77 @@
+# Prompt 12: "My Purchased Skills" Page
+
+## Objective
+Create a new page or a dedicated section in the user's dashboard that lists all the skills they have purchased across all agents.
+
+## Explanation
+Users need a central place to see all the premium content they've acquired. This improves user experience and provides a clear overview of their purchases. This task involves creating the UI for this page and wiring it up to a new backend endpoint.
+
+## Instructions
+1. **Create a New HTML Page or Section:**
+ * You can either create a new file, `my-skills.html`, or add a new section to an existing dashboard page (e.g., `dashboard.html`).
+ * The page should have a clear heading like "My Purchased Skills".
+ * It should contain a list or grid element that will be populated with the purchased skills.
+
+2. **Frontend JavaScript Logic:**
+ * Create a new JavaScript file or add to an existing one that's loaded on the dashboard page.
+ * On page load, make a `GET` request to a new API endpoint (`/api/users/me/owned-skills`) to fetch the list of skills.
+ * For each skill returned, render an item in the list. Each item should display:
+ * The skill's name.
+ * The name of the agent it belongs to (and maybe a link to that agent's page).
+ * The date of purchase.
+ * The price paid.
+
+3. **UI/UX Considerations:**
+ * Include a loading state while the skills are being fetched.
+ * Display a user-friendly message if the user hasn't purchased any skills yet (e.g., "You haven't purchased any skills yet. Explore the marketplace to find new abilities for your agents!").
+
+## HTML Example (`dashboard.html`)
+
+```html
+<!-- Add this section to the dashboard -->
+<section id="my-skills">
+ <h2>My Purchased Skills</h2>
+ <div id="owned-skills-list" class="skills-grid">
+ <!-- Skeletons for loading state -->
+ <div class="skill-card-skeleton"></div>
+ <div class="skill-card-skeleton"></div>
+ <div class="skill-card-skeleton"></div>
+ </div>
+</section>
+```
+
+## JavaScript Logic Example
+
+```javascript
+async function loadOwnedSkills() {
+ const container = document.getElementById('owned-skills-list');
+ try {
+ const response = await fetch('/api/users/me/owned-skills');
+ if (!response.ok) throw new Error('Failed to fetch skills');
+
+ const skills = await response.json();
+
+ if (skills.length === 0) {
+ container.innerHTML = '<p>You have not purchased any skills yet.</p>';
+ return;
+ }
+
+ container.innerHTML = skills.map(skill => `
+ <div class="owned-skill-card">
+ <h3>${escapeHtml(skill.skill_name)}</h3>
+ <p>From Agent: <a href="/marketplace/agent/${skill.agent_id}">${escapeHtml(skill.agent_name)}</a></p>
+ <div class="skill-meta">
+ <span>Purchased: ${new Date(skill.purchase_date).toLocaleDateString()}</span>
+ <span>Price: ${(skill.price_amount / 1e6).toFixed(2)} USDC</span>
+ </div>
+ </div>
+ `).join('');
+
+ } catch (error) {
+ container.innerHTML = '<p class="error">Could not load your skills. Please try again later.</p>';
+ console.error('Error loading skills:', error);
+ }
+}
+
+document.addEventListener('DOMContentLoaded', loadOwnedSkills);
+```
diff --git a/docs/monetization/13-api-for-owned-skills.md b/docs/monetization/13-api-for-owned-skills.md
new file mode 100644
index 000000000..cf4a6e4c7
--- /dev/null
+++ b/docs/monetization/13-api-for-owned-skills.md
@@ -0,0 +1,68 @@
+# Prompt 13: API for Owned Skills (Backend)
+
+## Objective
+Create the backend API endpoint that provides a list of skills owned by the currently authenticated user.
+
+## Explanation
+This endpoint will power the "My Purchased Skills" page (from the previous prompt). It needs to query the database, joining across several tables (`user_skill_ownership`, `agents`, `agent_skill_prices`) to gather all the necessary information for display.
+
+## Instructions
+1. **Create the API Endpoint:**
+ * Create a new file: `/api/users/me/owned-skills.js`.
+ * This endpoint should handle `GET` requests and must be protected by authentication.
+
+2. **Implement the Database Query:**
+ * The core of this endpoint is the SQL query. You need to:
+ * Select all records from `user_skill_ownership` that match the authenticated `user_id`.
+ * `JOIN` with the `agents` table on `agent_id` to get the agent's name.
+ * `LEFT JOIN` with the `agent_skill_prices` table on both `agent_id` and `skill_name` to get the price information. Note that price could have changed, so you might want to store the purchase price in the ownership table itself for historical accuracy (a task for a future prompt). For now, joining to get the *current* price is acceptable.
+ * Select the required fields: `skill_name`, `agent_id`, `agent_name`, `purchase_date` (`created_at` from the ownership table), and the price info.
+
+3. **Return the Data:**
+ * Execute the query and return the resulting list of skill objects as a JSON array.
+
+## Code Example (Backend - `api/users/me/owned-skills.js`)
+
+```javascript
+import { db } from '../../_lib/database-client';
+
+export default async function handler(req, res) {
+ if (req.method !== 'GET') return res.status(405).end();
+
+ try {
+ const userId = req.user.id; // From auth middleware
+
+ const { rows } = await db.query(
+ `
+ SELECT
+ uso.skill_name,
+ uso.created_at AS purchase_date,
+ a.id AS agent_id,
+ a.name AS agent_name,
+ asp.amount AS price_amount,
+ asp.currency_mint AS price_currency
+ FROM
+ user_skill_ownership AS uso
+ JOIN
+ agents AS a ON uso.agent_id = a.id
+ LEFT JOIN
+ agent_skill_prices AS asp ON uso.agent_id = asp.agent_id AND uso.skill_name = asp.skill_name
+ WHERE
+ uso.user_id = $1
+ ORDER BY
+ uso.created_at DESC;
+ `,
+ [userId]
+ );
+
+ res.status(200).json(rows);
+
+ } catch (error) {
+ console.error('Failed to fetch owned skills:', error);
+ res.status(500).json({ error: 'Internal Server Error' });
+ }
+}
+```
+
+## Future Improvement Note
+For true historical accuracy, the `user_skill_ownership` table should be modified to store the `amount` and `currency_mint` at the time of purchase. This prevents the user's purchase history from changing if the creator later updates the skill price. This could be its own future prompt: "Refine Purchase History for Price Accuracy."
diff --git a/docs/monetization/13-db-schema-access-grants.md b/docs/monetization/13-db-schema-access-grants.md
new file mode 100644
index 000000000..a8c9ebf2c
--- /dev/null
+++ b/docs/monetization/13-db-schema-access-grants.md
@@ -0,0 +1,65 @@
+# Prompt 13: Database Schema for Skill Access Grants
+
+## Objective
+Design and create the database table schema for `skill_access_grants` to track which users have permission to use specific paid skills.
+
+## Explanation
+After a user pays for a skill, we need a persistent record of their access rights. This table will serve as the source of truth for the backend to check before executing a potentially paid skill. It needs to be flexible enough to support different access models, such as time-based expiry or a fixed number of uses.
+
+## Instructions
+1. **Define the Table Schema:**
+ * Create a new table named `skill_access_grants`.
+ * The table should include the following columns:
+ * `id`: A unique primary key (e.g., UUID or auto-incrementing integer).
+ * `user_id`: Foreign key referencing the `users` table. This identifies who bought the skill.
+ * `agent_id`: Foreign key referencing the `agents` table.
+ * `skill_name`: A string that matches the name of the skill.
+ * `payment_id`: Foreign key referencing the `skill_payments` table, linking the grant to the specific purchase.
+ * `created_at`: Timestamp of when the grant was created.
+ * `expires_at`: A nullable timestamp. If set, the grant is valid until this time. This supports time-based access (e.g., 24-hour pass).
+ * `uses_left`: A nullable integer. If set, the grant is valid for this many uses. This supports pay-per-use models.
+
+2. **Create Indexes:**
+ * Create a composite index on `(user_id, agent_id, skill_name)` for fast lookups when checking for access before skill execution.
+ * Also, add an index on `expires_at` to efficiently query for expired grants if you need a cleanup job later.
+
+3. **Write the SQL Migration:**
+ * Create a new SQL migration file to apply this schema change to your database.
+
+## SQL Schema Example
+
+```sql
+CREATE TABLE skill_access_grants (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
+ skill_name VARCHAR(255) NOT NULL,
+ payment_id UUID NOT NULL REFERENCES skill_payments(id),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ expires_at TIMESTAMPTZ,
+ uses_left INTEGER,
+
+ -- A user can have multiple grants for the same skill over time, so a unique constraint isn't on user/agent/skill
+ CONSTRAINT check_positive_uses_left CHECK (uses_left IS NULL OR uses_left >= 0)
+);
+
+-- Index for fast access checks
+CREATE INDEX idx_skill_access_grants_check ON skill_access_grants(user_id, agent_id, skill_name);
+
+-- Index for cleaning up expired grants
+CREATE INDEX idx_skill_access_grants_expires_at ON skill_access_grants(expires_at);
+
+-- You'll also need a skill_payments table
+CREATE TABLE skill_payments (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES users(id),
+ agent_id UUID NOT NULL,
+ skill_name VARCHAR(255) NOT NULL,
+ amount BIGINT NOT NULL,
+ currency_mint VARCHAR(255) NOT NULL,
+ status VARCHAR(50) NOT NULL DEFAULT 'pending', -- pending, completed, failed
+ signature VARCHAR(255) UNIQUE, -- The on-chain transaction signature
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+```
diff --git a/docs/monetization/13-platform-fee-implementation.md b/docs/monetization/13-platform-fee-implementation.md
new file mode 100644
index 000000000..96f6efeab
--- /dev/null
+++ b/docs/monetization/13-platform-fee-implementation.md
@@ -0,0 +1,74 @@
+# Prompt 13: Platform Fee Implementation
+
+## Status
+- [ ] Not Started
+
+## Objective
+Implement a platform fee on every skill purchase, where a percentage of the sale amount is sent to a platform-owned treasury wallet.
+
+## Explanation
+To ensure the platform is sustainable, a platform fee is essential. This requires modifying the transaction creation logic to split the payment between the seller and the platform.
+
+## Instructions
+1. **Configure Treasury Wallet:**
+ * Store the platform's treasury wallet address in a secure configuration file or environment variable (e.g., `PLATFORM_TREASURY_WALLET`).
+
+2. **Modify Transaction Creation API:**
+ * In the `/api/payments/prepare-transaction` endpoint, calculate the platform fee based on the total price (e.g., a 5% fee).
+ * The total price is `priceInfo.amount`.
+ * `platformFee = priceInfo.amount * 0.05`
+ * `sellerAmount = priceInfo.amount - platformFee`
+
+3. **Create a Multi-Instruction Transaction:**
+ * The Solana transaction will now have two `createTransferInstruction` calls:
+ 1. A transfer of `sellerAmount` from the buyer to the seller.
+ 2. A transfer of `platformFee` from the buyer to the platform's treasury wallet.
+ * Add both instructions to the same transaction. This ensures the payment split is atomic—either both transfers succeed, or neither does.
+
+## Code Example (Backend - `/api/payments/prepare-transaction.js` Update)
+```javascript
+// ... (imports and initial setup)
+
+// Inside the handler function, after fetching priceInfo and sellerPublicKey
+const PLATFORM_FEE_BPS = 500; // 500 basis points = 5%
+const PLATFORM_TREASURY = new PublicKey(process.env.PLATFORM_TREASURY_WALLET);
+
+const totalAmount = priceInfo.amount;
+const platformFee = Math.floor(totalAmount * (PLATFORM_FEE_BPS / 10000));
+const sellerAmount = totalAmount - platformFee;
+
+// ... (setup connection, buyer, seller, mint)
+
+const buyerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, buyer);
+const sellerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, seller);
+const treasuryTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, PLATFORM_TREASURY);
+
+// Create the transaction with TWO transfer instructions
+const transaction = new Transaction();
+
+// 1. Transfer to seller
+transaction.add(
+ createTransferInstruction(
+ buyerTokenAccount.address,
+ sellerTokenAccount.address,
+ buyer,
+ sellerAmount
+ )
+);
+
+// 2. Transfer to platform treasury
+transaction.add(
+ createTransferInstruction(
+ buyerTokenAccount.address,
+ treasuryTokenAccount.address,
+ buyer,
+ platformFee
+ )
+);
+
+// ... (set blockhash, feePayer, serialize and send)
+```
+
+## Important Considerations
+* **Rounding:** Be mindful of potential rounding errors when calculating fees. Using integer math with basis points (BPS) is generally safer.
+* **Associated Token Accounts:** Ensure the platform's treasury wallet has an associated token account for each currency you support. The `getOrCreateAssociatedTokenAccount` function helps with this, but the transaction to create it might need to be handled separately or signed by the platform.
diff --git a/docs/monetization/13-subscription-model-database-schema.md b/docs/monetization/13-subscription-model-database-schema.md
new file mode 100644
index 000000000..ed87d4b73
--- /dev/null
+++ b/docs/monetization/13-subscription-model-database-schema.md
@@ -0,0 +1,69 @@
+# Prompt 13: Subscription Model Database Schema
+
+## Objective
+Design and create the necessary database tables to support a subscription-based monetization model for agent skills.
+
+## Explanation
+To move beyond one-time purchases, we need to support subscriptions. This will allow creators to offer bundles of skills for a recurring fee (e.g., monthly). This task focuses on the database design, which is the foundation for the subscription feature. We will need tables to manage subscription plans (tiers), and to track which users are subscribed to which plans.
+
+## Instructions
+1. **Design `agent_subscription_tiers` Table:**
+ * This table will store the different subscription plans a creator can offer for an agent.
+ * It should include columns for the agent it belongs to, a name (e.g., "Pro"), a price, a currency, and a billing interval (e.g., 'month', 'year').
+ * It should also include an array of skill names that are included in this tier.
+
+2. **Design `user_subscriptions` Table:**
+ * This table will track active user subscriptions.
+ * It should link a user to a subscription tier.
+ * It needs columns to manage the subscription's lifecycle, such as `status` (e.g., 'active', 'canceled'), `current_period_start`, and `current_period_end`.
+
+3. **Write SQL Schema:**
+ * Write the `CREATE TABLE` SQL statements for these new tables. Include appropriate foreign keys, constraints, and indexes.
+
+## SQL Schema Definition
+
+```sql
+-- Table to define the subscription plans for an agent
+CREATE TABLE agent_subscription_tiers (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID REFERENCES agents(id) NOT NULL,
+ name TEXT NOT NULL,
+ description TEXT,
+ price_amount BIGINT NOT NULL, -- Price in smallest unit
+ price_currency_mint TEXT NOT NULL,
+ billing_interval TEXT NOT NULL CHECK (billing_interval IN ('month', 'year')), -- e.g., monthly, yearly
+ included_skills TEXT[] NOT NULL, -- An array of skill names included in this tier
+ is_active BOOLEAN DEFAULT TRUE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+
+ UNIQUE(agent_id, name)
+);
+
+-- Table to track which user is subscribed to which tier
+CREATE TABLE user_subscriptions (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID REFERENCES auth.users(id) NOT NULL,
+ tier_id UUID REFERENCES agent_subscription_tiers(id) NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('active', 'canceled', 'past_due')),
+ current_period_start TIMESTAMPTZ NOT NULL,
+ current_period_end TIMESTAMPTZ NOT NULL,
+ cancel_at_period_end BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+
+-- Add indexes for performance
+CREATE INDEX idx_user_subscriptions_user_id ON user_subscriptions(user_id);
+CREATE INDEX idx_user_subscriptions_tier_id ON user_subscriptions(tier_id);
+
+-- RLS Policies
+ALTER TABLE agent_subscription_tiers ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "Creators can manage their own subscription tiers"
+ON agent_subscription_tiers FOR ALL
+USING (auth.uid() = (SELECT creator_id FROM agents WHERE id = agent_id));
+
+ALTER TABLE user_subscriptions ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "Users can view their own subscriptions"
+ON user_subscriptions FOR SELECT
+USING (auth.uid() = user_id);
+```
diff --git a/docs/monetization/14-grant-skill-access.md b/docs/monetization/14-grant-skill-access.md
new file mode 100644
index 000000000..ff3f6560e
--- /dev/null
+++ b/docs/monetization/14-grant-skill-access.md
@@ -0,0 +1,70 @@
+# Prompt 14: Grant Skill Access After Payment
+
+## Objective
+Integrate the logic for creating a `skill_access_grants` record into the payment confirmation flow.
+
+## Explanation
+This prompt links the successful payment confirmation (Prompt 12) with the access grant system (Prompt 13). Once the backend has verified a user's payment on-chain, it must immediately create the corresponding access grant in the database.
+
+## Instructions
+1. **File to Edit:**
+ * Open the backend endpoint for payment confirmation: `POST /api/payments/confirm-skill-payment`.
+
+2. **Integrate Grant Creation:**
+ * Locate the spot in your code immediately after the payment status has been successfully updated to `completed`.
+ * Before sending the final success response to the client, add a call to your database logic to insert a new row into the `skill_access_grants` table.
+
+3. **Determine Grant Rules:**
+ * You need to decide what kind of access this payment provides. For a simple one-time payment model, you could grant access for a fixed duration.
+ * **Example Rule:** Grant access for 24 hours from the time of purchase.
+ * To implement this, calculate the expiry timestamp.
+
+4. **Populate the Grant Record:**
+ * The new `skill_access_grants` row should be populated with:
+ * `user_id`: From the authenticated user session.
+ * `agent_id`, `skill_name`: From the `paymentIntent` record you fetched from the database.
+ * `payment_id`: The ID of the now-completed payment.
+ * `expires_at`: The calculated expiry timestamp (e.g., `Date.now() + 24 * 60 * 60 * 1000`).
+ * `uses_left`: `NULL` for this time-based model.
+
+5. **Transactional Integrity:**
+ * Ideally, the database operations for updating the payment status and creating the access grant should be wrapped in a database transaction. This ensures that either both operations succeed or both fail, preventing a state where a user pays but doesn't get access.
+
+## Code Example (Backend - `confirm-skill-payment` logic)
+
+This refines the example from Prompt 12.
+
+```javascript
+// Inside your /api/payments/confirm-skill-payment endpoint handler
+
+// ... after successfully verifying the on-chain transaction ...
+
+try {
+ // Use a database transaction to ensure atomicity
+ await db.transaction(async (trx) => {
+ // c. Update Payment Status
+ await trx.update('skill_payments', { status: 'completed', signature: signature })
+ .where({ id: paymentId });
+
+ // d. Grant Skill Access
+ const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours from now
+
+ await trx.insert({
+ user_id: user.id,
+ agent_id: paymentIntent.agentId,
+ skill_name: paymentIntent.skillName,
+ payment_id: paymentId,
+ expires_at: expiresAt,
+ uses_left: null, // This is a time-based grant
+ }).into('skill_access_grants');
+ });
+
+ // e. Respond for frontend to continue
+ res.status(200).json({ success: true, message: 'Payment confirmed and access granted.' });
+
+} catch (error) {
+ console.error('Error in confirmation transaction:', error);
+ // The database transaction should automatically roll back on error
+ res.status(500).json({ error: 'Failed to finalize payment.' });
+}
+```
diff --git a/docs/monetization/14-platform-fee.md b/docs/monetization/14-platform-fee.md
new file mode 100644
index 000000000..0dd0d9ecb
--- /dev/null
+++ b/docs/monetization/14-platform-fee.md
@@ -0,0 +1,78 @@
+# Prompt 14: Platform Fee (Backend)
+
+## Objective
+Implement a platform fee on every skill purchase transaction, splitting the payment between the skill creator and the platform's treasury wallet.
+
+## Explanation
+Platform fees are a standard monetization strategy. This task involves modifying the transaction creation logic to calculate a fee (e.g., 5%) and adding a second transfer instruction to the transaction. This ensures that a portion of every sale is automatically sent to the platform.
+
+## Instructions
+1. **Define Platform Wallet and Fee Rate:**
+ * In your backend configuration (e.g., environment variables), define your platform's Solana wallet address (`PLATFORM_WALLET_ADDRESS`) and the fee percentage (`PLATFORM_FEE_BPS`, in basis points, e.g., 500 for 5%).
+
+2. **Update the Payment Endpoint (`api/payments/prepare-skill-purchase.js`):**
+ * Inside the handler, after fetching the skill price:
+ * Calculate the platform fee from the total amount. Be careful with integer division and rounding; it's best to work with `BigInt` for token amounts to avoid precision errors.
+ * Calculate the amount the creator will receive (total amount - platform fee).
+ * Create two `createTransferInstruction` calls:
+ 1. One instruction to transfer the creator's portion to their payout wallet.
+ 2. A second instruction to transfer the platform fee to the platform's wallet.
+ * Add both transfer instructions to the same `Transaction` object.
+
+3. **Atomicity:**
+ * Because both transfers are part of the same transaction, the operation is atomic. If any part of it fails, the entire transaction (both the payment to the creator and the fee to the platform) will fail, ensuring consistency.
+
+## Code Example (Backend - `api/payments/prepare-skill-purchase.js`)
+
+```javascript
+// ... (imports)
+
+const PLATFORM_WALLET = new PublicKey(process.env.PLATFORM_WALLET_ADDRESS);
+// Fee in basis points (100 bps = 1%)
+const PLATFORM_FEE_BPS = BigInt(process.env.PLATFORM_FEE_BPS || 500);
+
+export default async function handler(req, res) {
+ // ... (handler setup)
+ try {
+ // ... (get buyer, creator wallet, price info)
+
+ const transaction = new Transaction({ /* ... */ });
+ const buyerUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, buyerPublicKey);
+ const creatorUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, creatorPublicKey);
+ const platformUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, PLATFORM_WALLET);
+
+ const totalAmount = BigInt(priceInfo.amount);
+
+ // Calculate fees using BigInt for precision
+ const platformFee = (totalAmount * PLATFORM_FEE_BPS) / 10000n;
+ const creatorAmount = totalAmount - platformFee;
+
+ // Instruction 1: Transfer to creator
+ transaction.add(
+ createTransferInstruction(
+ buyerUsdcAddress,
+ creatorUsdcAddress,
+ buyerPublicKey,
+ creatorAmount // Use BigInt amount
+ )
+ );
+
+ // Instruction 2: Transfer platform fee
+ if (platformFee > 0) {
+ transaction.add(
+ createTransferInstruction(
+ buyerUsdcAddress,
+ platformUsdcAddress,
+ buyerPublicKey,
+ platformFee // Use BigInt amount
+ )
+ );
+ }
+
+ // ... (serialize and return transaction)
+
+ } catch (error) {
+ // ... (error handling)
+ }
+}
+```
diff --git a/docs/monetization/14-ui-for-subscription-tiers.md b/docs/monetization/14-ui-for-subscription-tiers.md
new file mode 100644
index 000000000..dd4a2a3e0
--- /dev/null
+++ b/docs/monetization/14-ui-for-subscription-tiers.md
@@ -0,0 +1,90 @@
+# Prompt 14: UI for Subscription Tiers
+
+## Objective
+Implement the UI in the creator's dashboard that allows them to create, view, and manage subscription tiers for their agents.
+
+## Explanation
+Building on the subscription database schema, we now need a user interface for creators. This UI will live in the "Monetization" tab and will provide a form to define a new subscription tier (name, price, included skills) and a list to display existing tiers.
+
+## Instructions
+1. **Add UI Structure:**
+ * In `agent-edit.html`, within the "Monetization" tab panel, add a new section for "Subscription Tiers".
+ * This section should contain a button "Create New Tier" which reveals a form.
+ * Also, include a container to list the existing tiers, e.g., `#subscription-tiers-list`.
+
+2. **Create Tier Form:**
+ * The form should have inputs for tier `name`, `description`, `price`, `currency`, and `billing interval` (monthly/yearly).
+ * A crucial part will be a multi-select box or a list of checkboxes for the creator to choose which of the agent's skills are included in this tier.
+
+3. **Frontend Logic:**
+ * In `src/agent-edit.js`, write a function to fetch the agent's skills and existing subscription tiers.
+ * Populate the skills multi-select in the form.
+ * Render the list of existing tiers with an "Edit" or "Deactivate" button for each.
+ * Handle the form submission to collect the data for a new tier, which will be sent to the backend (to be created in the next prompt).
+
+## HTML Example (`agent-edit.html`)
+
+```html
+<!-- Inside the 'monetization' tab-content -->
+<div class="card">
+ <h3>Subscription Tiers</h3>
+ <div id="subscription-tiers-list">
+ <!-- Existing tiers will be rendered here -->
+ </div>
+ <button id="show-create-tier-form-btn">Create New Tier</button>
+ <div id="create-tier-form-container" style="display:none;">
+ <h4>New Subscription Tier</h4>
+ <div class="form-field">
+ <label for="tier-name">Tier Name</label>
+ <input type="text" id="tier-name" placeholder="e.g., Pro">
+ </div>
+ <div class="form-field">
+ <label for="tier-price">Price</label>
+ <input type="number" id="tier-price" placeholder="9.99">
+ <select id="tier-currency">
+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d">USDC</option>
+ </select>
+ <select id="tier-interval">
+ <option value="month">per month</option>
+ <option value="year">per year</option>
+ </select>
+ </div>
+ <div class="form-field">
+ <label>Included Skills</label>
+ <div id="tier-skills-checklist">
+ <!-- Checkboxes for skills will be rendered here -->
+ </div>
+ </div>
+ <button id="save-tier-btn">Save Tier</button>
+ <button id="cancel-create-tier-btn" type="button">Cancel</button>
+ </div>
+</div>
+```
+
+## JavaScript Example (`src/agent-edit.js`)
+
+```javascript
+const showCreateTierBtn = document.getElementById('show-create-tier-form-btn');
+const createTierContainer = document.getElementById('create-tier-form-container');
+const saveTierBtn = document.getElementById('save-tier-btn');
+
+showCreateTierBtn.addEventListener('click', () => {
+ createTierContainer.style.display = 'block';
+ showCreateTierBtn.style.display = 'none';
+ populateSkillsForTierForm(); // a function that fetches and renders skills as checkboxes
+});
+
+saveTierBtn.addEventListener('click', async () => {
+ const tierData = {
+ name: document.getElementById('tier-name').value,
+ price_amount: Math.round(parseFloat(document.getElementById('tier-price').value) * 1e6),
+ price_currency_mint: document.getElementById('tier-currency').value,
+ billing_interval: document.getElementById('tier-interval').value,
+ included_skills: Array.from(document.querySelectorAll('#tier-skills-checklist input:checked')).map(cb => cb.value)
+ };
+
+ const agentId = /* get agent id from context */;
+ // Backend call will be implemented next
+ await createSubscriptionTier(agentId, tierData);
+});
+```
diff --git a/docs/monetization/15-backend-check-active-grant.md b/docs/monetization/15-backend-check-active-grant.md
new file mode 100644
index 000000000..26e94ad66
--- /dev/null
+++ b/docs/monetization/15-backend-check-active-grant.md
@@ -0,0 +1,68 @@
+# Prompt 15: Backend Logic to Check for Active Grant
+
+## Objective
+Flesh out the database query and logic for checking if a user has a valid, active grant for a specific skill before execution.
+
+## Explanation
+This prompt focuses on completing the check designed in Prompt 8. With the `skill_access_grants` table now defined, we can write the precise database query that powers the access check. This logic is the gatekeeper for all paid skills.
+
+## Instructions
+1. **File to Edit:**
+ * Open your backend chat orchestrator (e.g., `/api/chat.js`) where the initial paid skill detection happens.
+
+2. **Create a Database Query Function:**
+ * In your database access layer, create a function like `checkForValidSkillGrant({ userId, agentId, skillName })`.
+
+3. **Implement the Query Logic:**
+ * This function needs to query the `skill_access_grants` table.
+ * The `WHERE` clause is the most important part. It should find a row where:
+ * `user_id`, `agent_id`, and `skill_name` all match the function's arguments.
+ * **AND** the grant is not expired. This requires a sub-clause: `(expires_at IS NULL OR expires_at > NOW())`.
+ * **AND** the grant has uses remaining: `(uses_left IS NULL OR uses_left > 0)`.
+ * You only need to know if *any* such grant exists, so you can optimize the query to return just one row or a simple count (`SELECT 1` or `SELECT COUNT(*)`). The function should return `true` if a valid grant is found, and `false` otherwise.
+
+4. **Decrement `uses_left` (for pay-per-use skills):**
+ * If a grant is found that relies on `uses_left` (i.e., `expires_at` is `NULL`), you must decrement the `uses_left` count in the database as part of this check.
+ * This should be an atomic `UPDATE` operation: `UPDATE skill_access_grants SET uses_left = uses_left - 1 WHERE id = ...`.
+ * This decrement should happen within a transaction to avoid race conditions.
+
+## Code Example (Backend - Database Access Layer)
+
+```javascript
+// Example using a SQL query builder like Knex.js
+
+async function checkForValidSkillGrant({ userId, agentId, skillName }) {
+ // Find a grant that is either time-based and not expired, or use-based and has uses left.
+ const grants = await db('skill_access_grants')
+ .where({
+ user_id: userId,
+ agent_id: agentId,
+ skill_name: skillName,
+ })
+ .where(builder => {
+ builder.where(q => {
+ q.whereNotNull('expires_at').andWhere('expires_at', '>', db.fn.now());
+ }).orWhere(q => {
+ q.whereNotNull('uses_left').andWhere('uses_left', '>', 0);
+ })
+ })
+ .select('id', 'uses_left')
+ .limit(1);
+
+ if (grants.length === 0) {
+ return false; // No valid grant found
+ }
+
+ const grant = grants[0];
+
+ // If this was a use-based grant, decrement the count.
+ if (grant.uses_left !== null && grant.uses_left > 0) {
+ await db('skill_access_grants')
+ .where({ id: grant.id })
+ .decrement('uses_left', 1);
+ }
+
+ return true; // Grant is valid
+}
+```
+This function would then be called from your chat handler as shown in Prompt 8.
diff --git a/docs/monetization/15-transaction-history.md b/docs/monetization/15-transaction-history.md
new file mode 100644
index 000000000..fb1b21570
--- /dev/null
+++ b/docs/monetization/15-transaction-history.md
@@ -0,0 +1,72 @@
+# Prompt 15: Transaction History
+
+## Objective
+Create a transaction history page or dashboard section for both users (buyers) and creators (sellers) to view past transactions.
+
+## Explanation
+Transparency is key for any platform dealing with payments. Users should be able to see a clear record of their purchases, and creators should be able to track their sales. This task involves creating a new database table to log transactions and building the UI and API to display this history.
+
+## Instructions
+1. **Database Schema:**
+ * Create a `transactions` table to log every purchase.
+ * Columns should include: `id`, `buyer_user_id`, `creator_user_id`, `agent_id`, `skill_name`, `amount`, `platform_fee`, `currency_mint`, `signature`, and `created_at`.
+
+2. **Log Transactions (Backend):**
+ * In your payment confirmation logic (`api/payments/prepare-skill-purchase.js` `GET` handler), after verifying the transaction and granting skill access, insert a new record into this `transactions` table.
+
+3. **Create API Endpoint(s) (Backend):**
+ * Create an endpoint `/api/users/me/transaction-history` that returns transactions where the user is either the `buyer_user_id` or the `creator_user_id`.
+ * You could add a query parameter `?role=buyer` or `?role=seller` to filter the results.
+
+4. **Build the UI (Frontend):**
+ * In the user's dashboard, create a new "Transaction History" tab or section.
+ * Fetch data from the new endpoint.
+ * Display the transactions in a table or list format.
+ * The view should clearly distinguish between sales and purchases. For each transaction, show details like date, item, amount, role (Buyer/Seller), and a link to the transaction on a block explorer like Solscan.
+
+## Code Example (Backend - Logging the transaction)
+
+```javascript
+// Inside the payment confirmation (GET handler) after successful verification
+
+// ...
+await grantSkillToUser(purchaseDetails.userId, purchaseDetails.skillName);
+
+// Now, log the transaction
+await logTransaction({
+ buyerUserId: purchaseDetails.userId,
+ creatorUserId: purchaseDetails.creatorId, // You need to fetch/store this
+ agentId: purchaseDetails.agentId,
+ skillName: purchaseDetails.skillName,
+ amount: purchaseDetails.amount,
+ platformFee: calculatedPlatformFee,
+ currencyMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d',
+ signature: req.query.signature
+});
+
+res.status(200).json({ status: 'ok', message: 'Purchase confirmed!' });
+```
+
+## UI Table Example (`dashboard.html`)
+
+```html
+<section>
+ <h2>Transaction History</h2>
+ <div class="table-wrapper">
+ <table>
+ <thead>
+ <tr>
+ <th>Date</th>
+ <th>Type</th>
+ <th>Details</th>
+ <th>Amount</th>
+ <th>Tx</th>
+ </tr>
+ </thead>
+ <tbody id="transaction-history-body">
+ <!-- Rows will be injected here -->
+ </tbody>
+ </table>
+ </div>
+</section>
+```
diff --git a/docs/monetization/16-integrate-skills-with-chat.md b/docs/monetization/16-integrate-skills-with-chat.md
new file mode 100644
index 000000000..fa039dbb4
--- /dev/null
+++ b/docs/monetization/16-integrate-skills-with-chat.md
@@ -0,0 +1,76 @@
+# Prompt 16: Integrate Owned Skills with Agent Chat
+
+## Objective
+Modify the agent chat backend to check if a user owns the required skill before allowing the execution of a premium agent capability.
+
+## Explanation
+Monetization is only effective if owning a skill actually unlocks functionality. This task connects the ownership record to the agent's core logic. When an agent is about to perform an action tied to a paid skill, it must first verify that the interacting user has purchased that skill.
+
+## Instructions
+1. **Map Agent Actions to Skills (Backend):**
+ * You need a way to associate specific agent behaviors with skill names. This could be done in your agent's configuration or a database table. For example, a `run_market_analysis` action might require the `MarketAnalysis` skill.
+
+2. **Create a Skill Check Middleware/Function (Backend):**
+ * In your chat API (`api/chat.js` or similar), create a function `checkSkillOwnership(userId, agentId, requiredSkill)`.
+ * This function will query the `user_skill_ownership` table to see if a record exists for the given user, agent, and skill.
+ * It should return `true` or `false`.
+
+3. **Enforce the Check (Backend):**
+ * In your main chat message handler, before executing a premium action:
+ * Identify the skill required for the action.
+ * Call your `checkSkillOwnership` function.
+ * If the check fails, do not execute the action. Instead, return a specific response to the frontend indicating the required skill is not owned.
+
+## Code Example (Backend - Chat API)
+
+```javascript
+import { checkSkillOwnership } from '../_lib/db'; // Your new DB function
+import { getSkillForAction } from '../_lib/agent-config'; // Function to map action to skill
+
+export default async function handler(req, res) {
+ // ... (chat handler setup, get user message and user id)
+ const userId = req.user.id;
+ const { agentId, message } = req.body;
+
+ // 1. Determine the agent's intended action based on the message
+ const action = determineAgentAction(message);
+
+ // 2. Look up the skill required for this action
+ const requiredSkill = getSkillForAction(agentId, action);
+
+ if (requiredSkill) {
+ // 3. This is a premium action, so check for ownership
+ const hasSkill = await checkSkillOwnership(userId, agentId, requiredSkill);
+
+ if (!hasSkill) {
+ // 4. If user doesn't own it, send a specific response
+ return res.status(402).json({ // 402 Payment Required
+ type: 'skill_required',
+ message: `This action requires the "${requiredSkill}" skill. Please purchase it from the marketplace to continue.`,
+ skillName: requiredSkill,
+ });
+ }
+ }
+
+ // If we reach here, the user either has the skill or the action is free.
+ // Proceed with executing the agent's action.
+ const agentResponse = await executeAgentAction(agentId, action, message);
+
+ res.status(200).json({ response: agentResponse });
+}
+```
+
+## Database Function (`_lib/db.js`)
+
+```javascript
+export async function checkSkillOwnership(userId, agentId, skillName) {
+ const { rowCount } = await db.query(
+ `
+ SELECT 1 FROM user_skill_ownership
+ WHERE user_id = $1 AND agent_id = $2 AND skill_name = $3;
+ `,
+ [userId, agentId, skillName]
+ );
+ return rowCount > 0;
+}
+```
diff --git a/docs/monetization/16-update-chat-ui-purchased.md b/docs/monetization/16-update-chat-ui-purchased.md
new file mode 100644
index 000000000..55abe9c65
--- /dev/null
+++ b/docs/monetization/16-update-chat-ui-purchased.md
@@ -0,0 +1,86 @@
+# Prompt 16: Update Chat UI for Purchased Skills
+
+## Objective
+Modify the chat UI to visually reflect when a user has purchased access to a premium skill, for example by changing an icon from a "lock" to an "unlock" state.
+
+## Explanation
+After a successful purchase, the user needs immediate visual feedback that their action was successful and the skill is now available. This improves user experience and reduces confusion.
+
+## Instructions
+1. **Modify the Chat UI Component:**
+ * Open your main chat component file (e.g., `chat/src/App.svelte`).
+ * The component needs to maintain a state of which skills the user has purchased access to for the current agent. This could be a `Set` or an `object`.
+ ```javascript
+ let purchasedSkills = new Set();
+ ```
+
+2. **Update State After Purchase:**
+ * In your `handlePaymentFlow` function from Prompt 11, upon successful confirmation from the backend, add the `skill_name` to your `purchasedSkills` set.
+ ```javascript
+ // Inside handlePaymentFlow, after successful confirmation
+ purchasedSkills.add(paymentDetails.skill_name);
+ purchasedSkills = purchasedSkills; // Trigger Svelte reactivity
+ ```
+
+3. **Initial State Loading:**
+ * When a chat session starts, you should ideally fetch the user's current access grants for the agent from the backend so that previously purchased skills are already shown as unlocked.
+ * Create a new, simple backend endpoint `GET /api/agents/:id/my-skill-grants` that returns a list of skill names for which the current user has active grants.
+ * Call this endpoint when the chat loads and populate the `purchasedSkills` set.
+
+4. **Dynamically Render Skill UI:**
+ * Locate the part of your UI that displays available skills (perhaps in a sidebar or as suggestion chips).
+ * When rendering each skill, check if its name is in the `purchasedSkills` set.
+ * Use this check to conditionally apply a class or show a different icon.
+
+## Code Example (Frontend - Svelte Component)
+
+```svelte
+<!-- Example of rendering a list of skills in the chat UI -->
+<div class="skill-list">
+ <h4>Available Skills</h4>
+ {#each agent.skills as skill}
+ {@const isLocked = skill.is_premium && !purchasedSkills.has(skill.name)}
+ <div class="skill-chip" class:locked={isLocked}>
+ {skill.name}
+ {#if isLocked}
+ <span>🔒</span>
+ {:else if skill.is_premium}
+ <span>✔️</span>
+ {/if}
+ </div>
+ {/each}
+</div>
+
+<script>
+ // ... existing script ...
+ export let agent;
+ let purchasedSkills = new Set();
+
+ // Fetch initial grants on component mount
+ import { onMount } from 'svelte';
+ onMount(async () => {
+ const res = await fetch(`/api/agents/${agent.id}/my-skill-grants`);
+ if (res.ok) {
+ const { granted_skills } = await res.json();
+ purchasedSkills = new Set(granted_skills);
+ }
+ });
+
+ // This function is called after a successful payment flow
+ function onSkillPurchased(skillName) {
+ purchasedSkills.add(skillName);
+ purchasedSkills = purchasedSkills; // This forces Svelte to update the UI
+ }
+</script>
+
+<style>
+ .skill-chip.locked {
+ opacity: 0.6;
+ cursor: not-allowed;
+ background-color: #333;
+ }
+ .skill-chip span {
+ margin-left: 8px;
+ }
+</style>
+```
diff --git a/docs/monetization/16-user-subscription-flow.md b/docs/monetization/16-user-subscription-flow.md
new file mode 100644
index 000000000..1a6a36a74
--- /dev/null
+++ b/docs/monetization/16-user-subscription-flow.md
@@ -0,0 +1,82 @@
+# Prompt 16: User Subscription Flow
+
+## Objective
+Implement the frontend and backend logic for users to subscribe to an agent's subscription tier.
+
+## Explanation
+This task combines previous concepts (wallet connection, transaction creation, verification) into a subscription context. The user will select a subscription tier, approve a transaction for the first payment, and the backend will create a record in the `user_subscriptions` table to mark the subscription as active. This prompt will not cover recurring payments, but will set up the initial subscription.
+
+## Instructions
+1. **Update Marketplace UI:**
+ * In `src/marketplace.js`, when rendering the agent detail page, fetch and display the available subscription tiers.
+ * Each tier should have a "Subscribe" button.
+
+2. **Subscription Confirmation Modal:**
+ * Clicking "Subscribe" should open a confirmation modal, similar to the one-time purchase, showing the tier name, price, and billing cycle.
+
+3. **Backend Subscription Endpoint:**
+ * Create an endpoint `/api/subscriptions/subscribe`.
+ * It takes `tierId` and the user's public key.
+ * It constructs and returns a transaction for the first payment, just like the one-time purchase.
+
+4. **Frontend Transaction Handling:**
+ * The frontend gets the transaction, has the user sign and send it.
+
+5. **Backend Verification and Activation Endpoint:**
+ * Create an endpoint `/api/subscriptions/verify`.
+ * It takes a `transactionSignature` and `tierId`.
+ * It verifies the transaction on-chain.
+ * If valid, it creates a new record in the `user_subscriptions` table with a status of 'active'. It calculates `current_period_start` (now) and `current_period_end` (e.g., now + 1 month).
+
+## Code Example (`api/subscriptions/verify.js`)
+
+```javascript
+import { supabase } from '../../_lib/supabase';
+import { json, error } from '../../_lib/http';
+import { getAuthUser } from '../../_lib/auth';
+
+export default async function handler(req, res) {
+ const { transactionSignature, tierId } = req.body;
+ const user = await getAuthUser(req);
+
+ if (!user) return error(res, 401, 'Unauthorized');
+
+ // 1. Verify transaction on-chain (similar to prompt #6)
+ const isTxValid = await verifySubscriptionPayment(transactionSignature, tierId, user.id);
+ if (!isTxValid) {
+ return error(res, 400, 'Invalid transaction.');
+ }
+
+ // 2. Get tier details to calculate the period end
+ const { data: tier } = await supabase.from('agent_subscription_tiers').select('billing_interval').eq('id', tierId).single();
+ if (!tier) {
+ return error(res, 404, 'Subscription tier not found.');
+ }
+
+ // 3. Create the subscription record
+ const startDate = new Date();
+ const endDate = new Date(startDate);
+ if (tier.billing_interval === 'month') {
+ endDate.setMonth(startDate.getMonth() + 1);
+ } else if (tier.billing_interval === 'year') {
+ endDate.setFullYear(startDate.getFullYear() + 1);
+ }
+
+ const { error: insertError } = await supabase
+ .from('user_subscriptions')
+ .insert({
+ user_id: user.id,
+ tier_id: tierId,
+ status: 'active',
+ current_period_start: startDate.toISOString(),
+ current_period_end: endDate.toISOString(),
+ // `transaction_signature` might be stored on a related `payments` table
+ });
+
+ if (insertError) {
+ return error(res, 500, 'Failed to activate subscription.');
+ }
+
+ return json(res, { success: true, message: 'Subscription activated!' });
+}
+```
diff --git a/docs/monetization/16_refactor_service_class.md b/docs/monetization/16_refactor_service_class.md
new file mode 100644
index 000000000..a96458ccf
--- /dev/null
+++ b/docs/monetization/16_refactor_service_class.md
@@ -0,0 +1,91 @@
+---
+status: not-started
+last_updated: 2026-05-04
+---
+# Prompt 16: Refactor Monetization Logic into a Service Class
+
+## Objective
+To improve code organization and reusability, refactor the scattered monetization logic (database queries, transaction building) into a dedicated `MonetizationService` class.
+
+## Explanation
+As the monetization feature grows, the logic becomes more complex. Keeping it directly inside API handlers makes it hard to maintain, test, and reuse. A service class will encapsulate all the business logic related to skill pricing, purchases, and payouts, providing a clean interface for the API layer.
+
+## Instructions
+1. **Create a New Service File:**
+ * Create a file at `api/_lib/services/MonetizationService.js`.
+
+2. **Design the `MonetizationService` Class:**
+ * The constructor can take a database connection object (`sql`) and the current user's session as arguments.
+ * Create methods that map to the core operations we've built:
+ * `getSkillPricesForAgent(agentId)`
+ * `setSkillPrices(agentId, prices)`
+ * `preparePurchaseTransaction(agentId, skillName)`
+ * `confirmPurchase(agentId, skillName, signature)`
+ * `checkSkillOwnership(agentId, skillName)`
+ * `getCreatorSalesData()`
+
+3. **Migrate Logic into the Service:**
+ * Move the database queries and transaction-building logic from the API handlers (`api/marketplace/[action].js`, `api/skills/purchase-prep.js`, etc.) into the corresponding methods of the new service class.
+ * The API handlers should become much thinner; their primary role will be handling HTTP requests/responses, validating input, and calling the service methods.
+
+4. **Refactor API Handlers:**
+ * Update all relevant API handlers to instantiate and use the `MonetizationService`.
+
+## Code Example (`MonetizationService.js`)
+
+```javascript
+import { sql } from '../db.js';
+import { Connection, ... } from '@solana/web3.js';
+// ... other imports
+
+export class MonetizationService {
+ constructor(user) {
+ this.user = user;
+ }
+
+ async setSkillPrices(agentId, prices) {
+ if (!this.user) throw new Error('Authentication required.');
+
+ // Verify ownership
+ const [agent] = await sql`...`;
+ if (!agent) throw new Error('Agent not found or permission denied.');
+
+ // Perform the database upsert logic here...
+ }
+
+ async preparePurchaseTransaction(agentId, skillName) {
+ if (!this.user) throw new Error('Authentication required.');
+
+ // All the logic for fetching prices, wallets, and building
+ // the VersionedTransaction goes here...
+ // Returns the serialized transaction.
+ }
+
+ // ... other methods
+}
+```
+
+## Code Example (Refactored API Handler)
+
+```javascript
+// api/skills/purchase-prep.js
+import { MonetizationService } from '../../_lib/services/MonetizationService.js';
+// ...
+
+export default wrap(async (req, res) => {
+ const user = await getSessionUser(req);
+ // ... input validation
+
+ try {
+ const monetizationService = new MonetizationService(user);
+ const { transaction } = await monetizationService.preparePurchaseTransaction(
+ req.body.agent_id,
+ req.body.skill_name
+ );
+ return json(res, 200, { transaction });
+ } catch (e) {
+ // Handle specific errors from the service for better status codes
+ return error(res, 500, 'prep_failed', e.message);
+ }
+});
+```
diff --git a/docs/monetization/17-access-control-for-skills.md b/docs/monetization/17-access-control-for-skills.md
new file mode 100644
index 000000000..d21e09f64
--- /dev/null
+++ b/docs/monetization/17-access-control-for-skills.md
@@ -0,0 +1,79 @@
+# Prompt 17: Access Control for Skills
+
+## Objective
+Implement a robust access control layer on the backend to check if a user is permitted to use a specific skill before execution.
+
+## Explanation
+Now that users can buy skills or subscribe to tiers, we need to enforce access. Before executing any skill via the API, the backend must check if the skill is free or, if it's paid, whether the user has the right to use it. This is a critical security measure to protect creators' intellectual property.
+
+## Instructions
+1. **Create an Access Control Middleware/Function:**
+ * It's best to centralize this logic. Create a helper function, e.g., `hasSkillAccess(userId, agentId, skillName)`.
+
+2. **Implement Access Logic:**
+ * The `hasSkillAccess` function will perform the following checks in order:
+ 1. Check if the skill is priced in `agent_skill_prices`. If not, it's a free skill, so return `true`.
+ 2. If the skill is priced, check if the user has a one-time purchase record for it in `user_purchased_skills`. If yes, return `true`.
+ 3. If not purchased individually, check if the user has an active subscription (`user_subscriptions` table).
+ 4. If they have a subscription, check if the `skillName` is in the `included_skills` array of their subscribed `agent_subscription_tiers`. If yes, return `true`.
+ 5. If none of the above are true, return `false`.
+
+3. **Integrate into Skill Execution Endpoint:**
+ * Locate the main API endpoint responsible for executing agent skills (e.g., `/api/chat` or `/api/agent-actions.js`).
+ * Before running the skill logic, call your new `hasSkillAccess` function.
+ * If it returns `false`, the endpoint should immediately stop and return a 403 Forbidden error with a message like "You do not have access to this skill. Please purchase it from the marketplace."
+
+## Code Example (Access Control Logic)
+
+```javascript
+// In a helper file, e.g., /api/_lib/access-control.js
+import { supabase } from './supabase';
+
+export async function hasSkillAccess(userId, agentId, skillName) {
+ // 1. Check if the skill is free
+ const { data: price, error: priceError } = await supabase
+ .from('agent_skill_prices')
+ .select('amount')
+ .eq('agent_id', agentId)
+ .eq('skill_name', skillName)
+ .single();
+
+ // If there's no price entry, it's considered free
+ if (!price) return true;
+
+ // User must be logged in to access priced skills
+ if (!userId) return false;
+
+ // 2. Check for a one-time purchase
+ const { data: purchase, error: purchaseError } = await supabase
+ .from('user_purchased_skills')
+ .select('id')
+ .eq('user_id', userId)
+ .eq('agent_id', agentId)
+ .eq('skill_name', skillName)
+ .single();
+
+ if (purchase) return true;
+
+ // 3. Check for an active subscription that includes this skill
+ const { data: subscription, error: subError } = await supabase
+ .from('user_subscriptions')
+ .select(`
+ status,
+ agent_subscription_tiers ( included_skills )
+ `)
+ .eq('user_id', userId)
+ .eq('status', 'active')
+ // We need to join through tiers to filter by agent
+ // This query is simplified; a real one might need an RPC function
+ // or a more complex join to link user_subscriptions -> tiers -> agents.
+ .single(); // Assuming one active sub per user/agent for now
+
+ if (subscription && subscription.agent_subscription_tiers.included_skills.includes(skillName)) {
+ return true;
+ }
+
+ // 4. If all checks fail
+ return false;
+}
+```
diff --git a/docs/monetization/17-creator-dashboard-tab.md b/docs/monetization/17-creator-dashboard-tab.md
new file mode 100644
index 000000000..c5d689488
--- /dev/null
+++ b/docs/monetization/17-creator-dashboard-tab.md
@@ -0,0 +1,97 @@
+# Prompt 17: Creator Dashboard Monetization Tab
+
+## Objective
+Create a new "Earnings" or "Monetization" tab in the agent creator's dashboard to serve as the central hub for managing paid skills and tracking revenue.
+
+## Explanation
+Creators need a dedicated space to view their sales performance, manage their payout settings, and see which of their skills are generating revenue. This prompt establishes the foundation for that space.
+
+## Instructions
+1. **Identify Dashboard File:**
+ * Find the main file for the creator dashboard. This might be a file like `dashboard.html` or a route within a frontend framework. The file `agent-edit.html` has tabs, so it's a good candidate for adding a new one.
+
+2. **Add a New Tab:**
+ * Add a new "Earnings" tab to the tab list in `agent-edit.html`.
+ * Create the corresponding panel `div` that will be shown when the tab is active.
+ ```html
+ <!-- In the tab list -->
+ <button class="edit-tab" data-tab="earnings" role="tab">Earnings</button>
+
+ <!-- In the main content area -->
+ <section class="edit-panel" id="panel-earnings" role="tabpanel" hidden>
+ <!-- Content for the earnings panel will go here -->
+ </section>
+ ```
+
+3. **Basic Panel Structure:**
+ * Inside the `#panel-earnings` div, create the initial layout. This should include:
+ * A "Summary" section to display key metrics like "Total Revenue," "Platform Fees," and "Net Earnings."
+ * A "Recent Sales" section that will eventually contain a table or list of the latest skill purchases.
+ * A "Payouts" section for managing withdrawal settings and viewing payout history.
+
+4. **Backend Data Endpoint:**
+ * Create a new backend endpoint, e.g., `GET /api/dashboard/earnings`, that is authenticated for the current user.
+ * This endpoint should gather and return all the necessary data for this page:
+ * Aggregated earnings stats (total revenue, etc.).
+ * A list of the 10 most recent sales transactions.
+ * The creator's current payout wallet settings.
+
+5. **Frontend JavaScript:**
+ * In the JavaScript for `agent-edit.html`, add logic to handle the new "Earnings" tab.
+ * When the tab is clicked for the first time, make a call to the new `/api/dashboard/earnings` endpoint.
+ * Use the returned data to populate the sections you created in the HTML. For now, you can just display the raw data or simple placeholders.
+
+## Code Example (Frontend - `agent-edit.html`)
+
+```html
+<!-- Inside the #panel-earnings section -->
+<div class="earnings-summary">
+ <div class="summary-card">
+ <span class="label">Total Revenue</span>
+ <span class="value" id="earnings-total-revenue">$0.00</span>
+ </div>
+ <div class="summary-card">
+ <span class="label">Net Earnings</span>
+ <span class="value" id="earnings-net">$0.00</span>
+ </div>
+ <div class="summary-card">
+ <span class="label">Withdrawable</span>
+ <span class="value" id="earnings-withdrawable">$0.00</span>
+ </div>
+</div>
+
+<h3>Recent Sales</h3>
+<div id="earnings-recent-sales">
+ <p>No sales yet.</p>
+</div>
+
+<h3>Payout Settings</h3>
+<div id="earnings-payouts">
+ <!-- Payout UI will go here, from a later prompt -->
+</div>
+```
+
+```javascript
+// In the script for agent-edit.html
+
+let earningsDataLoaded = false;
+function initEarningsTab() {
+ if (earningsDataLoaded) return;
+
+ fetch('/api/dashboard/earnings')
+ .then(res => res.json())
+ .then(data => {
+ document.getElementById('earnings-total-revenue').textContent = formatCurrency(data.summary.total_revenue);
+ document.getElementById('earnings-net').textContent = formatCurrency(data.summary.net_earnings);
+ document.getElementById('earnings-withdrawable').textContent = formatCurrency(data.summary.withdrawable);
+
+ renderRecentSales(data.recent_sales);
+ earningsDataLoaded = true;
+ })
+ .catch(err => {
+ document.getElementById('panel-earnings').innerHTML = '<p class="error">Could not load earnings data.</p>';
+ });
+}
+
+// In your tab switching logic, call initEarningsTab() when the 'earnings' tab is activated.
+```
diff --git a/docs/monetization/17-ui-for-insufficient-skills.md b/docs/monetization/17-ui-for-insufficient-skills.md
new file mode 100644
index 000000000..158f1dbfb
--- /dev/null
+++ b/docs/monetization/17-ui-for-insufficient-skills.md
@@ -0,0 +1,87 @@
+# Prompt 17: UI for Insufficient Skills
+
+## Objective
+Create a user interface in the chat window that gracefully handles cases where the user tries to use a premium skill they don't own, and prompts them to purchase it.
+
+## Explanation
+When the backend blocks an action due to a missing skill (from the previous prompt), the frontend needs to interpret this specific response and present a clear call-to-action to the user. Instead of a generic error, we should guide them directly to the marketplace to acquire the needed skill.
+
+## Instructions
+1. **Handle the Specific API Response (Frontend):**
+ * In your frontend chat logic, when you make a request to the chat API, check the response status code.
+ * If you receive a `402 Payment Required` status, you know it's a skill-related issue.
+ * Read the JSON body of the response, which will contain the `skillName` and the message.
+
+2. **Render a Special Chat Bubble:**
+ * Instead of rendering a normal error message, create a new type of chat bubble.
+ * This bubble should display the message from the API (e.g., "This action requires the 'MarketAnalysis' skill.").
+ * Crucially, it must include a button or link that says "Purchase Skill" or "Unlock in Marketplace".
+ * This button should link directly to the agent's detail page in the marketplace, possibly with a query parameter to highlight the required skill (e.g., `/marketplace/agent/<agent_id>?highlight_skill=MarketAnalysis`).
+
+## Code Example (Frontend - `src/chat.js`)
+
+```javascript
+async function sendMessage(messageText) {
+ const chatHistory = document.getElementById('chat-history');
+
+ try {
+ const response = await fetch('/api/chat', { /* ... POST data ... */ });
+
+ if (!response.ok) {
+ if (response.status === 402) {
+ // This is our special case for a required skill
+ const data = await response.json();
+ renderPurchasePrompt(data);
+ } else {
+ // Handle other server errors
+ throw new Error(`Server error: ${response.status}`);
+ }
+ return;
+ }
+
+ const data = await response.json();
+ renderAgentMessage(data.response);
+
+ } catch (error) {
+ renderErrorMessage(error.message);
+ }
+}
+
+function renderPurchasePrompt(data) {
+ const chatHistory = document.getElementById('chat-history');
+ const agentId = getCurrentAgentId(); // Helper to get the current agent's ID
+
+ const bubble = document.createElement('div');
+ bubble.className = 'chat-bubble agent-bubble purchase-prompt';
+ bubble.innerHTML = `
+ <p>${escapeHtml(data.message)}</p>
+ <a
+ href="/marketplace/agent/${agentId}?highlight_skill=${encodeURIComponent(data.skillName)}"
+ class="purchase-prompt-btn"
+ >
+ Unlock Skill
+ </a>
+ `;
+ chatHistory.appendChild(bubble);
+}
+```
+
+## CSS for the Prompt Bubble
+
+```css
+.purchase-prompt {
+ background-color: rgba(253, 224, 71, 0.1);
+ border: 1px solid rgba(253, 224, 71, 0.3);
+}
+
+.purchase-prompt-btn {
+ display: inline-block;
+ margin-top: 10px;
+ padding: 8px 16px;
+ background-color: var(--accent);
+ color: #fff;
+ text-decoration: none;
+ border-radius: 6px;
+ font-weight: 600;
+}
+```
diff --git a/docs/monetization/17_caching_layer.md b/docs/monetization/17_caching_layer.md
new file mode 100644
index 000000000..8a6385109
--- /dev/null
+++ b/docs/monetization/17_caching_layer.md
@@ -0,0 +1,74 @@
+---
+status: not-started
+last_updated: 2026-05-04
+---
+# Prompt 17: Caching Layer for On-Chain Data
+
+## Objective
+Implement a caching layer (e.g., using Redis) to reduce redundant calls to the Solana RPC and other external APIs, improving performance and reliability.
+
+## Explanation
+Our application makes several calls to the Solana network (e.g., `getLatestBlockhash`, `getParsedTransaction`) and potentially other services like CoinGecko. These calls can be slow and are subject to rate limiting. Caching frequently accessed, non-time-sensitive data can significantly speed up our API responses.
+
+## Instructions
+1. **Set Up a Caching Client:**
+ * Add a Redis client library (e.g., `ioredis`) to the project.
+ * Create a Redis client instance that can be shared across the application, likely in `api/_lib/redis.js`.
+
+2. **Identify Caching Opportunities:**
+ * **Skill Prices:** Prices set by creators don't change often. They can be cached for several minutes. The cache should be invalidated whenever a creator updates their prices.
+ * **Agent Details:** Marketplace agent data is a prime candidate for caching.
+ * **Transaction Details:** A confirmed transaction is immutable. Once we've verified a purchase signature with `getParsedTransaction`, we can cache the result indefinitely. If we check the same signature again, we can serve it from the cache.
+ * **SOL/USD Price:** The CoinGecko API has rate limits. We should cache the SOL price for at least 60-120 seconds.
+
+3. **Implement Caching Logic:**
+ * Wrap your data-fetching logic in a "cache-aside" pattern:
+ * First, try to get the data from the Redis cache using a specific key (e.g., `skill-price:${agentId}:${skillName}`).
+ * If the data exists in the cache (a "cache hit"), return it immediately.
+ * If not (a "cache miss"), fetch the data from the primary source (database or external API).
+ * After fetching, store the data in Redis with a Time-To-Live (TTL) before returning it.
+
+## Code Example (A generic caching function)
+
+```javascript
+// In api/_lib/cache.js
+import { redis } from './redis.js'; // Assume this exports a Redis client
+
+export async function cacheAside(key, ttlSeconds, fetchDataFn) {
+ const cachedData = await redis.get(key);
+ if (cachedData) {
+ return JSON.parse(cachedData);
+ }
+
+ const liveData = await fetchDataFn();
+
+ // Set with TTL and handle cases where liveData might be null
+ if (liveData) {
+ await redis.set(key, JSON.stringify(liveData), 'EX', ttlSeconds);
+ }
+
+ return liveData;
+}
+```
+
+## Code Example (Using the cache in a service)
+
+```javascript
+// Inside MonetizationService.js
+import { cacheAside } from '../../_lib/cache.js';
+
+class MonetizationService {
+ async getSkillPrice(agentId, skillName) {
+ const cacheKey = `skill-price:${agentId}:${skillName}`;
+ const ttl = 300; // 5 minutes
+
+ return cacheAside(cacheKey, ttl, async () => {
+ const [price] = await sql`
+ SELECT amount, currency_mint FROM agent_skill_prices
+ WHERE agent_id = ${agentId} AND skill_name = ${skillName}
+ `;
+ return price;
+ });
+ }
+}
+```
diff --git a/docs/monetization/18-db-schema-earnings.md b/docs/monetization/18-db-schema-earnings.md
new file mode 100644
index 000000000..5f873622a
--- /dev/null
+++ b/docs/monetization/18-db-schema-earnings.md
@@ -0,0 +1,75 @@
+# Prompt 18: DB Schema for Earnings and Platform Fees
+
+## Objective
+Design and create the database table schema for `skill_payment_earnings` to reliably track revenue for creators and calculate platform fees.
+
+## Explanation
+When a payment is successfully completed, the revenue needs to be allocated. This table will store a record of each sale, attributing the earnings to the correct creator, and clearly separating the gross amount, the platform's cut, and the net amount due to the creator. This is fundamental for accurate accounting and payouts.
+
+## Instructions
+1. **Define the Table Schema:**
+ * Create a new table named `skill_payment_earnings`.
+ * It should include the following columns:
+ * `id`: Primary key (UUID or auto-incrementing integer).
+ * `payment_id`: A unique foreign key referencing `skill_payments(id)`. This ensures each payment has only one corresponding earnings entry.
+ * `agent_id`: Foreign key to `agents(id)`.
+ * `creator_id`: Foreign key to `users(id)`, identifying the user who gets the earnings.
+ * `gross_amount`: The total amount paid by the user (in lamports or smallest unit).
+ * `platform_fee_bps`: The platform fee basis points at the time of the transaction (e.g., `500` for 5%).
+ * `platform_fee_amount`: The calculated platform fee (`gross_amount * platform_fee_bps / 10000`).
+ * `net_amount`: The amount due to the creator (`gross_amount - platform_fee_amount`).
+ * `currency_mint`: The mint address of the currency used.
+ * `payout_id`: A nullable foreign key that will link to a `payouts` table when the earnings are withdrawn.
+ * `created_at`: Timestamp.
+
+2. **Create Indexes:**
+ * Create an index on `creator_id` to quickly query for all earnings belonging to a specific creator for their dashboard.
+ * Create an index on `payout_id` to find all earnings included in a specific payout batch.
+
+3. **Write the SQL Migration:**
+ * Create a new SQL migration file to apply this schema change to your database.
+
+## SQL Schema Example
+
+```sql
+CREATE TABLE skill_payment_earnings (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ payment_id UUID NOT NULL UNIQUE REFERENCES skill_payments(id) ON DELETE CASCADE,
+ agent_id UUID NOT NULL REFERENCES agents(id),
+ creator_id UUID NOT NULL REFERENCES users(id),
+
+ gross_amount BIGINT NOT NULL,
+ platform_fee_bps INTEGER NOT NULL, -- e.g., 500 for 5.00%
+ platform_fee_amount BIGINT NOT NULL,
+ net_amount BIGINT NOT NULL,
+
+ currency_mint VARCHAR(255) NOT NULL,
+
+ -- This will be NULL until the earnings are included in a payout
+ payout_id UUID REFERENCES payouts(id),
+
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT check_amounts CHECK (gross_amount = platform_fee_amount + net_amount)
+);
+
+-- Index for creator dashboard queries
+CREATE INDEX idx_skill_earnings_creator_id ON skill_payment_earnings(creator_id);
+
+-- Index for finding earnings in a payout
+CREATE INDEX idx_skill_earnings_payout_id ON skill_payment_earnings(payout_id);
+
+
+-- You will also need a payouts table for later prompts
+CREATE TABLE payouts (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ creator_id UUID NOT NULL REFERENCES users(id),
+ amount BIGINT NOT NULL,
+ currency_mint VARCHAR(255) NOT NULL,
+ status VARCHAR(50) NOT NULL DEFAULT 'pending', -- pending, completed, failed
+ destination_address VARCHAR(255) NOT NULL,
+ tx_signature VARCHAR(255),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ completed_at TIMESTAMPTZ
+);
+```
diff --git a/docs/monetization/18-on-chain-program-for-skill-nfts.md b/docs/monetization/18-on-chain-program-for-skill-nfts.md
new file mode 100644
index 000000000..6cc088d80
--- /dev/null
+++ b/docs/monetization/18-on-chain-program-for-skill-nfts.md
@@ -0,0 +1,87 @@
+# Prompt 18: On-Chain Program for Skill NFTs
+
+## Objective
+Design and outline the structure of a Solana program (smart contract) that represents ownership of a purchased skill as a Non-Fungible Token (NFT).
+
+## Explanation
+To fully embrace decentralization and give users true ownership, purchasing a skill should mint them an NFT that acts as an on-chain access key. This is a significant architectural step. The NFT would be tied to the user's wallet, the agent, and the specific skill. Our backend could then check for the presence of this NFT in a user's wallet as an alternative way to verify access. This prompt focuses on the design of the on-chain program using Anchor.
+
+## Instructions
+1. **Define the Program's State:**
+ * What data needs to be stored on-chain?
+ * We'll need an account to represent the skill license. Let's call it `SkillLicense`.
+ * The `SkillLicense` account should store:
+ * `authority` (the user's wallet that owns it).
+ * `agent_mint` (the public key of an NFT representing the agent itself, for grouping).
+ * `skill_name` (a string identifying the skill).
+ * `purchase_date`.
+
+2. **Define the Program's Instructions:**
+ * What actions can users take?
+ * The primary instruction will be `mint_skill_license`.
+ * This instruction will be called by our backend (acting as a minter authority) after a payment is verified.
+ * It will create a new `SkillLicense` account and a corresponding NFT for the user.
+ * We might also need a `burn_skill_license` for refunds or transfers.
+
+3. **Set up an Anchor Project:**
+ * If not already present, set up a new Anchor project in the `/contracts` directory.
+ * Define the `SkillLicense` account struct in `lib.rs`.
+ * Define the `mint_skill_license` instruction handler.
+
+## Anchor (Rust) Code Example (`contracts/src/lib.rs`)
+
+```rust
+use anchor_lang::prelude::*;
+// We would also use anchor_spl::token for NFT minting
+
+declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
+
+#[program]
+pub mod skill_marketplace {
+ use super::*;
+ pub fn mint_skill_license(
+ ctx: Context<MintSkillLicense>,
+ skill_name: String
+ ) -> Result<()> {
+ let license = &mut ctx.accounts.skill_license;
+ license.authority = *ctx.accounts.user.key;
+ license.agent_id = *ctx.accounts.agent.key; // Simplified: agent is an account
+ license.skill_name = skill_name;
+ license.purchase_date = Clock::get()?.unix_timestamp;
+
+ // Here, we would also add the logic to mint a Metaplex NFT
+ // to the user's wallet, using this license account as a basis.
+ // This is a complex step involving CPIs to the Token and Metaplex programs.
+
+ msg!("Skill license created for skill: {}", license.skill_name);
+ Ok(())
+ }
+}
+
+#[derive(Accounts)]
+pub struct MintSkillLicense<'info> {
+ #[account(init, payer = minter, space = 8 + 32 + 32 + 32 + 8)]
+ pub skill_license: Account<'info, SkillLicense>,
+
+ /// CHECK: The agent this skill belongs to
+ pub agent: AccountInfo<'info>,
+
+ /// CHECK: The user who is receiving the license
+ #[account(mut)]
+ pub user: Signer<'info>,
+
+ // The backend's wallet, which has authority to mint licenses
+ #[account(mut)]
+ pub minter: Signer<'info>,
+
+ pub system_program: Program<'info, System>,
+}
+
+#[account]
+pub struct SkillLicense {
+ pub authority: Pubkey, // User who owns the skill
+ pub agent_id: Pubkey, // Agent the skill is for
+ pub skill_name: String,
+ pub purchase_date: i64,
+}
+```
diff --git a/docs/monetization/18-refactor-to-payment-sdk.md b/docs/monetization/18-refactor-to-payment-sdk.md
new file mode 100644
index 000000000..173109515
--- /dev/null
+++ b/docs/monetization/18-refactor-to-payment-sdk.md
@@ -0,0 +1,84 @@
+# Prompt 18: Refactor to a Payment SDK
+
+## Objective
+Abstract the core Solana payment logic into a reusable SDK within the `agent-payments-sdk/` directory to promote code reuse and maintainability.
+
+## Explanation
+As the platform grows, you may want to add payments for other items, such as purchasing agents, tipping creators, or buying 3D assets. Repeating the Solana Pay transaction logic in each API endpoint would be inefficient and error-prone. By creating a centralized `PaymentSDK`, we can handle all payment-related operations in one place.
+
+## Instructions
+1. **Identify Core Logic:**
+ * Review your `api/payments/prepare-skill-purchase.js` endpoint.
+ * Identify the reusable parts:
+ * Creating and configuring a `Connection`.
+ * Constructing SPL token transfer instructions.
+ * Handling platform fees.
+ * Serializing and structuring the transaction for the Solana Pay response.
+ * Verifying a transaction signature.
+
+2. **Create the SDK Module (`agent-payments-sdk/src/index.ts`):**
+ * Create a `PaymentSDK` class or a set of exported functions.
+ * Move the core logic identified above into methods within this SDK.
+ * For example, you could have a method `createSplTransferTransaction(buyer, transfers, reference)` where `transfers` is an array of `{ destination, amount }` objects. This method would handle the platform fee calculation internally.
+ * Another method could be `verifyTransaction(signature, expectedTransfers)`.
+
+3. **Refactor the API Endpoint:**
+ * Rewrite the `prepare-skill-purchase.js` endpoint to use your new SDK.
+ * The endpoint will now be much simpler. It will be responsible for fetching the business logic details (like the skill price and creator wallet) and then calling the SDK methods to construct and verify the transaction.
+
+## Code Example (`agent-payments-sdk/src/index.ts`)
+
+```typescript
+import { Connection, PublicKey, Transaction, SystemProgram } from '@solana/web3.js';
+import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';
+
+interface Transfer {
+ destination: PublicKey;
+ amount: bigint; // Use BigInt for lamports
+}
+
+export class PaymentSDK {
+ private connection: Connection;
+ private platformWallet: PublicKey;
+ private platformFeeBps: bigint;
+
+ constructor(rpcUrl: string, platformWallet: string, feeBps: number) {
+ this.connection = new Connection(rpcUrl);
+ this.platformWallet = new PublicKey(platformWallet);
+ this.platformFeeBps = BigInt(feeBps);
+ }
+
+ async createPurchaseTransaction(
+ buyer: PublicKey,
+ creator: PublicKey,
+ totalAmount: bigint,
+ mint: PublicKey,
+ reference: PublicKey
+ ): Promise<Transaction> {
+ const { blockhash } = await this.connection.getLatestBlockhash();
+ const transaction = new Transaction({ recentBlockhash: blockhash, feePayer: buyer });
+
+ const buyerAta = await getAssociatedTokenAddress(mint, buyer);
+ const creatorAta = await getAssociatedTokenAddress(mint, creator);
+ const platformAta = await getAssociatedTokenAddress(mint, this.platformWallet);
+
+ const platformFee = (totalAmount * this.platformFeeBps) / 10000n;
+ const creatorAmount = totalAmount - platformFee;
+
+ transaction.add(
+ createTransferInstruction(buyerAta, creatorAta, buyer, creatorAmount),
+ );
+ if (platformFee > 0) {
+ transaction.add(
+ createTransferInstruction(buyerAta, platformAta, buyer, platformFee),
+ );
+ }
+
+ // Add reference for lookup
+ transaction.add(SystemProgram.transfer({ fromPubkey: buyer, toPubkey: reference, lamports: 0 }));
+
+ return transaction;
+ }
+ // ... other methods like verifyTransaction
+}
+```
diff --git a/docs/monetization/18_testing_the_service.md b/docs/monetization/18_testing_the_service.md
new file mode 100644
index 000000000..8d8aa624b
--- /dev/null
+++ b/docs/monetization/18_testing_the_service.md
@@ -0,0 +1,72 @@
+---
+status: not-started
+last_updated: 2026-05-04
+---
+# Prompt 18: Unit and Integration Tests for Monetization Service
+
+## Objective
+Write a suite of tests for the `MonetizationService` to ensure its logic is correct, robust, and reliable.
+
+## Explanation
+The monetization logic is critical and involves financial transactions, so it must be thoroughly tested. We need to create both unit tests (testing individual methods in isolation) and integration tests (testing the service's interaction with a real or mock database).
+
+## Instructions
+1. **Set Up a Testing Framework:**
+ * Ensure a testing framework like Jest or Vitest is configured for the backend.
+ * Set up a separate test database or a mechanism to run tests in a transaction that can be rolled back, to avoid polluting the development database.
+
+2. **Write Unit Tests:**
+ * **Mock Dependencies:** Mock the `sql` database client and any external APIs.
+ * **Test Cases:**
+ * `setSkillPrices`: Test that it correctly formats the SQL query for upserting prices. Test that it throws an error if the user is not the agent owner.
+ * `preparePurchaseTransaction`: Mock the database calls for price/wallet lookups. Verify that the created transaction has the correct instructions, amounts, and public keys. Test the platform fee calculation.
+ * `checkSkillOwnership`: Mock database calls to simulate a user owning a skill, not owning it, and the skill being free. Test that it returns the correct access decision.
+
+3. **Write Integration Tests:**
+ * **Use a Test Database:** Connect to a real test database.
+ * **Test Scenarios:**
+ * Create a test user and agent.
+ * Call `setSkillPrices` and then immediately query the database to verify the price was written correctly.
+ * Simulate a purchase confirmation by first inserting a record into `user_purchased_skills` and then calling `checkSkillOwnership` to ensure it returns true.
+ * Test the `getCreatorSalesData` method by seeding some purchase data and verifying that the aggregation (total revenue, counts) is correct.
+
+## Code Example (Jest - Unit Test Snippet)
+
+```javascript
+// In tests/services/MonetizationService.test.js
+import { MonetizationService } from '../../api/_lib/services/MonetizationService';
+import { sql } from '../../api/_lib/db'; // Mock this
+
+// Mock the database
+jest.mock('../../api/_lib/db', () => ({
+ sql: jest.fn().mockResolvedValue([
+ // mock return values here
+ ]),
+}));
+
+describe('MonetizationService', () => {
+ let service;
+ const mockUser = { id: 'user-123' };
+
+ beforeEach(() => {
+ service = new MonetizationService(mockUser);
+ sql.mockClear();
+ });
+
+ it('should block price setting if user is not the owner', async () => {
+ // Mock the agent ownership check to return no agent
+ sql.mockResolvedValueOnce([]);
+ await expect(service.setSkillPrices('agent-abc', {})).rejects.toThrow('permission denied');
+ });
+
+ it('should correctly calculate platform fee in transaction prep', async () => {
+ // Mock DB calls to return a price of 1,000,000 lamports
+ // Mock web3.js calls
+ // ...
+ const { transaction } = await service.preparePurchaseTransaction(...);
+ // Inspect the deserialized transaction to check instruction amounts
+ // expect(creatorInstruction.amount).toBe(950000); // 95%
+ // expect(platformFeeInstruction.amount).toBe(50000); // 5%
+ });
+});
+```
diff --git a/docs/monetization/19-backend-record-earnings.md b/docs/monetization/19-backend-record-earnings.md
new file mode 100644
index 000000000..c3112e1e3
--- /dev/null
+++ b/docs/monetization/19-backend-record-earnings.md
@@ -0,0 +1,77 @@
+# Prompt 19: Backend Logic to Record Earnings
+
+## Objective
+After a payment is confirmed, implement the backend logic to calculate and record the creator's earnings and the platform fee in the `skill_payment_earnings` table.
+
+## Explanation
+This is the accounting step of the monetization flow. It connects the confirmed payment to the creator's ledger. This logic must run immediately after payment confirmation to ensure that revenue is tracked in real-time.
+
+## Instructions
+1. **File to Edit:**
+ * Open the backend endpoint for payment confirmation: `POST /api/payments/confirm-skill-payment`.
+
+2. **Integrate Earnings Calculation:**
+ * Locate the spot in your code inside the database transaction, immediately after you have updated the `skill_payments` table to `completed` and created the `skill_access_grants` record.
+ * **Define Platform Fee:** Get the current platform fee. It's best practice to have this as a configurable value (e.g., in an environment variable or a configuration file). For example, `PLATFORM_FEE_BPS = 500` (for 5%).
+ * **Calculate Amounts:**
+ * `gross_amount`: This is the `amount` from the `paymentIntent` record.
+ * `platform_fee_amount`: `Math.floor(gross_amount * PLATFORM_FEE_BPS / 10000)`. Use floor to be safe.
+ * `net_amount`: `gross_amount - platform_fee_amount`.
+ * **Get Creator ID:** You'll need the ID of the agent's creator, which should be available on the `agent` object.
+
+3. **Insert the Earnings Record:**
+ * Within the same database transaction, insert a new row into the `skill_payment_earnings` table with all the calculated values.
+
+## Code Example (Backend - `confirm-skill-payment` logic)
+
+This refines the example from Prompt 14, adding the earnings logic to the transaction.
+
+```javascript
+// Inside your /api/payments/confirm-skill-payment endpoint handler
+
+// ... after successfully verifying the on-chain transaction ...
+
+const PLATFORM_FEE_BPS = 500; // 5%
+
+try {
+ // Use a database transaction to ensure atomicity
+ await db.transaction(async (trx) => {
+ // 1. Update Payment Status
+ await trx.update('skill_payments', { status: 'completed', signature: signature })
+ .where({ id: paymentId });
+
+ // 2. Grant Skill Access
+ const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
+ await trx.insert({
+ user_id: user.id,
+ agent_id: paymentIntent.agentId,
+ skill_name: paymentIntent.skillName,
+ payment_id: paymentId,
+ expires_at: expiresAt,
+ }).into('skill_access_grants');
+
+ // 3. NEW: Record Earnings
+ const agent = await trx.select('creator_id').from('agents').where({ id: paymentIntent.agentId }).first();
+ const gross_amount = paymentIntent.amount;
+ const platform_fee_amount = Math.floor(gross_amount * PLATFORM_FEE_BPS / 10000);
+ const net_amount = gross_amount - platform_fee_amount;
+
+ await trx.insert({
+ payment_id: paymentId,
+ agent_id: paymentIntent.agentId,
+ creator_id: agent.creator_id,
+ gross_amount,
+ platform_fee_bps: PLATFORM_FEE_BPS,
+ platform_fee_amount,
+ net_amount,
+ currency_mint: paymentIntent.currency_mint,
+ }).into('skill_payment_earnings');
+ });
+
+ res.status(200).json({ success: true, message: 'Payment confirmed and access granted.' });
+
+} catch (error) {
+ console.error('Error in confirmation transaction:', error);
+ res.status(500).json({ error: 'Failed to finalize payment.' });
+}
+```
diff --git a/docs/monetization/19-integrate-skill-nfts-into-purchase-flow.md b/docs/monetization/19-integrate-skill-nfts-into-purchase-flow.md
new file mode 100644
index 000000000..6ac82b61e
--- /dev/null
+++ b/docs/monetization/19-integrate-skill-nfts-into-purchase-flow.md
@@ -0,0 +1,71 @@
+# Prompt 19: Integrate Skill NFTs into Purchase Flow
+
+## Objective
+Modify the skill purchase and verification flow to mint a "Skill NFT" to the user upon a successful purchase, using the on-chain program designed in the previous prompt.
+
+## Explanation
+This task connects our off-chain backend with our on-chain program. After a user's payment is confirmed, instead of just writing to our own database, the backend's primary job will be to call the `mint_skill_license` instruction on our Solana program. This creates a durable, on-chain record of ownership for the user.
+
+## Instructions
+1. **Update Verification Endpoint:**
+ * In the `/api/marketplace/skills/verify-purchase` endpoint, after successfully verifying the user's payment transaction, add a new step.
+
+2. **Call the On-Chain Program:**
+ * The backend, using its own service wallet (the "minter"), will construct and sign a transaction that calls the `mint_skill_license` instruction of our deployed Solana program.
+ * It will need the Anchor-generated client library for the program to build this transaction easily.
+ * The parameters for the instruction (`user`, `agent`, `skill_name`) will come from the context of the purchase.
+
+3. **Update Access Control:**
+ * Modify the `hasSkillAccess` helper function from prompt #17.
+ * Add a new check: after checking the local database, if access is still denied, the function should query the blockchain to see if the user's wallet holds the required Skill NFT for that agent and skill. This makes the system more decentralized, as ownership can be proven directly on-chain.
+
+## Code Example (Backend Snippet in `verify-purchase.js`)
+
+```javascript
+import { AnchorProvider, Program } from '@coral-xyz/anchor';
+import { Connection, Keypair, PublicKey } from '@solana/web3.js';
+// Assume `idl` and `programId` are available for our Anchor program
+import idl from '../../../../contracts/target/idl/skill_marketplace.json';
+const programId = new PublicKey(idl.metadata.address);
+
+// ... inside the verify-purchase handler, after payment is confirmed ...
+
+// 1. Set up connection to the on-chain program
+const connection = new Connection(clusterApiUrl('devnet'));
+const backendMinterWallet = Keypair.fromSecretKey(Buffer.from(process.env.MINTER_PRIVATE_KEY, 'base64'));
+const provider = new AnchorProvider(connection, new Wallet(backendMinterWallet), {});
+const program = new Program(idl, programId, provider);
+
+// 2. Prepare accounts for the instruction
+const skillLicenseAccount = Keypair.generate();
+const userPublicKey = new PublicKey(purchaserPublicKey); // from original request
+const agentPublicKey = new PublicKey(agent.on_chain_id); // Assuming agent has an on-chain ID
+
+try {
+ // 3. Call the 'mint_skill_license' instruction
+ const txSignature = await program.methods
+ .mintSkillLicense(skillName)
+ .accounts({
+ skillLicense: skillLicenseAccount.publicKey,
+ agent: agentPublicKey,
+ user: userPublicKey,
+ minter: backendMinterWallet.publicKey,
+ systemProgram: SystemProgram.programId,
+ })
+ .signers([skillLicenseAccount, backendMinterWallet]) // Minter and new account need to sign
+ .rpc();
+
+ console.log(`Successfully minted Skill NFT. Transaction: ${txSignature}`);
+
+ // We might still write to our local DB for caching/performance,
+ // but the on-chain record is now the source of truth.
+ await recordPurchaseInLocalDB(userId, agentId, skillName, txSignature);
+
+ return json(res, { success: true, message: 'Skill NFT minted!' });
+
+} catch (e) {
+ console.error("Failed to mint skill NFT:", e);
+ // Important: Handle this failure, maybe by retrying or refunding the user.
+ return error(res, 500, 'Failed to mint on-chain license.');
+}
+```
diff --git a/docs/monetization/19-purchase-notifications.md b/docs/monetization/19-purchase-notifications.md
new file mode 100644
index 000000000..82678065f
--- /dev/null
+++ b/docs/monetization/19-purchase-notifications.md
@@ -0,0 +1,80 @@
+# Prompt 19: Purchase Confirmation Notifications
+
+## Objective
+After a successful skill purchase, send a confirmation to the user, either via an in-app notification, an email, or both.
+
+## Explanation
+Providing post-purchase confirmation is a standard practice that builds user trust and keeps them informed. An in-app notification provides immediate feedback, while an email serves as a permanent receipt. This task involves setting up a notification system and triggering it after a purchase is confirmed.
+
+## Instructions
+1. **Choose a Notification System:**
+ * **In-app:** You can build a simple notification system with a database table (`notifications`) and a UI element in the site header that shows a notification count.
+ * **Email:** Integrate with an email service provider like SendGrid, Postmark, or Resend.
+
+2. **Create a Notification Service (Backend):**
+ * Create a new module, e.g., `services/notifications.js`.
+ * This service will have a function, e.g., `sendPurchaseConfirmation(userId, purchaseDetails)`.
+ * This function will contain the logic to either:
+ * Insert a new row into the `notifications` table in your database.
+ * Or, make an API call to your chosen email service provider to send a templated email.
+
+3. **Integrate into Purchase Flow (Backend):**
+ * In your payment confirmation endpoint (`api/payments/prepare-skill-purchase.js`), after you have verified the transaction and granted the skill, call your new `sendPurchaseConfirmation` function.
+ * Pass all the necessary details, such as the user's information (for their email address), the skill name, agent name, and price paid.
+
+## Code Example (Backend - Notification Service using Resend)
+
+```javascript
+// services/notifications.js
+import { Resend } from 'resend';
+import { findUserById } from '../_lib/db'; // DB function to get user details
+
+const resend = new Resend(process.env.RESEND_API_KEY);
+
+export async function sendPurchaseConfirmationEmail(userId, details) {
+ try {
+ const user = await findUserById(userId);
+ if (!user || !user.email) {
+ console.warn(`Cannot send email: User ${userId} not found or has no email.`);
+ return;
+ }
+
+ await resend.emails.send({
+ to: user.email,
+ subject: 'Your Skill Purchase Confirmation',
+ html: `
+ <h1>Purchase Confirmed!</h1>
+ <p>Hi ${user.name || 'there'},</p>
+ <p>You have successfully purchased the skill "<strong>${details.skillName}</strong>" for the agent "<strong>${details.agentName}</strong>".</p>
+ <p><strong>Price:</strong> ${(details.amount / 1e6).toFixed(2)} USDC</p>
+ <p>Thank you for your purchase!</p>
+ `,
+ });
+ } catch (error) {
+ console.error('Failed to send purchase confirmation email:', error);
+ }
+}
+```
+
+## Integration into Payment Endpoint
+
+```javascript
+// In api/payments/prepare-skill-purchase.js (GET handler)
+// ... after granting skill access
+
+import { sendPurchaseConfirmationEmail } from '../../services/notifications';
+
+// ...
+await grantSkillToUser(...);
+await logTransaction(...);
+
+// Asynchronously send the notification so it doesn't block the response
+sendPurchaseConfirmationEmail(purchaseDetails.userId, {
+ skillName: purchaseDetails.skillName,
+ agentName: purchaseDetails.agentName,
+ amount: purchaseDetails.amount,
+});
+
+res.status(200).json({ status: 'ok', message: 'Purchase confirmed!' });
+```
diff --git a/docs/monetization/19_sale_notifications.md b/docs/monetization/19_sale_notifications.md
new file mode 100644
index 000000000..69f86675d
--- /dev/null
+++ b/docs/monetization/19_sale_notifications.md
@@ -0,0 +1,70 @@
+---
+status: not-started
+last_updated: 2026-05-04
+---
+# Prompt 19: User Experience - Notifications for Sales
+
+## Objective
+Implement a system to notify creators in real-time or near-real-time when one of their skills is purchased.
+
+## Explanation
+A key part of a positive creator experience is immediate feedback on sales. We will build a notification system that alerts creators when they've made a sale. This could be an on-site notification, an email, or both.
+
+## Instructions
+1. **Choose a Notification Channel:**
+ * **On-site:** A simple bell icon in the navigation that shows a red dot for new notifications. Clicking it reveals a dropdown of recent events.
+ * **Email:** Send a transactional email to the user's registered email address.
+ * For this task, we will focus on the backend logic to generate notifications, which can then be used for any channel.
+
+2. **Database Schema for Notifications:**
+ * Create a `notifications` table:
+ * `id`: Primary key.
+ * `user_id`: The user who receives the notification.
+ * `type`: An enum or text, e.g., `'SKILL_SALE'`.
+ * `payload`: A JSONB column with details about the event (e.g., `{ "skillName": "...", "price": 1.00, "buyerUsername": "..." }`).
+ * `is_read`: A boolean flag, default `false`.
+ * `created_at`: Timestamp.
+
+3. **Trigger Notification on Purchase:**
+ * In the `POST /api/skills/purchase-confirm` endpoint, after successfully verifying and recording a purchase, insert a new row into the `notifications` table.
+ * The `user_id` should be the ID of the agent's creator.
+
+4. **API to Fetch Notifications:**
+ * Create a new endpoint, `GET /api/notifications`.
+ * This endpoint should fetch all unread notifications for the currently authenticated user.
+ * It could also fetch a list of recent notifications (both read and unread).
+
+5. **API to Mark Notifications as Read:**
+ * Create an endpoint like `POST /api/notifications/mark-read`.
+ * This would update the `is_read` flag for specified notification IDs, so they no longer appear as "new."
+
+## Code Example (Logic in `purchase-confirm` API)
+
+```javascript
+// ... after successfully inserting into user_purchased_skills
+
+const [agentOwner] = await sql`
+ SELECT user_id FROM agent_identities WHERE id = ${agent_id}
+`;
+
+if (agentOwner) {
+ // Create a notification for the agent's creator
+ await sql`
+ INSERT INTO notifications (user_id, type, payload)
+ VALUES (
+ ${agentOwner.user_id},
+ 'SKILL_SALE',
+ ${JSON.stringify({
+ skillName: skill_name,
+ agentId: agent_id,
+ amount: expectedAmount,
+ currency: currencyMint,
+ buyerId: user.id,
+ purchaseSignature: signature
+ })}::jsonb
+ )
+ `;
+}
+
+// ... return success response
+```
diff --git a/docs/monetization/20-display-earnings-dashboard.md b/docs/monetization/20-display-earnings-dashboard.md
new file mode 100644
index 000000000..502b4d4e2
--- /dev/null
+++ b/docs/monetization/20-display-earnings-dashboard.md
@@ -0,0 +1,121 @@
+# Prompt 20: Display Earnings in Creator Dashboard
+
+## Objective
+Fetch and display the creator's earnings summary and a list of their recent transactions in the "Earnings" tab of their dashboard.
+
+## Explanation
+This prompt brings the creator-facing part of the monetization feature to life. It involves building the backend endpoint to aggregate earnings data and then using that data to populate the UI components created in Prompt 17.
+
+## Instructions
+1. **File to Edit (Backend):**
+ * Open the file for the `GET /api/dashboard/earnings` endpoint.
+
+2. **Implement Backend Logic:**
+ * **Authentication:** Ensure the user is authenticated.
+ * **Summary Metrics:**
+ * Write a SQL query to get the `SUM` of `gross_amount`, `platform_fee_amount`, and `net_amount` from the `skill_payment_earnings` table, `WHERE creator_id` matches the current user.
+ * Also, calculate the `withdrawable` amount by summing `net_amount` only for earnings where `payout_id` is `NULL`.
+ * **Recent Sales:**
+ * Write a query to get the 10 most recent records from `skill_payment_earnings` for the current creator, ordered by `created_at DESC`.
+ * Join with the `skill_payments` table to get additional details like the `skill_name`.
+ * **Response:** Return a JSON object containing `summary` and `recent_sales`.
+
+3. **File to Edit (Frontend):**
+ * Open the JavaScript for `agent-edit.html`.
+
+4. **Implement Frontend Rendering:**
+ * In the `initEarningsTab` function (from Prompt 17), use the data returned from the API to populate the UI.
+ * **Summary:** Update the text content of the summary cards (`#earnings-total-revenue`, etc.) with the formatted currency values.
+ * **Recent Sales:**
+ * Create a function `renderRecentSales(sales)`.
+ * If the `sales` array is empty, show a "No sales yet" message.
+ * If it has data, dynamically create a table or a list of `div`s to display each sale.
+ * Include columns for `Date`, `Skill Name`, `Gross Revenue`, and `Net Earnings`.
+ * Format dates and currency values to be human-readable.
+
+## Code Example (Backend - `/api/dashboard/earnings.js`)
+
+```javascript
+// Inside the API handler
+
+const user = await getAuthenticatedUser(req);
+
+// Query for summary metrics
+const summaryResult = await db('skill_payment_earnings')
+ .where({ creator_id: user.id })
+ .sum({
+ total_revenue: 'gross_amount',
+ net_earnings: 'net_amount'
+ })
+ .first();
+
+const withdrawableResult = await db('skill_payment_earnings')
+ .where({ creator_id: user.id, payout_id: null })
+ .sum({ amount: 'net_amount' })
+ .first();
+
+const summary = {
+ total_revenue: summaryResult.total_revenue || 0,
+ net_earnings: summaryResult.net_earnings || 0,
+ withdrawable: withdrawableResult.amount || 0,
+};
+
+// Query for recent sales
+const recent_sales = await db('skill_payment_earnings as earn')
+ .join('skill_payments as pay', 'earn.payment_id', 'pay.id')
+ .where('earn.creator_id', user.id)
+ .orderBy('earn.created_at', 'desc')
+ .limit(10)
+ .select(
+ 'earn.created_at',
+ 'pay.skill_name',
+ 'earn.gross_amount',
+ 'earn.net_amount',
+ 'earn.currency_mint'
+ );
+
+res.status(200).json({ summary, recent_sales });
+```
+
+## Code Example (Frontend - `agent-edit.html` script)
+
+```javascript
+function renderRecentSales(sales) {
+ const container = document.getElementById('earnings-recent-sales');
+ if (!sales || sales.length === 0) {
+ container.innerHTML = '<p>No sales yet.</p>';
+ return;
+ }
+
+ const table = document.createElement('table');
+ table.className = 'earnings-table';
+ table.innerHTML = `
+ <thead>
+ <tr>
+ <th>Date</th>
+ <th>Skill</th>
+ <th>Gross</th>
+ <th>Net</th>
+ </tr>
+ </thead>
+ <tbody>
+ ${sales.map(sale => `
+ <tr>
+ <td>${new Date(sale.created_at).toLocaleDateString()}</td>
+ <td>${escapeHtml(sale.skill_name)}</td>
+ <td>${formatCurrency(sale.gross_amount, sale.currency_mint)}</td>
+ <td>${formatCurrency(sale.net_amount, sale.currency_mint)}</td>
+ </tr>
+ `).join('')}
+ </tbody>
+ `;
+ container.innerHTML = '';
+ container.appendChild(table);
+}
+
+function formatCurrency(amount, mint) {
+ // Basic formatting, assuming 6 decimals for USDC
+ const value = (amount / 1e6).toFixed(2);
+ return `$${value} USDC`;
+}
+```
diff --git a/docs/monetization/20-error-handling-frontend.md b/docs/monetization/20-error-handling-frontend.md
new file mode 100644
index 000000000..fe371dec4
--- /dev/null
+++ b/docs/monetization/20-error-handling-frontend.md
@@ -0,0 +1,76 @@
+# Prompt 20: Error Handling (Frontend)
+
+## Objective
+Implement robust and user-friendly error handling throughout the entire frontend purchase flow.
+
+## Explanation
+Things can go wrong during a purchase: the backend API might be down, the Solana network could be congested, or the user might close the modal prematurely. We need to catch these errors and provide clear, helpful feedback to the user instead of leaving them with a broken UI.
+
+## Instructions
+1. **Use `try...catch` Blocks:**
+ * Wrap all `fetch` calls and asynchronous operations in your payment logic (`src/marketplace.js`) within `try...catch` blocks.
+
+2. **Display User-Friendly Messages:**
+ * When an error is caught, display a message to the user. Don't show raw technical errors like "TypeError: failed to fetch".
+ * Use a dedicated element in your payment modal or a global "toast" notification system.
+ * Messages should be actionable. For example:
+ * "Could not connect to the server. Please check your internet connection and try again."
+ * "Failed to create the transaction. Please try again in a few moments."
+ * "The transaction timed out. Please try again."
+
+3. **Manage UI State:**
+ * Ensure that the UI is correctly reset after an error. For example, if an error occurs while generating the QR code, the loading spinner should be hidden, and the "Purchase" button should become clickable again.
+ * The payment modal should have a "Close" or "Cancel" button that properly cleans up any polling timers or pending states.
+
+## Code Example (Frontend - `src/marketplace.js`)
+
+```javascript
+// In your handlePurchaseClick function
+
+const modal = $('payment-modal');
+const spinner = modal.querySelector('.spinner');
+const errorMessageEl = modal.querySelector('.error-message');
+let pollInterval = null; // Keep track of the timer
+
+function showModalError(message) {
+ spinner.hidden = true;
+ errorMessageEl.textContent = message;
+}
+
+function cleanupModal() {
+ if (pollInterval) {
+ clearInterval(pollInterval);
+ pollInterval = null;
+ }
+ modal.close();
+ spinner.hidden = true;
+ errorMessageEl.textContent = '';
+}
+
+modal.querySelector('.close-modal-btn').addEventListener('click', cleanupModal);
+
+// ...
+try {
+ const response = await fetch('/api/payments/prepare-skill-purchase', { /* ... */ });
+
+ if (!response.ok) {
+ // Handle specific HTTP errors from the backend
+ const errorData = await response.json().catch(() => ({})); // Gracefully handle non-JSON error bodies
+ throw new Error(errorData.error || `The server responded with status ${response.status}. Please try again.`);
+ }
+
+ // ... (success path with polling)
+
+ pollInterval = setInterval(/* ... */);
+ setTimeout(() => {
+ if (pollInterval) {
+ clearInterval(pollInterval);
+ showModalError("Confirmation timed out. Please check your wallet and transaction history.");
+ }
+ }, 300000);
+
+} catch (error) {
+ console.error('Purchase failed:', error);
+ showModalError(error.message || 'An unexpected error occurred.');
+}
+```
diff --git a/docs/monetization/20-usage-based-billing-model.md b/docs/monetization/20-usage-based-billing-model.md
new file mode 100644
index 000000000..67ac24b80
--- /dev/null
+++ b/docs/monetization/20-usage-based-billing-model.md
@@ -0,0 +1,92 @@
+# Prompt 20: Usage-Based Billing Model
+
+## Objective
+Design the database schema and API structure to support usage-based ("pay-per-call") billing for specific agent skills.
+
+## Explanation
+Some skills are better monetized by charging for each use rather than a one-time purchase or subscription (e.g., a call to a powerful AI model, or a complex on-chain analysis). This requires a system to track usage, a way for users to pre-fund a balance, and a mechanism to deduct from that balance on each skill execution.
+
+## Instructions
+1. **Update `agent_skill_prices` Table:**
+ * Add a `billing_type` column (e.g., 'one_time', 'per_call').
+ * The `amount` would now represent the cost per execution for 'per_call' skills.
+
+2. **Create `user_credit_balances` Table:**
+ * This table will store the pre-paid balance for each user.
+ * Columns: `user_id`, `balance_amount`, `currency_mint`.
+
+3. **Implement a "Top Up" Flow:**
+ * Create a UI in the user's profile/dashboard to add credits.
+ * This will be a standard payment flow where the user transfers funds (e.g., USDC) to a company-owned treasury wallet. A backend endpoint will verify this transaction and update the user's balance in `user_credit_balances`.
+
+4. **Modify Skill Execution Endpoint:**
+ * In the main skill execution endpoint, before running the skill, check its `billing_type`.
+ * If it's 'per_call', check if the user has sufficient balance in `user_credit_balances`.
+ * If they do, deduct the skill's `amount` from their balance *before* executing the skill. This must be an atomic operation.
+ * If they don't have enough balance, return an error (e.g., 402 Payment Required) with a message prompting them to top up their account.
+
+## Database Schema Changes
+
+```sql
+-- Add billing type to prices table
+ALTER TABLE agent_skill_prices
+ADD COLUMN billing_type TEXT NOT NULL DEFAULT 'one_time' CHECK (billing_type IN ('one_time', 'per_call'));
+
+-- New table for user credit balances
+CREATE TABLE user_credit_balances (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID REFERENCES auth.users(id) NOT NULL UNIQUE,
+ balance_amount BIGINT NOT NULL DEFAULT 0,
+ currency_mint TEXT NOT NULL, -- For now, assume one currency like USDC
+ updated_at TIMESTAMPTZ DEFAULT NOW()
+);
+```
+
+## Code Example (Skill Execution Endpoint Snippet)
+
+```javascript
+// Inside the skill execution endpoint, after checking basic access
+// but before running the skill.
+
+const { data: priceInfo } = await supabase.from('agent_skill_prices')
+ .select('amount, billing_type').eq('agent_id', agentId).eq('skill_name', skillName).single();
+
+if (priceInfo && priceInfo.billing_type === 'per_call') {
+ // It's a pay-per-call skill, check and deduct balance.
+ // This should be done in a database transaction (RPC function in Supabase).
+
+ const { error: deductError } = await supabase.rpc('deduct_skill_charge', {
+ user_id_in: userId,
+ charge_amount: priceInfo.amount
+ });
+
+ if (deductError) {
+ // The RPC function would throw an error if balance is insufficient.
+ return error(res, 402, 'Payment Required: Insufficient credits for this skill.');
+ }
+}
+
+// ... proceed with skill execution ...
+```
+
+### Supabase RPC Function (`deduct_skill_charge`)
+
+```sql
+CREATE OR REPLACE FUNCTION deduct_skill_charge(user_id_in UUID, charge_amount BIGINT)
+RETURNS void AS $$
+DECLARE
+ current_balance BIGINT;
+BEGIN
+ SELECT balance_amount INTO current_balance
+ FROM user_credit_balances WHERE user_id = user_id_in;
+
+ IF current_balance IS NULL OR current_balance < charge_amount THEN
+ RAISE EXCEPTION 'Insufficient balance';
+ END IF;
+
+ UPDATE user_credit_balances
+ SET balance_amount = balance_amount - charge_amount, updated_at = NOW()
+ WHERE user_id = user_id_in;
+END;
+$$ LANGUAGE plpgsql;
+```
diff --git a/docs/monetization/20_multiple_currencies.md b/docs/monetization/20_multiple_currencies.md
new file mode 100644
index 000000000..af6fff6b7
--- /dev/null
+++ b/docs/monetization/20_multiple_currencies.md
@@ -0,0 +1,62 @@
+---
+status: not-started
+last_updated: 2026-05-04
+---
+# Prompt 20: Support for Multiple Currencies
+
+## Objective
+Extend the monetization system to allow creators to set prices and users to pay in different SPL tokens (e.g., BONK, RENDER) in addition to USDC.
+
+## Explanation
+To increase flexibility and appeal to different communities, we should support more than just one currency. This requires changes to how prices are stored, how transactions are built, and how data is displayed.
+
+## Instructions
+1. **Currency Whitelist:**
+ * In the backend configuration, create a whitelist of supported SPL token mints. This should be a list of objects, each containing the mint address, symbol, name, and decimals. This prevents creators from listing arbitrary, untrusted tokens.
+
+2. **Update UI for Setting Prices:**
+ * In the agent editor (`agent-edit.html`), the price input for each skill should now include a dropdown (`<select>`) menu next to the amount.
+ * This dropdown should be populated with the symbols of the whitelisted currencies.
+ * When saving, the chosen `currency_mint` is sent along with the `amount`.
+
+3. **Update Purchase Preparation API:**
+ * The `purchase-prep` API now needs to handle the `currency_mint` of the skill being purchased.
+ * All the `spl-token` instructions must be created using the correct mint address from the skill's price data.
+
+4. **Frontend Wallet Interaction:**
+ * The frontend needs to be aware of the currency being used. When preparing the purchase, it's good practice to check if the user has a sufficient balance of the required token *before* showing the sign prompt. This can be done using `connection.getTokenAccountBalance`.
+ * The UI should clearly display the correct currency symbol (e.g., "Purchase for 500 BONK").
+
+5. **Update Creator Dashboard:**
+ * The sales data aggregation must now `GROUP BY currency_mint` to show total earnings for each currency separately.
+
+## Code Example (Currency Whitelist)
+
+```javascript
+// In a config file, e.g., api/_lib/config.js
+export const SUPPORTED_CURRENCIES = {
+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a': {
+ symbol: 'USDC',
+ decimals: 6,
+ },
+ 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263': {
+ symbol: 'BONK',
+ decimals: 5,
+ }
+};
+```
+
+## Code Example (Price Setting UI Change)
+
+```javascript
+// In agent-edit.js, when rendering price inputs
+const selectHtml = `<select class="currency-select" data-skill-name="${skillName}">
+ ${Object.entries(SUPPORTED_CURRENCIES).map(([mint, {symbol}]) =>
+ `<option value="${mint}" ${price?.currency_mint === mint ? 'selected' : ''}>
+ ${symbol}
+ </option>`
+ ).join('')}
+</select>`;
+
+// The input group would now be: <input type="number"> and the <select>
+```
diff --git a/docs/monetization/21-affiliate-referral-system.md b/docs/monetization/21-affiliate-referral-system.md
new file mode 100644
index 000000000..a564ddaf2
--- /dev/null
+++ b/docs/monetization/21-affiliate-referral-system.md
@@ -0,0 +1,76 @@
+# Prompt 21: Affiliate/Referral System
+
+## Objective
+Design and implement a basic affiliate system where users can earn a commission for referring new users who purchase agent skills.
+
+## Explanation
+A referral system can be a powerful growth engine. This feature will allow users to generate a unique referral code. When a new user signs up using this code and makes a purchase, the original user (the affiliate) will receive a percentage of the sale. This incentivizes word-of-mouth marketing.
+
+## Instructions
+1. **Database Schema:**
+ * Add a `referral_code` column to the `users` table.
+ * Add a `referred_by` column (nullable foreign key to `users.id`) to the `users` table.
+ * Create a `referral_payouts` table to track commissions earned.
+
+2. **UI for Affiliates:**
+ * In the user's dashboard, add a new "Affiliate" section.
+ * Display the user's unique referral link (e.g., `three.ws/register?ref=CODE`).
+ * Show stats: number of sign-ups, total purchase volume from referrals, and commission earned.
+
+3. **Backend Logic:**
+ * **Registration:** When a user registers, check for a `ref` query parameter. If present and valid, store the referrer's user ID in the new user's `referred_by` column.
+ * **Purchase:** When a skill purchase is successfully verified, check if the purchaser was referred by someone.
+ * **Commission:** If they were, calculate the commission (e.g., 5% of the sale price) and create a record in the `referral_payouts` table for the affiliate.
+ * **Payouts:** Create a system (initially can be manual) for paying out earned commissions to affiliates' wallets.
+
+## Database Schema Changes
+
+```sql
+-- Add columns to your user table (e.g., auth.users)
+ALTER TABLE auth.users
+ADD COLUMN referral_code TEXT UNIQUE,
+ADD COLUMN referred_by UUID REFERENCES auth.users(id);
+
+-- Initialize existing users with a referral code
+-- (Requires a function to generate unique codes)
+
+-- Table to track commissions
+CREATE TABLE affiliate_earnings (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ affiliate_user_id UUID REFERENCES auth.users(id) NOT NULL,
+ originating_purchase_id UUID REFERENCES user_purchased_skills(id) NOT NULL,
+ commission_amount BIGINT NOT NULL,
+ commission_currency_mint TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'unpaid' CHECK (status IN ('unpaid', 'paid')),
+ created_at TIMESTAMPTZ DEFAULT NOW()
+);
+```
+
+## Code Example (Purchase Verification Snippet)
+
+```javascript
+// Inside /api/marketplace/skills/verify-purchase.js
+// After the purchase has been successfully recorded...
+
+const { data: purchaser } = await supabase
+ .from('users') // or auth.users
+ .select('referred_by')
+ .eq('id', userId)
+ .single();
+
+if (purchaser && purchaser.referred_by) {
+ const affiliateId = purchaser.referred_by;
+ const saleAmount = /* get price of the skill just sold */;
+ const commissionRate = 0.05; // 5%
+ const commissionAmount = Math.round(saleAmount * commissionRate);
+
+ if (commissionAmount > 0) {
+ await supabase.from('affiliate_earnings').insert({
+ affiliate_user_id: affiliateId,
+ originating_purchase_id: newlyCreatedPurchaseRecord.id,
+ commission_amount: commissionAmount,
+ commission_currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d' // USDC
+ });
+ }
+}
+```
diff --git a/docs/monetization/21-loading-states-frontend.md b/docs/monetization/21-loading-states-frontend.md
new file mode 100644
index 000000000..370610aec
--- /dev/null
+++ b/docs/monetization/21-loading-states-frontend.md
@@ -0,0 +1,86 @@
+# Prompt 21: Loading States (Frontend)
+
+## Objective
+Implement clear loading states throughout the marketplace and payment UI to provide feedback to the user during asynchronous operations.
+
+## Explanation
+A responsive UI should always inform the user when it's busy. Waiting for data to load or a process to complete without any visual feedback can make an application feel slow or broken. This task involves adding loading indicators (like spinners or skeleton screens) to all parts of the monetization feature that involve waiting.
+
+## Instructions
+1. **Agent Detail Page:**
+ * When the agent detail page is loading its data (including skill prices), display a skeleton UI. This means showing grayed-out placeholder boxes where the agent name, description, and skills will eventually appear. This provides a better perceived performance than a blank screen or a single large spinner.
+
+2. **Payment Modal:**
+ * When the user clicks "Purchase" and the frontend is waiting for the backend to create the transaction, show a spinner in the center of the modal.
+ * The QR code and payment details should only appear after the API call is successful and the spinner is hidden.
+
+3. **Buttons:**
+ * Disable buttons and show a loading state on them while their associated action is in progress. For example, the "Save Prices" button on the agent edit page should be disabled and could show text like "Saving..." to prevent double-clicks.
+
+## CSS for Skeleton Loader
+
+```css
+.skeleton {
+ background-color: #2a2a36; /* A darker panel color */
+ border-radius: 4px;
+ animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;
+}
+
+@keyframes pulse {
+ 50% {
+ opacity: .5;
+ }
+}
+
+/* Example usage for a skill entry */
+.skill-entry-skeleton {
+ display: inline-block;
+ width: 120px;
+ height: 24px;
+ margin: 4px;
+}
+```
+
+## HTML/JS for Skeleton State
+
+```javascript
+// In src/marketplace.js, before fetching the agent data
+
+function showDetailSkeleton() {
+ $('d-skills').innerHTML = `
+ <span class="skill-entry-skeleton skeleton"></span>
+ <span class="skill-entry-skeleton skeleton"></span>
+ <span class="skill-entry-skeleton skeleton"></span>
+ `;
+ // Also show skeletons for agent name, description, etc.
+}
+
+async function renderDetail(id) {
+ showDetailSkeleton(); // Show skeleton first
+ try {
+ const agent = await fetchAgentData(id);
+ // ... then render the actual data
+ } catch (e) {
+ // ... handle error
+ }
+}
+```
+
+## Button Loading State
+
+```javascript
+// In the save prices click handler
+const saveBtn = document.getElementById('save-skill-prices-btn');
+saveBtn.disabled = true;
+saveBtn.textContent = 'Saving...';
+
+try {
+ await savePrices();
+ showToast('Success!');
+} catch (e) {
+ showToast('Error!', 'error');
+} finally {
+ saveBtn.disabled = false;
+ saveBtn.textContent = 'Save Prices';
+}
+```
diff --git a/docs/monetization/21-payout-system-ui.md b/docs/monetization/21-payout-system-ui.md
new file mode 100644
index 000000000..e7b581f21
--- /dev/null
+++ b/docs/monetization/21-payout-system-ui.md
@@ -0,0 +1,107 @@
+# Prompt 21: Payout System UI
+
+## Objective
+Create the user interface in the creator dashboard that allows creators to see their withdrawable balance and initiate a payout.
+
+## Explanation
+This is the frontend component of the payout system. It should clearly display how much money the creator can withdraw and provide a simple button to start the process. It also needs a way for creators to set the Solana wallet address where they want to receive their funds.
+
+## Instructions
+1. **File to Edit:**
+ * Open `agent-edit.html` and focus on the `#panel-earnings` section created in a previous prompt.
+
+2. **Create Payouts UI Section:**
+ * Within the "Payout Settings" area of the earnings panel, add the following elements:
+ * An input field for the user to enter their Solana payout wallet address.
+ * A "Save Address" button.
+ * A display area to show the currently saved wallet address.
+ * A display for the "Withdrawable Balance". This should be the same value shown in the summary card at the top of the page.
+ * A "Withdraw Funds" button. This button should be disabled if the withdrawable balance is zero.
+
+3. **Implement JavaScript Logic:**
+ * **Saving Wallet Address:**
+ * When "Save Address" is clicked, validate that the input contains a plausible Solana address (e.g., check length and characters).
+ * Make a `POST` request to a new backend endpoint (e.g., `/api/dashboard/payout-settings`) to save the user's payout address.
+ * **Initiating Withdrawal:**
+ * When "Withdraw Funds" is clicked:
+ * Show a confirmation dialog (`confirm()`) to prevent accidental withdrawals.
+ * If confirmed, make a `POST` request to a new backend endpoint (e.g., `/api/dashboard/request-payout`).
+ * The button should be disabled and show a "Processing..." state while waiting for the API response.
+ * On success, show a confirmation message to the user (e.g., "Payout initiated! It may take a few minutes to arrive.").
+ * On failure, show an error message.
+
+## Code Example (Frontend - `agent-edit.html` HTML)
+
+```html
+<!-- Inside the #earnings-payouts div -->
+<h4>Payout Wallet</h4>
+<div class="form-group">
+ <label class="form-label">Your Solana Wallet Address</label>
+ <div class="payout-address-row">
+ <input class="form-input" id="payout-wallet-input" type="text" placeholder="Enter your SOL address...">
+ <button class="btn-secondary" id="save-wallet-btn">Save</button>
+ </div>
+ <div class="form-status" id="payout-wallet-status"></div>
+</div>
+
+<hr class="earnings-divider">
+
+<h4>Withdraw</h4>
+<div class="payout-withdraw-row">
+ <div>
+ <span class="label">Withdrawable Balance</span>
+ <span class="value" id="payout-withdrawable-balance">$0.00</span>
+ </div>
+ <button class="btn-primary" id="withdraw-btn" disabled>Withdraw Funds</button>
+</div>
+<div class="form-status" id="withdraw-status"></div>
+
+```
+
+## Code Example (Frontend - `agent-edit.html` JavaScript)
+
+```javascript
+// Add this logic to your earnings tab initialization
+
+// Load and display current settings
+function loadPayoutSettings(settings) {
+ const input = document.getElementById('payout-wallet-input');
+ if (settings.payout_address) {
+ input.value = settings.payout_address;
+ }
+ document.getElementById('payout-withdrawable-balance').textContent = formatCurrency(summary.withdrawable);
+ document.getElementById('withdraw-btn').disabled = summary.withdrawable <= 0;
+}
+
+// Save wallet button
+document.getElementById('save-wallet-btn').addEventListener('click', async () => {
+ const address = document.getElementById('payout-wallet-input').value.trim();
+ // Add basic validation here
+
+ // API call to save address
+ const res = await fetch('/api/dashboard/payout-settings', { /* ... */ });
+ // ... handle response and status message
+});
+
+// Withdraw button
+document.getElementById('withdraw-btn').addEventListener('click', async () => {
+ if (!confirm('Are you sure you want to withdraw your available balance?')) return;
+
+ const btn = document.getElementById('withdraw-btn');
+ const statusEl = document.getElementById('withdraw-status');
+ btn.disabled = true;
+ statusEl.textContent = 'Processing...';
+
+ // API call to request payout
+ const res = await fetch('/api/dashboard/request-payout', { method: 'POST' });
+ if (res.ok) {
+ statusEl.textContent = 'Payout initiated!';
+ // Refresh earnings data to show updated balance
+ initEarningsTab();
+ } else {
+ const { error } = await res.json();
+ statusEl.textContent = `Error: ${error}`;
+ btn.disabled = false;
+ }
+});
+```
diff --git a/docs/monetization/21_nft_gating.md b/docs/monetization/21_nft_gating.md
new file mode 100644
index 000000000..1d6b7fa74
--- /dev/null
+++ b/docs/monetization/21_nft_gating.md
@@ -0,0 +1,59 @@
+---
+status: not-started
+last_updated: 2026-05-04
+---
+# Prompt 21: Gating Agent Access Based on NFT Ownership
+
+## Objective
+Implement a new monetization mechanism where creators can restrict access to their entire agent (or specific skills) to holders of a specific NFT collection.
+
+## Explanation
+Token-gating is a powerful web3-native monetization strategy. It builds community and provides utility for NFT holders. This feature will allow creators to specify an NFT collection's "Verified Creator" address (formerly known as `updateAuthority`), and our system will check if a user holds an NFT from that collection before granting access.
+
+## Instructions
+1. **Update UI for Gating Configuration:**
+ * In `agent-edit.html`, add a new section for "Access Control".
+ * Include an option to select "Token Gating" and an input field for the "NFT Collection Address" (this will be the Verified Creator address).
+
+2. **Database Changes:**
+ * Add a column to the `agent_identities` table's `meta` field or a new table to store this gating rule (e.g., `meta.access_rule = { type: 'NFT_HOLD', collection_address: '...' }`).
+
+3. **Backend - Gated Access Check:**
+ * This check should happen in the same place as the skill ownership check (e.g., `api/chat.js`).
+ * When a user tries to interact with a gated agent:
+ * **Fetch User's NFTs:** Use a Solana RPC provider or an indexing service like Helius or Shyft to get all NFTs owned by the user's wallet address. The RPC `getTokenAccountsByOwner` method combined with parsing can work, but indexers are far more efficient.
+ * **Verify Collection:** Iterate through the user's NFTs. For each NFT, fetch its metadata. The metadata (e.g., from an Arweave URL) will contain a `collection` field or a `creators` array. Check if the collection's `key` or one of the creator's `address` matches the `collection_address` specified by the agent creator.
+ * If a match is found, grant access.
+ * If no matching NFT is found, return a `403 Forbidden` error with a message like "You must hold an NFT from the required collection to use this agent."
+
+## Code Example (Backend NFT Check Logic using an Indexer)
+
+```javascript
+// This is a conceptual example. The exact API will depend on the indexer used.
+// Assume `userWalletAddress` and `requiredCollectionAddress` are known.
+
+async function userHoldsNftFromCollection(userWalletAddress, requiredCollectionAddress) {
+ const HELIUS_API_URL = `https://api.helius.xyz/v0/addresses/${userWalletAddress}/nfts?api-key=...`;
+
+ const response = await fetch(HELIUS_API_URL);
+ const data = await response.json();
+
+ for (const nft of data.nfts) {
+ // Helius provides a verified collection address directly
+ const collectionInfo = nft.grouping.find(g => g.group_key === 'collection');
+ if (collectionInfo && collectionInfo.group_value === requiredCollectionAddress) {
+ return true; // Found a matching NFT
+ }
+ }
+
+ return false; // No match found
+}
+
+// In the access control middleware/handler:
+const isHolder = await userHoldsNftFromCollection(user.wallet_address, agent.meta.access_rule.collection_address);
+
+if (!isHolder) {
+ return error(res, 403, 'nft_required', 'Access denied. NFT from required collection not found in your wallet.');
+}
+// Proceed...
+```
diff --git a/docs/monetization/22-backend-for-payouts.md b/docs/monetization/22-backend-for-payouts.md
new file mode 100644
index 000000000..77b3f03ab
--- /dev/null
+++ b/docs/monetization/22-backend-for-payouts.md
@@ -0,0 +1,100 @@
+# Prompt 22: Backend for Payouts
+
+## Objective
+Create the backend infrastructure to process creator payout requests, batch earnings, and prepare the on-chain transaction.
+
+## Explanation
+This is the core of the payout system. The backend will be responsible for securely gathering all of a creator's unpaid earnings, marking them as "in-progress," and constructing a single Solana transaction to transfer the total amount to the creator's designated wallet.
+
+## Instructions
+1. **Create API Route for Payout Request:**
+ * Set up the endpoint `POST /api/dashboard/request-payout`.
+ * This endpoint must be authenticated.
+
+2. **Implement Payout Logic:**
+ * **a. Get User and Settings:** Get the authenticated `user` and fetch their saved `payout_address` from the database. If no address is set, return a `400 Bad Request` error.
+ * **b. Lock Earnings and Calculate Total:**
+ * Start a database transaction.
+ * Find all records in `skill_payment_earnings` for this `creator_id` where `payout_id` is `NULL`.
+ * If there are no such earnings, return an error.
+ * Calculate the `total_net_amount` to be paid out. For simplicity, we'll assume a single currency (USDC) for now.
+ * **c. Create Payout Record:**
+ * Create a new record in the `payouts` table with a `pending` status, the `creator_id`, the `total_net_amount`, and the `destination_address`. Store the `payoutId`.
+ * **d. Associate Earnings with Payout:**
+ * Update all the earnings records you found in the previous step, setting their `payout_id` to the new `payoutId`. This "locks" them and prevents them from being included in future payouts.
+ * **e. Commit Transaction:** Commit the database transaction.
+ * **f. Process the Payout (Asynchronously):**
+ * The actual on-chain transaction should be handled by a separate, asynchronous process or queue. For this prompt, we can simulate it in a `setTimeout`.
+ * This background job will:
+ 1. Construct the `spl-token` transfer transaction from a platform-owned treasury/hot wallet to the creator's `payout_address`.
+ 2. Sign the transaction with the treasury wallet's key (this key must be securely stored on the server).
+ 3. Send and confirm the transaction.
+ 4. Update the `payouts` record with the `completed` status and the `tx_signature`.
+ * **g. Respond to Client:** Immediately after committing the DB transaction (step e), respond to the client with a success message. Do *not* wait for the on-chain part to finish.
+
+## Code Example (Backend - `/api/dashboard/request-payout.js`)
+
+```javascript
+// --- Inside your API handler ---
+
+const user = await getAuthenticatedUser(req);
+
+// a. Get user and settings
+const payoutSettings = await db.getPayoutSettings(user.id);
+if (!payoutSettings?.payout_address) {
+ return res.status(400).json({ error: 'Payout address not configured.' });
+}
+
+let payoutId;
+try {
+ // b., c., d. Transactional logic
+ await db.transaction(async (trx) => {
+ const earningsToPay = await trx('skill_payment_earnings')
+ .where({ creator_id: user.id, payout_id: null })
+ .select('id', 'net_amount');
+
+ if (earningsToPay.length === 0) {
+ throw new Error('No withdrawable balance.');
+ }
+
+ const totalNetAmount = earningsToPay.reduce((sum, e) => sum + e.net_amount, 0);
+ const currencyMint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; // Assume USDC
+
+ // c. Create Payout Record
+ const [newPayout] = await trx('payouts')
+ .insert({
+ creator_id: user.id,
+ amount: totalNetAmount,
+ currency_mint: currencyMint,
+ destination_address: payoutSettings.payout_address,
+ status: 'pending',
+ })
+ .returning('id');
+ payoutId = newPayout.id;
+
+ // d. Associate Earnings
+ const earningIds = earningsToPay.map(e => e.id);
+ await trx('skill_payment_earnings')
+ .whereIn('id', earningIds)
+ .update({ payout_id: payoutId });
+ });
+
+} catch (error) {
+ return res.status(400).json({ error: error.message });
+}
+
+// f. Trigger async payout processing
+// DO NOT await this. This should be handled by a background worker queue (e.g., BullMQ, Celery).
+// We simulate with a timeout for this example.
+processPayout(payoutId);
+
+// g. Respond to client immediately
+res.status(202).json({ message: 'Payout initiated.', payoutId });
+
+
+// --- In a separate background worker file ---
+async function processPayout(payoutId) {
+ // Fetch payout details, create/sign/send transaction, update status to 'completed'.
+ // This part is complex and involves secure key management for the treasury wallet.
+}
+```
diff --git a/docs/monetization/22-marketplace-analytics-dashboard.md b/docs/monetization/22-marketplace-analytics-dashboard.md
new file mode 100644
index 000000000..1b76301d3
--- /dev/null
+++ b/docs/monetization/22-marketplace-analytics-dashboard.md
@@ -0,0 +1,83 @@
+# Prompt 22: Marketplace Analytics Dashboard
+
+## Objective
+Create a dedicated analytics page for the marketplace that displays key metrics about agent and skill performance.
+
+## Explanation
+To create a healthy and competitive marketplace, creators and the platform administrators need data. This analytics dashboard will provide insights into which agents are most popular, which skills are selling the most, and overall revenue trends. This helps creators understand what the market wants and helps administrators monitor the health of the economy.
+
+## Instructions
+1. **Create a New Page:**
+ * Create a new route and page, e.g., `marketplace/analytics.html`.
+ * Design the layout with charts and data tables.
+
+2. **Backend Analytics Endpoint:**
+ * Create a new API endpoint, `/api/marketplace/analytics`.
+ * This endpoint will perform aggregation queries to calculate stats. It should be restricted to administrators or perhaps a subset of stats could be public.
+ * **Metrics to compute:**
+ * Total marketplace volume (in USD).
+ * Number of unique buyers.
+ * Number of unique sellers (creators with at least one sale).
+ * A time-series chart of daily/weekly sales volume.
+ * Top 10 best-selling agents (by revenue).
+ * Top 10 best-selling skills (by revenue).
+
+3. **Frontend Visualization:**
+ * On the analytics page, fetch data from the new endpoint.
+ * Use a charting library (e.g., Chart.js, which is lightweight) to visualize the time-series data.
+ * Render the "Top 10" lists in styled tables.
+
+## Code Example (Backend Analytics Endpoint - `/api/marketplace/analytics.js`)
+
+```javascript
+import { supabase } from '../../_lib/supabase';
+import { json, error } from '../../_lib/http';
+
+export default async function handler(req, res) {
+ // Add admin authentication check here
+
+ // Example: Fetching top selling skills
+ const { data: topSkills, error: skillsError } = await supabase.rpc('get_top_selling_skills', { limit_count: 10 });
+
+ if (skillsError) {
+ return error(res, 500, 'Failed to calculate analytics.');
+ }
+
+ // Example: Fetching sales volume by day
+ const { data: salesVolume } = await supabase.rpc('get_daily_sales_volume');
+
+ // ...fetch other metrics...
+
+ return json(res, {
+ topSkills,
+ salesVolume,
+ // ...other data...
+ });
+}
+```
+
+## Supabase RPC Function Example (`get_top_selling_skills`)
+
+```sql
+CREATE OR REPLACE FUNCTION get_top_selling_skills(limit_count INT)
+RETURNS TABLE(skill_name TEXT, agent_id UUID, total_revenue BIGINT, total_sales BIGINT) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ ups.skill_name,
+ ups.agent_id,
+ SUM(asp.amount) as total_revenue,
+ COUNT(ups.id) as total_sales
+ FROM
+ user_purchased_skills ups
+ JOIN
+ agent_skill_prices asp ON ups.agent_id = asp.agent_id AND ups.skill_name = asp.skill_name
+ GROUP BY
+ ups.skill_name, ups.agent_id
+ ORDER BY
+ total_revenue DESC
+ LIMIT
+ limit_count;
+END;
+$$ LANGUAGE plpgsql;
+```
diff --git a/docs/monetization/22-responsive-design-payment-modal.md b/docs/monetization/22-responsive-design-payment-modal.md
new file mode 100644
index 000000000..36f3c8db9
--- /dev/null
+++ b/docs/monetization/22-responsive-design-payment-modal.md
@@ -0,0 +1,62 @@
+# Prompt 22: Responsive Design for Payment Modal
+
+## Objective
+Ensure the Solana Pay QR code modal and related monetization UI elements are fully responsive and usable on all screen sizes, especially mobile devices.
+
+## Explanation
+A significant portion of users, especially in the web3 space, may interact with the platform on mobile devices. The payment flow, in particular, is centered around mobile wallets. Therefore, the QR code must be easy to scan and the surrounding information must be legible on small screens.
+
+## Instructions
+1. **Use CSS Media Queries:**
+ * In your `marketplace.css` file, add `@media` queries to adjust the styling of the payment modal for smaller screens.
+
+2. **Adjust Modal Size:**
+ * On mobile, the modal should likely take up the full width and a larger portion of the height of the screen to maximize space for the QR code.
+ * `width: 95vw; max-width: 400px;` is a common pattern.
+
+3. **Optimize QR Code Size:**
+ * The QR code itself needs to be large enough to be easily scannable. You might need to adjust the `size` parameter passed to `createQR` based on the screen width, or simply use a larger default size that also works on desktop.
+
+4. **Layout Changes:**
+ * Consider changing the layout of elements inside the modal on small screens. For example, a two-column layout on desktop might need to stack into a single column on mobile. Use flexbox properties like `flex-direction: column;`.
+
+5. **Test Thoroughly:**
+ * Use your browser's developer tools to simulate various mobile device screen sizes (e.g., iPhone, Android devices) and test the entire purchase flow.
+
+## CSS Example (`marketplace.css`)
+
+```css
+/* Base styles for the payment modal */
+#payment-modal {
+ width: 450px;
+ padding: 24px;
+ border-radius: 12px;
+ /* ... other styles */
+}
+
+.qr-code-container {
+ width: 300px; /* default size */
+ height: 300px;
+ margin: 20px auto;
+}
+
+
+/* Media query for mobile devices */
+@media (max-width: 600px) {
+ #payment-modal {
+ width: 90vw; /* Take up most of the screen width */
+ padding: 16px;
+ }
+
+ .qr-code-container {
+ width: 80vw; /* Make QR code responsive to screen width */
+ height: 80vw;
+ max-width: 280px;
+ max-height: 280px;
+ }
+
+ #payment-modal h2 {
+ font-size: 18px; /* Adjust font sizes for readability */
+ }
+}
+```
diff --git a/docs/monetization/22_skill_subscriptions.md b/docs/monetization/22_skill_subscriptions.md
new file mode 100644
index 000000000..a9fceaa72
--- /dev/null
+++ b/docs/monetization/22_skill_subscriptions.md
@@ -0,0 +1,55 @@
+---
+status: not-started
+last_updated: 2026-05-04
+---
+# Prompt 22: Skill Subscriptions (Recurring Revenue)
+
+## Objective
+Introduce a subscription model for skills, allowing creators to earn recurring revenue. Users can subscribe to a skill for a monthly fee to maintain access.
+
+## Explanation
+One-time purchases are great, but subscriptions provide creators with a predictable income stream and encourage them to keep their skills updated. This is a significant architectural addition, requiring a system to manage subscription state and handle recurring payments. For Solana, we can't use traditional server-side billing, so we'll model it as a system of time-limited access tokens that the user must renew.
+
+## Instructions
+1. **Database Schema for Subscriptions:**
+ * Create a `skill_subscriptions` table:
+ * `id`: Primary key.
+ * `user_id`, `agent_id`, `skill_name`: Foreign keys.
+ * `expires_at`: A timestamp indicating when the current subscription period ends.
+ * `status`: An enum (e.g., `'active'`, `'expired'`, `'cancelled'`).
+ * `last_payment_signature`: The signature of the latest renewal transaction.
+
+2. **Update UI for Price Setting:**
+ * In `agent-edit.html`, allow creators to specify a price as "one-time" or "monthly."
+ * If monthly, they set a monthly price. This gets stored in `agent_skill_prices` with a new column, e.g., `billing_interval: 'monthly'`.
+
+3. **Modify Purchase Flow:**
+ * When a user "subscribes," the purchase flow is the same as a one-time purchase.
+ * However, upon successful confirmation in `purchase-confirm`, a record is created in the `skill_subscriptions` table instead of `user_purchased_skills`. The `expires_at` is set to 30 days from now.
+
+4. **Update Access Control Logic:**
+ * The skill ownership check (`api/chat.js`) must now also check the `skill_subscriptions` table.
+ * If a user has an 'active' subscription and `expires_at` is in the future, they are granted access.
+ * If `expires_at` is in the past, their status should be considered 'expired', and they should be denied access.
+
+5. **Renewal UI:**
+ * In the marketplace UI, if a user has an expired subscription, the "Purchase" button should reappear as "Renew Subscription."
+ * Clicking it triggers the same purchase flow, which, upon confirmation, updates the `expires_at` timestamp for the existing subscription record.
+
+## SQL Example (`skill_subscriptions` table)
+
+```sql
+CREATE TABLE IF NOT EXISTS skill_subscriptions (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ skill_name VARCHAR(255) NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL,
+ status VARCHAR(50) NOT NULL DEFAULT 'active', -- e.g., 'active', 'expired'
+ last_payment_signature VARCHAR(128),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ UNIQUE(user_id, agent_id, skill_name)
+);
+```
diff --git a/docs/monetization/23-e2e-testing-purchase-flow.md b/docs/monetization/23-e2e-testing-purchase-flow.md
new file mode 100644
index 000000000..a4a7852c7
--- /dev/null
+++ b/docs/monetization/23-e2e-testing-purchase-flow.md
@@ -0,0 +1,78 @@
+# Prompt 23: E2E Testing for Purchase Flow
+
+## Objective
+Write an end-to-end (E2E) test using a framework like Playwright or Cypress to simulate and validate the entire skill purchase flow.
+
+## Explanation
+As the monetization feature becomes more complex, manual testing becomes time-consuming and prone to error. An automated E2E test will ensure the core purchase functionality remains stable as we add new features or refactor code. This test will mock the blockchain interaction but validate the entire UI and API flow.
+
+## Instructions
+1. **Set Up the Test Environment:**
+ * Ensure you have Playwright or your chosen E2E testing framework installed and configured in the project.
+ * You will need to set up a test that can handle authentication, likely by pre-setting an auth token in local storage.
+
+2. **Mock the Backend API:**
+ * The test should not make real payments. You need to mock the API endpoints.
+ * Mock `/api/payments/prepare-skill-purchase`: It should return a fake, but correctly structured, Solana Pay transaction response.
+ * Mock `/api/payments/check-purchase-status`: The test should control this endpoint's response, initially returning `{ status: 'pending' }` and later switching to `{ status: 'confirmed' }` to simulate a successful purchase.
+
+3. **Write the Test Script:**
+ * The test should perform the following steps:
+ 1. Navigate to a specific agent's marketplace page.
+ 2. Verify that the "Purchase" button is visible for a paid skill.
+ 3. Click the "Purchase" button.
+ 4. Assert that the payment modal appears and the QR code is rendered.
+ 5. Trigger the mock API to switch to a "confirmed" status.
+ 6. Wait for the polling mechanism to detect the change.
+ 7. Assert that the modal closes automatically.
+ 8. Assert that the "Purchase" button has been replaced with the "Owned" status indicator on the main page.
+
+## Test Script Example (Playwright)
+
+```javascript
+// tests/monetization.spec.ts
+import { test, expect } from '@playwright/test';
+
+test.describe('Skill Purchase Flow', () => {
+ test('should allow a user to successfully purchase a skill', async ({ page }) => {
+ const agentId = 'some-test-agent-id';
+ const skillName = 'TestSkill';
+
+ // Mock the backend APIs before navigating
+ await page.route(`/api/payments/prepare-skill-purchase`, async route => {
+ const json = {
+ transaction: 'fake-serialized-transaction-base64',
+ message: 'Test Purchase',
+ reference: 'test-reference-123',
+ };
+ await route.fulfill({ json });
+ });
+
+ let purchaseStatus = 'pending';
+ await page.route(`/api/payments/check-purchase-status?reference=test-reference-123`, async route => {
+ await route.fulfill({ json: { status: purchaseStatus } });
+ });
+
+ // 1. Navigate to the page
+ await page.goto(`/marketplace/agent/${agentId}`);
+
+ // 2. Find and click the purchase button
+ const purchaseButton = page.locator(`.purchase-skill-btn[data-skill-name="${skillName}"]`);
+ await expect(purchaseButton).toBeVisible();
+ await purchaseButton.click();
+
+ // 3. Assert modal and QR code are visible
+ await expect(page.locator('#payment-modal')).toBeVisible();
+ await expect(page.locator('.qr-code-container svg')).toBeVisible();
+
+ // 4. Simulate the successful payment confirmation
+ purchaseStatus = 'confirmed';
+
+ // 5. Assert that the modal closes and the UI updates
+ await expect(page.locator('#payment-modal')).not.toBeVisible({ timeout: 10000 }); // Wait for poll
+ const ownedIndicator = page.locator(`.skill-owned:has-text("Owned")`);
+ await expect(ownedIndicator).toBeVisible();
+ await expect(purchaseButton).not.toBeVisible();
+ });
+});
+```
diff --git a/docs/monetization/23-email-and-in-app-notifications.md b/docs/monetization/23-email-and-in-app-notifications.md
new file mode 100644
index 000000000..ac2ae83cf
--- /dev/null
+++ b/docs/monetization/23-email-and-in-app-notifications.md
@@ -0,0 +1,70 @@
+# Prompt 23: Email and In-App Notifications
+
+## Objective
+Implement a notification system to alert users and creators about important monetization events, such as a new sale or a subscription renewal.
+
+## Explanation
+To create an engaging user experience, the platform should proactively inform users about events relevant to them. For creators, a "You've made a sale!" notification is highly motivating. For users, a receipt or a reminder about an upcoming subscription renewal is essential. This task involves setting up the infrastructure for both in-app and email notifications.
+
+## Instructions
+1. **Choose a Notification Service:**
+ * For emails, we can integrate a transactional email service like Resend, SendGrid, or Postmark.
+ * For in-app notifications, we'll create a new database table and a UI component.
+
+2. **Database Schema for In-App Notifications:**
+ * Create a `notifications` table.
+ * Columns: `id`, `user_id` (who the notification is for), `type` (e.g., 'sale_made', 'skill_purchased'), `message`, `is_read`, `link_url` (e.g., link to the transaction), `created_at`.
+
+3. **Backend Integration:**
+ * In the backend logic where monetization events occur (e.g., in `verify-purchase.js`), add calls to a new notification helper function.
+ * This function, `createNotification(userId, type, data)`, will:
+ * Insert a record into the `notifications` table.
+ * (Optional) Trigger an email to be sent via the chosen email service.
+
+4. **Frontend UI:**
+ * Add a "notification bell" icon to the main site header.
+ * When clicked, it should show a dropdown or a dedicated page listing the user's unread notifications, fetched from a new `/api/notifications` endpoint.
+ * Clicking a notification should mark it as read and, if it has a `link_url`, navigate the user there.
+
+## Code Example (Backend Notification Trigger)
+
+```javascript
+// /api/_lib/notifications.js
+import { supabase } from './supabase';
+// import { Resend } from 'resend';
+// const resend = new Resend(process.env.RESEND_API_KEY);
+
+export async function createSaleNotification(purchase) {
+ // Notify the creator
+ const creatorMessage = `You sold the skill "${purchase.skillName}" for agent "${purchase.agentName}"!`;
+ await supabase.from('notifications').insert({
+ user_id: purchase.creatorId,
+ type: 'sale_made',
+ message: creatorMessage,
+ link_url: `/marketplace/agents/${purchase.agentId}`
+ });
+ // await resend.emails.send({ ... });
+
+ // Notify the buyer
+ const buyerMessage = `You successfully purchased the skill "${purchase.skillName}".`;
+ await supabase.from('notifications').insert({
+ user_id: purchase.buyerId,
+ type: 'skill_purchased',
+ message: buyerMessage,
+ link_url: `/users/me/library`
+ });
+ // await resend.emails.send({ ... }); // Send receipt
+}
+
+// In /api/marketplace/skills/verify-purchase.js
+// After successfully verifying and recording a purchase...
+import { createSaleNotification } from '../../_lib/notifications';
+
+await createSaleNotification({
+ creatorId: agent.creator_id,
+ buyerId: userId,
+ skillName: skillName,
+ agentName: agent.name,
+ agentId: agentId,
+});
+```
diff --git a/docs/monetization/23-ui-payout-wallet-config.md b/docs/monetization/23-ui-payout-wallet-config.md
new file mode 100644
index 000000000..5f4eb6a64
--- /dev/null
+++ b/docs/monetization/23-ui-payout-wallet-config.md
@@ -0,0 +1,104 @@
+# Prompt 23: UI for Payout Wallet Configuration
+
+## Objective
+Implement the UI and the corresponding backend endpoint for creators to securely save and update their Solana payout wallet address.
+
+## Explanation
+Before creators can receive payouts, they must specify where the funds should be sent. This prompt covers creating a simple form for this purpose and the API to persist this setting.
+
+## Instructions
+1. **Database Schema:**
+ * Ensure your `users` table (or a related `user_settings` table) has a column to store the payout address, e.g., `payout_sol_address` (nullable `VARCHAR`).
+
+2. **File to Edit (Frontend):**
+ * Open `agent-edit.html` and its associated JavaScript. Focus on the "Payout Settings" section of the "Earnings" tab.
+
+3. **Implement Frontend Logic:**
+ * **Display Current Address:** When the earnings tab loads, the data from `/api/dashboard/earnings` should include the user's currently saved `payout_address`. Display this in or below the input field.
+ * **Save Button Event Listener:**
+ * Attach a `click` event listener to the "Save Address" button (`#save-wallet-btn`).
+ * When clicked, get the value from the input field (`#payout-wallet-input`).
+ * **Validation:** Perform basic client-side validation. A simple check is to ensure the address is between 32 and 44 characters and contains only Base58 characters. For a more robust check, you could use a library.
+ * If valid, make a `POST` request to a new `/api/dashboard/payout-settings` endpoint.
+ * Display status messages (e.g., "Saving...", "Saved!", "Invalid address.") in the status element (`#payout-wallet-status`).
+
+4. **Create Backend Endpoint (Backend):**
+ * Create the new endpoint: `POST /api/dashboard/payout-settings`.
+ * **Authentication:** Ensure the user is authenticated.
+ * **Validation:**
+ * The request body should contain the `address`.
+ * Perform robust server-side validation to ensure it's a valid Solana public key. You can do this by trying to construct a `new PublicKey(address)` from `@solana/web3.js` inside a try-catch block.
+ * **Database Update:** Update the `payout_sol_address` column for the authenticated user in your `users` (or `user_settings`) table.
+ * Return a success message.
+
+## Code Example (Frontend - `agent-edit.html` script)
+
+```javascript
+// In the script for agent-edit.html
+
+const saveWalletBtn = document.getElementById('save-wallet-btn');
+const walletInput = document.getElementById('payout-wallet-input');
+const walletStatus = document.getElementById('payout-wallet-status');
+
+saveWalletBtn.addEventListener('click', async () => {
+ const address = walletInput.value.trim();
+
+ // Basic client-side validation
+ if (address.length < 32 || address.length > 44) {
+ walletStatus.textContent = 'Invalid address length.';
+ return;
+ }
+
+ walletStatus.textContent = 'Saving...';
+ saveWalletBtn.disabled = true;
+
+ try {
+ const res = await fetch('/api/dashboard/payout-settings', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ address: address })
+ });
+
+ if (!res.ok) {
+ const { error } = await res.json();
+ throw new Error(error || 'Failed to save.');
+ }
+
+ walletStatus.textContent = 'Saved!';
+ } catch (err) {
+ walletStatus.textContent = `Error: ${err.message}`;
+ } finally {
+ saveWalletBtn.disabled = false;
+ }
+});
+```
+
+## Code Example (Backend - `/api/dashboard/payout-settings.js`)
+
+```javascript
+import { PublicKey } from '@solana/web3.js';
+
+// --- Inside your API handler ---
+
+const { address } = req.body;
+const user = await getAuthenticatedUser(req);
+
+// Server-side validation
+try {
+ // This will throw an error if the address is not a valid base58 string
+ new PublicKey(address);
+} catch (error) {
+ return res.status(400).json({ error: 'Invalid Solana address format.' });
+}
+
+try {
+ // Update the user's record in the database
+ await db('users')
+ .where({ id: user.id })
+ .update({ payout_sol_address: address });
+
+ res.status(200).json({ message: 'Payout address updated.' });
+} catch (dbError) {
+ res.status(500).json({ error: 'Database error.' });
+}
+```
diff --git a/docs/monetization/23_free_trials.md b/docs/monetization/23_free_trials.md
new file mode 100644
index 000000000..5f1d3e478
--- /dev/null
+++ b/docs/monetization/23_free_trials.md
@@ -0,0 +1,64 @@
+---
+status: not-started
+last_updated: 2026-05-04
+---
+# Prompt 23: Free Trials for Subscriptions
+
+## Objective
+Allow creators to offer a limited-time free trial for their subscription-based skills to attract more users.
+
+## Explanation
+Free trials are a proven strategy for converting users to paid subscribers. This feature lets a user try a skill for a set period (e.g., 7 days) without paying. After the trial, they must subscribe to retain access.
+
+## Instructions
+1. **Update Price Setting UI:**
+ * In `agent-edit.html`, next to the monthly subscription price setting, add a checkbox and an input for "Offer free trial" and "Trial days".
+
+2. **Database Changes:**
+ * In the `agent_skill_prices` table, add a new column, `trial_days` (integer).
+ * In the `skill_subscriptions` table, add a `is_in_trial` boolean flag.
+
+3. **Implement Trial Activation Flow:**
+ * In the marketplace UI, for a skill with a trial, the button should say "Start Free Trial."
+ * Clicking this button will NOT trigger a payment transaction. Instead, it will call a new, simple API endpoint, e.g., `POST /api/skills/start-trial`.
+ * This endpoint verifies the user hasn't already used a trial for this skill.
+ * It then creates a record in the `skill_subscriptions` table with `is_in_trial = true`, `status = 'active'`, and `expires_at` set to `NOW() + trial_days`.
+
+4. **Update Access Control Logic:**
+ * The existing subscription check already verifies `status = 'active'` and `expires_at` > `NOW()`, so it will automatically grant access to users in their trial period.
+
+5. **UI for Conversion:**
+ * When a user is in a trial, the marketplace UI for that skill should change. Instead of "Purchase," it should show a message like "Trial active: X days remaining" and a button to "Subscribe Now."
+ * If the trial expires, the button reverts to "Subscribe." The access control logic will automatically block them until they pay.
+
+## Code Example (Trial Activation Endpoint)
+
+```javascript
+// POST /api/skills/start-trial
+export default wrap(async (req, res) => {
+ // ... auth, validation for agent_id, skill_name
+ const user = await getSessionUser(req);
+
+ // 1. Check if skill offers a trial
+ const [skillPrice] = await sql`
+ SELECT trial_days FROM agent_skill_prices
+ WHERE agent_id = ${agent_id} AND skill_name = ${skill_name} AND trial_days > 0
+ `;
+ if (!skillPrice) return error(res, 400, 'no_trial_offered');
+
+ // 2. Check if user already had a subscription/trial for this skill
+ const [existingSub] = await sql`
+ SELECT id FROM skill_subscriptions WHERE ...
+ `;
+ if (existingSub) return error(res, 409, 'trial_already_used');
+
+ // 3. Create the trial subscription record
+ const expiresAt = new Date(Date.now() + skillPrice.trial_days * 24 * 60 * 60 * 1000);
+ await sql`
+ INSERT INTO skill_subscriptions (user_id, agent_id, skill_name, expires_at, status, is_in_trial)
+ VALUES (${user.id}, ${agent_id}, ${skill_name}, ${expiresAt}, 'active', true)
+ `;
+
+ return json(res, 201, { success: true, expires_at: expiresAt });
+});
+```
diff --git a/docs/monetization/24-analytics-and-tracking.md b/docs/monetization/24-analytics-and-tracking.md
new file mode 100644
index 000000000..679148791
--- /dev/null
+++ b/docs/monetization/24-analytics-and-tracking.md
@@ -0,0 +1,82 @@
+# Prompt 24: Analytics and Tracking
+
+## Objective
+Integrate analytics events to track key user interactions throughout the monetization funnel, providing insights into user behavior and conversion rates.
+
+## Explanation
+To understand how users are interacting with the new payment features and to identify potential drop-off points, we need to track key events. This data is invaluable for making informed decisions on how to improve the feature. We can use a service like Segment, Amplitude, or a simple internal logging system.
+
+## Instructions
+1. **Choose an Analytics Provider:**
+ * Select and set up an analytics service. For this example, we'll assume a simple global `analytics.track()` function is available (often provided by a Segment or similar script).
+
+2. **Define Key Events:**
+ * Identify the most important events to track in the monetization funnel:
+ * `Skill Purchase Initiated`: Fired when a user clicks the "Purchase" button.
+ * `Payment QR Code Displayed`: Fired when the QR code is successfully rendered.
+ * `Skill Purchase Succeeded`: Fired when the frontend confirms a successful purchase.
+ * `Skill Purchase Failed`: Fired when any error occurs during the process.
+ * `Skill Prices Saved`: Fired when a creator successfully saves new prices.
+
+3. **Implement Tracking Calls (Frontend):**
+ * In your frontend JavaScript (`src/marketplace.js`, `src/agent-edit.js`), call `analytics.track()` at the appropriate points in the code.
+ * Include relevant properties with each event, such as `agentId`, `skillName`, `price`, and `currency`.
+
+## Code Example (Frontend - `src/marketplace.js`)
+
+```javascript
+// This is a placeholder for your analytics library's API
+// e.g., window.analytics.track(...)
+const trackEvent = (eventName, properties) => {
+ console.log('[Analytics]', eventName, properties);
+ // In a real app, this would send data to Segment, Amplitude, etc.
+ if (window.analytics) {
+ window.analytics.track(eventName, properties);
+ }
+};
+
+// In handlePurchaseClick function
+async function handlePurchaseClick(event) {
+ // ...
+ const skillName = button.dataset.skillName;
+ const agentId = /* ... */;
+ const price = /* ... get price ... */;
+
+ // 1. Track when the purchase is initiated
+ trackEvent('Skill Purchase Initiated', {
+ agentId: agentId,
+ skillName: skillName,
+ price: price,
+ currency: 'USDC',
+ });
+
+ try {
+ // ... (API call to prepare purchase)
+
+ // 2. Track when the QR code is shown
+ trackEvent('Payment QR Code Displayed', {
+ agentId: agentId,
+ skillName: skillName,
+ });
+
+ // ... (Polling logic)
+ if (status === 'confirmed') {
+ // 3. Track successful purchase
+ trackEvent('Skill Purchase Succeeded', {
+ agentId: agentId,
+ skillName: skillName,
+ price: price,
+ });
+ }
+
+ } catch (error) {
+ // 4. Track failure
+ trackEvent('Skill Purchase Failed', {
+ agentId: agentId,
+ skillName: skillName,
+ error: error.message,
+ });
+ // ...
+ }
+}
+```
diff --git a/docs/monetization/24-end-to-end-monetization-testing.md b/docs/monetization/24-end-to-end-monetization-testing.md
new file mode 100644
index 000000000..3dd6e3fc1
--- /dev/null
+++ b/docs/monetization/24-end-to-end-monetization-testing.md
@@ -0,0 +1,79 @@
+# Prompt 24: End-to-End Monetization Testing
+
+## Objective
+Write a suite of end-to-end (E2E) tests to validate the entire skill monetization flow, from a user connecting their wallet to a creator seeing the sale in their dashboard.
+
+## Explanation
+The monetization flow is complex, involving multiple frontend components, backend APIs, database interactions, and on-chain transactions. Manual testing is error-prone and time-consuming. An automated E2E test suite using a framework like Playwright is essential to ensure the system is robust, secure, and reliable, especially before and after deploying changes.
+
+## Instructions
+1. **Set up Playwright:**
+ * If not already in the project, add Playwright: `npm install -D playwright`.
+ * Configure it in `playwright.config.js`. You'll need to set up a base URL and potentially a test user account.
+
+2. **Set up a Test Wallet:**
+ * The tests will need a Solana wallet with devnet funds. The private key for this test wallet can be stored as a secret environment variable and used to programmatically sign transactions during the test run.
+
+3. **Write Test Scenarios:**
+ * Create a new test file, e.g., `tests/monetization.spec.js`.
+ * **Scenario 1: One-Time Purchase**
+ * `test.beforeAll()`: Create a test agent and a test creator user via API. Set a price on one of the agent's skills.
+ * Test that a guest user cannot purchase the skill.
+ * Test that a logged-in user can connect their wallet, navigate to the agent, click the skill, confirm, and "sign" the transaction. (Playwright can mock the wallet interaction).
+ * Test that after purchase, the skill appears as "owned".
+ * Test that the creator can log in and see the sale in their earnings dashboard.
+ * **Scenario 2: Subscription**
+ * Similar setup, but test subscribing to a tier.
+ * Test that the user gains access to all skills within that tier.
+ * Test that access is revoked after the subscription period ends (requires time-mocking or a special test setup).
+
+## Playwright Test Example (`tests/monetization.spec.js`)
+
+```javascript
+import { test, expect } from '@playwright/test';
+import { login, createTestAgent } from './test-helpers'; // Assume helper functions exist
+
+test.describe('Skill Monetization E2E', () => {
+ let agentId;
+ let creatorToken;
+ const skillName = 'premium_skill';
+
+ test.beforeAll(async ({ request }) => {
+ // Create a creator and an agent with a priced skill
+ const creator = await login(request, 'creator');
+ creatorToken = creator.token;
+ const agent = await createTestAgent(request, creatorToken, {
+ skills: [{ name: skillName }],
+ prices: { [skillName]: { amount: 1000000, currency_mint: 'USDC_MINT' } }
+ });
+ agentId = agent.id;
+ });
+
+ test('a user can purchase a skill', async ({ page, context }) => {
+ // Login as a buyer
+ const buyer = await login(context);
+
+ // TODO: Inject a mock wallet into the browser context for the buyer
+ // This is an advanced setup but crucial for testing.
+
+ await page.goto(`/marketplace/agents/${agentId}`);
+
+ // Find the skill and its price badge
+ const skillEntry = page.locator('.skill-entry', { hasText: skillName });
+ await expect(skillEntry.locator('.price-paid')).toBeVisible();
+
+ // Click to open purchase modal
+ await skillEntry.click();
+ await expect(page.locator('#purchaseModal')).toBeVisible();
+
+ // Click "Buy Now"
+ await page.locator('#confirmPurchaseBtn').click();
+
+ // The test would now need to handle the mock wallet signing prompt
+ // and wait for the post-purchase confirmation.
+
+ // Assert that the UI updates to show ownership
+ await expect(page.locator('.skill-entry', { hasText: skillName }).locator('.owned-badge')).toBeVisible();
+ });
+});
+```
diff --git a/docs/monetization/24-subscription-model.md b/docs/monetization/24-subscription-model.md
new file mode 100644
index 000000000..78efb3e29
--- /dev/null
+++ b/docs/monetization/24-subscription-model.md
@@ -0,0 +1,82 @@
+# Prompt 24: Subscription Pricing Model for Skills
+
+## Objective
+Extend the monetization system to support a subscription model, where a user pays a recurring fee for access to all of an agent's paid skills.
+
+## Explanation
+A one-time payment per skill is a good start, but subscriptions offer creators a predictable revenue stream and users a more convenient way to access a suite of premium skills. This prompt covers the necessary database and backend changes to introduce a subscription option.
+
+## Instructions
+1. **Database Schema Changes:**
+ * **`agents` table:** Add columns to the `agents` table (or a new `agent_subscriptions` table) to store subscription pricing:
+ * `subscription_amount` (BIGINT)
+ * `subscription_interval` (VARCHAR, e.g., 'month')
+ * `subscription_currency_mint` (VARCHAR)
+ * **`user_agent_subscriptions` table:** Create a new table to track active user subscriptions.
+ * `id`: Primary key.
+ * `user_id`: Foreign key to `users`.
+ * `agent_id`: Foreign key to `agents`.
+ * `status`: VARCHAR (e.g., 'active', 'cancelled', 'past_due').
+ * `current_period_ends_at`: TIMESTAMPTZ.
+ * `created_at`, `updated_at`.
+
+2. **UI for Creators:**
+ * In `agent-edit.html`, under the new "Earnings" or a dedicated "Monetization" tab, add a form for creators to enable and configure subscriptions for their agent.
+ * This includes inputs for price, currency, and interval (e.g., a dropdown for "monthly").
+
+3. **Modify Skill Access Check:**
+ * Update the `checkForValidSkillGrant` logic (from Prompt 15).
+ * Before checking for individual skill grants in `skill_access_grants`, it must **first** check if the user has an `active` subscription to the agent in the `user_agent_subscriptions` table where `current_period_ends_at` is in the future.
+ * If an active subscription exists, the check should immediately return `true`, granting access to all of the agent's skills.
+
+4. **Subscription Payment Flow:**
+ * Create a new "Subscribe" button on the agent's detail page in the marketplace.
+ * This will trigger a new payment flow, similar to the single-skill payment:
+ * A new "prepare subscription" endpoint that creates a transaction for the subscription amount.
+ * A "confirm subscription" endpoint that verifies the payment and creates the initial record in `user_agent_subscriptions`.
+
+5. **Recurring Billing (Advanced):**
+ * True recurring billing on Solana is complex. For this prompt, the focus is on a manual renewal model. The user's subscription is valid until `current_period_ends_at`.
+ * A separate, more advanced feature would involve setting up a cron job or on-chain program to handle automatic renewals.
+
+## Code Example (Backend - Skill Access Check Logic)
+
+```javascript
+// The updated access check logic
+
+async function checkForAccess({ userId, agentId, skillName }) {
+ // 1. Check for an active agent-level subscription first
+ const activeSubscription = await db('user_agent_subscriptions')
+ .where({
+ user_id: userId,
+ agent_id: agentId,
+ status: 'active',
+ })
+ .where('current_period_ends_at', '>', db.fn.now())
+ .first();
+
+ if (activeSubscription) {
+ return true; // Subscription grants access to all skills
+ }
+
+ // 2. If no subscription, check for a specific, single-skill grant
+ const skillGrant = await db('skill_access_grants')
+ .where({
+ user_id: userId,
+ agent_id: agentId,
+ skill_name: skillName,
+ })
+ .where(builder => {
+ builder.where('expires_at', '>', db.fn.now())
+ .orWhere('uses_left', '>', 0);
+ })
+ .first();
+
+ if (skillGrant) {
+ // Decrement uses_left if applicable (as in Prompt 15)
+ return true;
+ }
+
+ return false;
+}
+```
diff --git a/docs/monetization/24_creator_analytics.md b/docs/monetization/24_creator_analytics.md
new file mode 100644
index 000000000..ce4b0e4f2
--- /dev/null
+++ b/docs/monetization/24_creator_analytics.md
@@ -0,0 +1,62 @@
+---
+status: not-started
+last_updated: 2026-05-04
+---
+# Prompt 24: Analytics for Creators
+
+## Objective
+Provide creators with analytics on how users are interacting with their paid skills, helping them understand what's popular and what's not.
+
+## Explanation
+Beyond sales data, creators need insight into skill usage to improve their offerings. We will track every time a paid skill is executed and present this data in the creator dashboard.
+
+## Instructions
+1. **Database Schema for Skill Usage:**
+ * Create a new table `skill_usage_logs`.
+ * Columns: `id`, `user_id`, `agent_id`, `skill_name`, `created_at`, `status` ('success' or 'failure'), `execution_time_ms`.
+
+2. **Log Skill Executions:**
+ * In the main skill execution API (`api/chat.js`), after the ownership/access control check passes, add a logging step.
+ * Before executing the skill, record the start time.
+ * After execution, record the end time and whether it succeeded or failed.
+ * Asynchronously (to avoid slowing down the chat response), insert a new record into the `skill_usage_logs` table with this information.
+
+3. **Backend API for Analytics:**
+ * Create a new endpoint, `GET /api/creators/skill-analytics`.
+ * This endpoint will query the `skill_usage_logs` table for agents owned by the current user.
+ * It should aggregate the data to provide metrics like:
+ * Total usage count per skill.
+ * Unique users per skill.
+ * Success/failure rate per skill.
+ * Average execution time per skill.
+
+4. **Frontend Dashboard UI:**
+ * In `creator-dashboard.html`, add a new section for "Skill Analytics."
+ * Fetch data from the new analytics endpoint.
+ * Display the aggregated data in a table. This gives creators a clear overview of which of their skills are most used, most reliable, and fastest.
+ * Optionally, add charts to visualize usage trends over time.
+
+## Code Example (Logging in `api/chat.js`)
+
+```javascript
+// ... after access control checks pass
+const startTime = Date.now();
+let status = 'success';
+let result;
+
+try {
+ result = await executeSkill(skillName, ...);
+} catch (e) {
+ status = 'failure';
+ throw e; // Re-throw the error to the user
+} finally {
+ const executionTimeMs = Date.now() - startTime;
+ // Log asynchronously without waiting
+ sql`
+ INSERT INTO skill_usage_logs (user_id, agent_id, skill_name, status, execution_time_ms)
+ VALUES (${userId}, ${agentId}, ${skillName}, ${status}, ${executionTimeMs})
+ `.catch(dbErr => console.error("Failed to log skill usage:", dbErr));
+}
+
+return result;
+```
diff --git a/docs/monetization/25-creator-documentation.md b/docs/monetization/25-creator-documentation.md
new file mode 100644
index 000000000..5fb037697
--- /dev/null
+++ b/docs/monetization/25-creator-documentation.md
@@ -0,0 +1,80 @@
+# Prompt 25: Documentation for Creators
+
+## Objective
+Create a well-written documentation page that explains the monetization features to agent creators, covering how to set prices, how payouts work, and the platform fees.
+
+## Explanation
+To encourage adoption of the new monetization features, we need to provide clear and comprehensive documentation for our creators. This page should be the go-to resource for any creator looking to start selling their skills.
+
+## Instructions
+1. **Create a New Docs Page:**
+ * In the `docs/` directory, create a new file, e.g., `monetization.md` or `selling-skills.md`.
+ * Add a link to this new page in your main documentation navigation.
+
+2. **Write the Content:**
+ * Structure the document with clear headings.
+ * **Introduction:** Briefly explain the opportunity for creators to earn revenue.
+ * **Getting Started:** A step-by-step guide:
+ 1. "Set up your Payout Wallet": Explain where to find this setting in their dashboard and why it's important. Include a screenshot.
+ 2. "Pricing Your Skills": Show them where to go in the agent editor to set prices. Explain that a price of 0 means the skill is free.
+ * **How Payouts Work:**
+ * Explain that payments are made instantly on the Solana blockchain.
+ * Clarify that funds are sent directly to their configured payout wallet.
+ * **Platform Fees:**
+ * Be transparent about the platform fee. State the percentage clearly (e.g., "three.ws takes a 5% platform fee on every sale.").
+ * Explain that this fee is automatically deducted from the transaction.
+ * **FAQ Section:**
+ * "What currency can I sell in?" (Initially, just USDC).
+ * "When do I get paid?" (Instantly).
+ * "Where can I see my sales?" (Link to their Transaction History dashboard).
+
+3. **Review and Publish:**
+ * Read through the documentation to ensure it's clear, concise, and free of jargon.
+ * Publish the page so it's accessible to creators.
+
+## Markdown Example (`docs/selling-skills.md`)
+
+```markdown
+# Monetizing Your Agent's Skills
+
+Welcome, creator! This guide will walk you through setting up your account to sell your agent's unique skills on the marketplace.
+
+## How It Works
+
+Our platform allows you to set a price for any skill your agent possesses. When a user wants to unlock that capability, they can purchase it directly from your agent's page. Payments are handled instantly and securely on the Solana blockchain.
+
+## Getting Started: 2 Simple Steps
+
+### 1. Set Your Payout Wallet
+
+Before you can receive payments, you need to tell us where to send the funds.
+
+- Go to your **Dashboard**.
+- Navigate to the **Settings** tab.
+- In the "Payout Wallet" section, enter your Solana public key. This is where all your earnings will be sent.
+- Click "Save".
+
+![Screenshot of payout wallet setting](./images/payout-wallet-setting.png)
+
+### 2. Price Your Skills
+
+Now you're ready to set prices.
+
+- Go to **My Agents** and select the agent you wish to edit.
+- In the agent editor, find the "Skills" section.
+- Next to each skill, you'll see an input field for the price in USDC.
+- To make a skill free, simply leave the price as 0.
+- Click "Save Prices" when you're done.
+
+## Platform Fees
+
+three.ws takes a 5% platform fee on every sale. This fee is automatically deducted from the purchase amount during the transaction. For example, if you price a skill at 1.00 USDC, you will receive 0.95 USDC.
+
+## Frequently Asked Questions
+
+**Q: When do I get paid?**
+A: Instantly. The payment is sent to your wallet as soon as the user's transaction is confirmed on the blockchain.
+
+**Q: Where can I track my sales?**
+A: You can see a full list of all your sales in the "Transaction History" section of your dashboard.
+```
diff --git a/docs/monetization/25-documentation-for-creators.md b/docs/monetization/25-documentation-for-creators.md
new file mode 100644
index 000000000..1cd337977
--- /dev/null
+++ b/docs/monetization/25-documentation-for-creators.md
@@ -0,0 +1,71 @@
+# Prompt 25: Documentation for Creators
+
+## Objective
+Create a comprehensive guide for agent creators that explains how to use the monetization features, including setting up their payout wallet, pricing their skills, and understanding the fee structure.
+
+## Explanation
+To ensure a successful launch of the monetization features, creators need clear and accessible documentation. A well-written guide reduces support requests and empowers creators to get started quickly. This document will be a new page in the main `docs` section of the website.
+
+## Instructions
+1. **Create a New Markdown File:**
+ * Create `docs/for-creators/monetization.md`.
+
+2. **Write the Content:**
+ * Structure the document with clear headings and a logical flow.
+ * **Introduction:** Briefly explain the benefits of monetizing agent skills.
+ * **Getting Started (Checklist):**
+ 1. Create an Agent.
+ 2. Set up your Payout Wallet.
+ 3. Price your Skills.
+ 4. Publish your Agent.
+ * **Payout Wallet Setup:**
+ * Provide a step-by-step guide on where to find the monetization dashboard.
+ * Explain the importance of using a secure, self-custody Solana wallet.
+ * Show a screenshot of the input field.
+ * **Pricing Models:**
+ * Explain the "One-Time Purchase" model.
+ * Explain the "Subscription" model and how tiers work.
+ * Explain the "Pay-per-call" model for usage-based skills.
+ * Provide best-practice recommendations for pricing.
+ * **Fee Structure:**
+ * Be transparent about any platform fees. For example: "The platform takes a 5% fee on all primary sales to support development and maintain the marketplace."
+ * Explain how Solana network fees work.
+ * **Viewing Earnings:**
+ * Guide the user through the Earnings Dashboard, explaining each metric.
+ * **FAQ Section:**
+ * "How often are payouts processed?"
+ * "What currencies are supported?"
+ * "Can I change the price of a skill after it's published?"
+
+3. **Link to the New Doc:**
+ * Add a link to this new documentation page from the creator dashboard UI to make it easily discoverable.
+
+## Excerpt from `monetization.md`
+
+```markdown
+---
+title: Monetizing Your Agent
+description: A guide for creators on how to sell access to their agent's skills on the marketplace.
+---
+
+# Monetizing Your Agent
+
+Welcome, creator! The three.ws platform provides powerful tools to help you earn revenue from the unique skills you build for your AI agents. This guide will walk you through the entire process, from setting up your wallet to understanding your earnings.
+
+## How It Works
+
+You can monetize your agent's skills in three ways:
+
+1. **One-Time Purchase:** Users pay once to unlock permanent access to a specific skill.
+2. **Subscriptions:** Users pay a recurring fee (e.g., monthly) for access to a bundle of skills defined in a "tier."
+3. **Pay-per-Call:** For resource-intensive skills, you can charge users a small amount for each time they use the skill.
+
+## Getting Started: Your 4-Step Checklist
+
+1. **Have an Agent:** You need an agent with at least one custom skill. You can create one in the [Agent Editor](/agent-edit).
+2. **Set Your Payout Wallet:** Go to the "Monetization" tab in the editor and enter your Solana wallet address. This is where your earnings will be sent.
+3. **Price Your Skills:** Use the tools in the Monetization tab to set prices for individual skills or group them into subscription tiers.
+4. **Publish:** Once your agent is public in the marketplace, users can start buying your skills!
+
+... (continue with detailed sections) ...
+```
diff --git a/docs/monetization/25-user-purchases-page.md b/docs/monetization/25-user-purchases-page.md
new file mode 100644
index 000000000..244b8ac1e
--- /dev/null
+++ b/docs/monetization/25-user-purchases-page.md
@@ -0,0 +1,116 @@
+# Prompt 25: User-Facing "My Purchased Skills" Page
+
+## Objective
+Create a new page for authenticated users where they can view all the premium skills and agent subscriptions they have purchased.
+
+## Explanation
+Users need a central place to see what premium content they have access to, when it expires, or how many uses are left. This page improves transparency and helps users manage their purchases.
+
+## Instructions
+1. **Create New Frontend Page:**
+ * Create a new HTML file, e.g., `purchases.html`.
+ * Add basic HTML structure and link to your standard CSS and a new JavaScript file, e.g., `src/purchases.js`.
+ * Add a link to this new page in the main user navigation menu (e.g., in the user dropdown after they log in).
+
+2. **Create Backend Endpoint:**
+ * Create a new authenticated endpoint: `GET /api/users/my-purchases`.
+ * This endpoint should query two tables for the currently logged-in user:
+ * **`skill_access_grants`**: Fetch all active grants (not expired, or uses > 0). Join with the `agents` table to get agent names.
+ * **`user_agent_subscriptions`**: Fetch all active subscriptions. Join with `agents` to get agent names.
+ * Return a JSON object containing two arrays: `skill_grants` and `subscriptions`.
+
+3. **Implement Frontend Logic:**
+ * In `src/purchases.js`, on page load, make a request to the `/api/users/my-purchases` endpoint.
+ * **Render Subscriptions:**
+ * Create a section for "Active Subscriptions".
+ * Iterate through the `subscriptions` array and render a card for each one, showing:
+ * Agent Name (linked to the agent's page).
+ * "Access until [formatted date]".
+ * **Render Skill Grants:**
+ * Create a section for "Individual Skill Purchases".
+ * Iterate through the `skill_grants` array and render a card or table row for each, showing:
+ * Skill Name.
+ * Agent Name.
+ * Access status (e.g., "Expires on [date]" or "[N] uses left").
+
+## Code Example (Backend - `/api/users/my-purchases.js`)
+
+```javascript
+// --- Inside your API handler ---
+
+const user = await getAuthenticatedUser(req);
+
+const skill_grants = await db('skill_access_grants as grants')
+ .join('agents', 'agents.id', 'grants.agent_id')
+ .where('grants.user_id', user.id)
+ .where(q => {
+ q.where('grants.expires_at', '>', db.fn.now())
+ .orWhere('grants.uses_left', '>', 0);
+ })
+ .select(
+ 'agents.name as agent_name',
+ 'agents.id as agent_id',
+ 'grants.skill_name',
+ 'grants.expires_at',
+ 'grants.uses_left'
+ );
+
+const subscriptions = await db('user_agent_subscriptions as subs')
+ .join('agents', 'agents.id', 'subs.agent_id')
+ .where({
+ 'subs.user_id': user.id,
+ 'subs.status': 'active'
+ })
+ .where('subs.current_period_ends_at', '>', db.fn.now())
+ .select(
+ 'agents.name as agent_name',
+ 'agents.id as agent_id',
+ 'subs.current_period_ends_at'
+ );
+
+res.status(200).json({ skill_grants, subscriptions });
+```
+
+## Code Example (Frontend - `purchases.html` + `src/purchases.js`)
+
+```html
+<!-- purchases.html -->
+<body>
+ <!-- Header/Nav -->
+ <main class="container">
+ <h1>My Purchases</h1>
+
+ <h2>Active Subscriptions</h2>
+ <div id="subscriptions-list" class="purchase-list">
+ <p>Loading...</p>
+ </div>
+
+ <h2>Individual Skills</h2>
+ <div id="skills-list" class="purchase-list">
+ <p>Loading...</p>
+ </div>
+ </main>
+ <!-- Footer -->
+ <script type="module" src="/src/purchases.js"></script>
+</body>
+```
+
+```javascript
+// src/purchases.js
+
+function render(data) {
+ const subsContainer = document.getElementById('subscriptions-list');
+ // ... logic to map over data.subscriptions and render HTML ...
+
+ const skillsContainer = document.getElementById('skills-list');
+ // ... logic to map over data.skill_grants and render HTML ...
+ // For each grant, display either expires_at or uses_left.
+}
+
+fetch('/api/users/my-purchases')
+ .then(res => res.json())
+ .then(render)
+ .catch(err => {
+ document.querySelector('main').innerHTML = 'Error loading your purchases.';
+ });
+```
diff --git a/docs/prompts/monetization/05-unlock-skill-after-purchase.md b/docs/prompts/monetization/05-unlock-skill-after-purchase.md
new file mode 100644
index 000000000..2451d8ad9
--- /dev/null
+++ b/docs/prompts/monetization/05-unlock-skill-after-purchase.md
@@ -0,0 +1,57 @@
+---
+status: not-started
+---
+# Prompt 5: Unlock Skill After Purchase
+
+## Objective
+Ensure that once a skill is purchased and verified, the user gains immediate access to use it with the agent.
+
+## Explanation
+The final step of the core purchase flow is to "unlock" the skill. This involves updating the application's state to reflect the new ownership and making sure that the agent's runtime can now execute this skill for the user.
+
+## Instructions
+1. **Modify Skill Execution Logic:**
+ * Locate the core logic where an agent's skill is invoked by a user. This might be in the `Runtime` class or a similar agent-brain module.
+ * Before executing a skill, add a check:
+ * Is the skill priced?
+ * If so, does the current user own it?
+
+2. **Create an Ownership Check API:**
+ * Create a reusable backend function or endpoint, e.g., `hasSkillAccess(userId, agentId, skillName)`.
+ * This function should query your database (`skill_purchases` table) to see if a `completed` purchase record exists for that user and skill.
+ * The skill execution logic will call this function. If the user doesn't have access, the skill execution should fail with an informative error message like "You must purchase this skill to use it."
+
+3. **Real-time UI Updates:**
+ * Ensure that when the payment verification poll succeeds (from Prompt 4), the frontend state is updated immediately.
+ * The `ownedSkills` set from Prompt 2 should be updated with the newly purchased skill name.
+ * The UI should automatically re-render, changing the "Purchase" button to an "Owned" badge without requiring a page reload.
+
+## Code Example (Backend - Agent Runtime)
+```javascript
+// Inside the skill execution logic of the agent's brain
+
+async function executeSkill(userId, agentId, skillName, args) {
+ const skill = getSkillDefinition(skillName);
+ if (!skill) {
+ throw new Error('Skill not found.');
+ }
+
+ // Check if the skill is priced
+ const priceInfo = await db.getSkillPrice(agentId, skillName);
+
+ if (priceInfo) {
+ // If it's a paid skill, verify ownership
+ const hasAccess = await db.hasSkillAccess(userId, agentId, skillName);
+ if (!hasAccess) {
+ // Return a message to the user instead of throwing an error
+ return {
+ output: `You have not purchased the "${skillName}" skill. Please purchase it from the marketplace to use it.`,
+ isError: true,
+ };
+ }
+ }
+
+ // --- If checks pass, proceed with skill execution ---
+ return skill.execute(args);
+}
+```
diff --git a/docs/prompts/monetization/06-user-purchased-skills-api.md b/docs/prompts/monetization/06-user-purchased-skills-api.md
new file mode 100644
index 000000000..e189266be
--- /dev/null
+++ b/docs/prompts/monetization/06-user-purchased-skills-api.md
@@ -0,0 +1,59 @@
+---
+status: not-started
+---
+# Prompt 6: User's Purchased Skills API and UI
+
+## Objective
+Create a dedicated API endpoint and a new UI section in the user's dashboard to display all the skills they have purchased across all agents.
+
+## Explanation
+Users need a central place to see all their purchased assets. This enhances the user experience by providing a clear record of their purchases and reinforces the value of their account on the platform.
+
+## Instructions
+1. **Create Backend API Endpoint:**
+ * Create a new endpoint, e.g., `GET /api/users/me/skills`.
+ * This endpoint should be authenticated and retrieve the current user's ID.
+ * Query the `skill_purchases` table for all `completed` purchases made by the user.
+ * Join the data with the `agents` and `skills` tables to return rich information for each purchase, such as the skill name, the agent it belongs to, the agent's avatar, and the purchase date.
+
+2. **Create Dashboard Page:**
+ * Create a new HTML file for the dashboard page, e.g., `dashboard.html`, if it doesn't exist.
+ * Add a new section or tab to this page titled "My Purchased Skills".
+
+3. **Fetch and Render Skills:**
+ * In the corresponding JavaScript file for the dashboard (`dashboard.js`), fetch the data from the `/api/users/me/skills` endpoint when the page loads.
+ * Render the purchased skills in a user-friendly list or grid format.
+ * Each item should display the skill name, the agent's name, and an avatar, and link back to that agent's detail page in the marketplace.
+
+## Code Example (Frontend - `dashboard.js`)
+```javascript
+async function renderPurchasedSkills() {
+ const container = document.getElementById('purchased-skills-container');
+ container.innerHTML = 'Loading...';
+
+ try {
+ const skills = await get('/api/users/me/skills'); // Your API helper
+
+ if (!skills || skills.length === 0) {
+ container.innerHTML = '<p>You have not purchased any skills yet.</p>';
+ return;
+ }
+
+ container.innerHTML = skills.map(skill => `
+ <div class="purchased-skill-card">
+ <img src="${skill.agent_avatar_url}" alt="${skill.agent_name}" class="purchased-skill-avatar" />
+ <div class="purchased-skill-info">
+ <h4 class="purchased-skill-name">${escapeHtml(skill.name)}</h4>
+ <p class="purchased-skill-agent">for <a href="/marketplace/agent/${skill.agent_id}">${escapeHtml(skill.agent_name)}</a></p>
+ </div>
+ <div class="purchased-skill-date">
+ Purchased on ${new Date(skill.purchase_date).toLocaleDateString()}
+ </div>
+ </div>
+ `).join('');
+ } catch (error) {
+ container.innerHTML = '<p>Failed to load your purchased skills.</p>';
+ console.error(error);
+ }
+}
+```
diff --git a/docs/prompts/monetization/07-skill-pricing-dashboard.md b/docs/prompts/monetization/07-skill-pricing-dashboard.md
new file mode 100644
index 000000000..2938579ce
--- /dev/null
+++ b/docs/prompts/monetization/07-skill-pricing-dashboard.md
@@ -0,0 +1,59 @@
+---
+status: not-started
+---
+# Prompt 7: Skill Pricing Dashboard for Creators
+
+## Objective
+Create a dashboard for agent creators to view their skills and set or update prices for them.
+
+## Explanation
+To create a functioning marketplace, we need to empower creators. This prompt focuses on building the user interface where a creator can manage the monetization of their agent's skills.
+
+## Instructions
+1. **Create Creator Dashboard Page:**
+ * In the user dashboard area, create a new section or page accessible to users who have created agents, titled "My Agents & Skills".
+ * This page should list all the agents created by the current user.
+
+2. **Agent Skill Management UI:**
+ * For each agent listed, provide a "Manage Skills" button.
+ * Clicking this button should lead to a view that lists all skills associated with that agent.
+ * Next to each skill, display its current price (or "Not for sale") and an "Edit Price" button.
+
+3. **Price Editing Modal:**
+ * Clicking "Edit Price" should open a modal.
+ * The modal should contain a form with an input for the price and a dropdown for the currency (initially, only USDC on Solana).
+ * The form should handle both setting a price for a new skill and updating an existing one.
+ * Include a "Remove from sale" button to make a skill free again.
+
+4. **Backend API for Pricing:**
+ * Create a secure backend endpoint, e.g., `POST /api/agents/:agentId/skills/price`.
+ * The endpoint must verify that the authenticated user is the owner of the agent.
+ * It should accept `skillName`, `amount`, and `currencyMint` as input.
+ * This endpoint will `INSERT` or `UPDATE` a record in the `agent_skill_prices` table. If the amount is set to 0 or null, the existing price record should be deleted.
+
+## Code Example (Frontend - Price Edit Modal)
+```html
+<div id="price-edit-modal" class="modal">
+ <div class="modal-content">
+ <span class="close-button">&times;</span>
+ <h3>Set Price for <span id="modal-skill-name"></span></h3>
+ <form id="price-form">
+ <input type="hidden" id="modal-agent-id">
+ <div class="form-group">
+ <label for="price-amount">Price</label>
+ <input type="number" id="price-amount" step="0.01" min="0" required>
+ </div>
+ <div class="form-group">
+ <label for="price-currency">Currency</label>
+ <select id="price-currency" disabled>
+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7uVv">USDC (Solana)</option>
+ </select>
+ </div>
+ <div class="form-actions">
+ <button type="submit" class="btn-primary">Save Price</button>
+ <button type="button" id="remove-price-btn" class="btn-danger">Remove from Sale</button>
+ </div>
+ </form>
+ </div>
+</div>
+```
diff --git a/scripts/migrations/20260504120000_create_agent_skill_prices.sql b/scripts/migrations/20260504120000_create_agent_skill_prices.sql
new file mode 100644
index 000000000..5cde68f9f
--- /dev/null
+++ b/scripts/migrations/20260504120000_create_agent_skill_prices.sql
@@ -0,0 +1,26 @@
+-- Create the agent_skill_prices table
+CREATE TABLE IF NOT EXISTS agent_skill_prices (
+ agent_id UUID NOT NULL,
+ skill_name VARCHAR(255) NOT NULL,
+ amount BIGINT NOT NULL,
+ currency_mint VARCHAR(255) NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW(),
+ updated_at TIMESTAMPTZ DEFAULT NOW(),
+ PRIMARY KEY (agent_id, skill_name),
+ FOREIGN KEY (agent_id) REFERENCES agent_identities(id) ON DELETE CASCADE
+);
+
+-- Create a trigger function to automatically update the updated_at timestamp
+CREATE OR REPLACE FUNCTION update_updated_at_column()
+RETURNS TRIGGER AS $$
+BEGIN
+ NEW.updated_at = NOW();
+ RETURN NEW;
+END;
+$$ language 'plpgsql';
+
+-- Create a trigger that uses the function
+CREATE TRIGGER update_agent_skill_prices_updated_at
+BEFORE UPDATE ON agent_skill_prices
+FOR EACH ROW
+EXECUTE FUNCTION update_updated_at_column();
diff --git a/tasks/monetization-feature/01-display-priced-skills.md b/tasks/monetization-feature/01-display-priced-skills.md
index 44794909b..19f00332a 100644
--- a/tasks/monetization-feature/01-display-priced-skills.md
+++ b/tasks/monetization-feature/01-display-priced-skills.md
@@ -1,9 +1,5 @@
---
-status: not-started
----
-
----
-status: not-started
+status: completed
---
# Prompt 1: Display Priced Skills in Marketplace
diff --git a/tasks/monetization-feature/03-backend-api-for-skill-pricing.md b/tasks/monetization-feature/03-backend-api-for-skill-pricing.md
new file mode 100644
index 000000000..6427eb7a0
--- /dev/null
+++ b/tasks/monetization-feature/03-backend-api-for-skill-pricing.md
@@ -0,0 +1,78 @@
+---
+status: not-started
+---
+
+# Prompt 3: Create API for Skill Pricing
+
+**Status:** Not Started
+
+## Objective
+Create backend API endpoints for creators to set, update, and remove prices for their agent's skills.
+
+## Explanation
+With the database table in place, creators need a way to manage the prices of their skills. We will create a secure API endpoint that allows an agent's owner to define these prices. This endpoint will handle creating new price entries, updating existing ones, and deleting them.
+
+## Instructions
+- **Create a New API Route:**
+ - Create a new API file, for example, `/api/agents/[id]/skill-prices.js`.
+ - This route will handle `POST`, `PUT`, and `DELETE` requests for a specific agent's skill prices.
+ - Ensure the route is protected and can only be accessed by the authenticated owner of the agent.
+
+- **Implement the `POST` Handler (Create/Update):**
+ - The `POST` handler will receive a skill name, an amount, and a currency mint in the request body.
+ - It should use an `INSERT ... ON CONFLICT` (UPSERT) query to either create a new price entry or update an existing one for the given agent and skill. This is more efficient than checking for existence first.
+ - Validate the input data. The amount should be a non-negative integer.
+
+- **Implement the `DELETE` Handler (Remove):**
+ - The `DELETE` handler will receive a skill name in the request body or query parameters.
+ - It will execute a `DELETE` query to remove the price entry from the `agent_skill_prices` table for that agent and skill.
+
+## Code Example (Backend - `/api/agents/[id]/skill-prices.js`)
+
+```javascript
+// Example using Node.js, Express-like syntax, and `sql` from './_lib/db.js'
+
+import { getSessionUser } from './_lib/auth.js';
+import { sql } from './_lib/db.js';
+import { error, json, method, readJson, wrap } from './_lib/http.js';
+
+export default wrap(async (req, res, id) => {
+ if (!method(req, res, ['POST', 'DELETE'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [agent] = await sql`
+ SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+
+ const body = await readJson(req);
+ const { skill_name } = body;
+ if (!skill_name) return error(res, 400, 'validation_error', 'skill_name is required');
+
+ if (req.method === 'POST') {
+ const { amount, currency_mint } = body;
+ if (amount == null || !currency_mint) {
+ return error(res, 400, 'validation_error', 'amount and currency_mint are required');
+ }
+
+ const [price] = await sql`
+ INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
+ VALUES (${id}, ${skill_name}, ${BigInt(amount)}, ${currency_mint})
+ ON CONFLICT (agent_id, skill_name)
+ DO UPDATE SET amount = EXCLUDED.amount, currency_mint = EXCLUDED.currency_mint, updated_at = NOW()
+ RETURNING *
+ `;
+ return json(res, 200, { price });
+ }
+
+ if (req.method === 'DELETE') {
+ await sql`
+ DELETE FROM agent_skill_prices WHERE agent_id = ${id} AND skill_name = ${skill_name}
+ `;
+ return json(res, 200, { ok: true });
+ }
+});
+```
diff --git a/tasks/monetization-feature/03-backend-api-set-skill-price.md b/tasks/monetization-feature/03-backend-api-set-skill-price.md
new file mode 100644
index 000000000..dac89a7ee
--- /dev/null
+++ b/tasks/monetization-feature/03-backend-api-set-skill-price.md
@@ -0,0 +1,73 @@
+---
+status: not-started
+---
+
+# Prompt 3: Backend API - Set/Update Skill Price
+
+**Status:** Not Started
+
+## Objective
+Create a secure API endpoint that allows an agent's creator to set or update the price of a skill.
+
+## Explanation
+Now that the database table exists, creators need a way to manage their skill prices. This endpoint will accept a price, skill name, and agent ID. It must be secure, ensuring that only the authenticated user who owns the agent can modify its skill prices.
+
+## Instructions
+- [ ] **Create a new API file:** `api/marketplace/set-skill-price.js`.
+- [ ] **Implement the endpoint logic:**
+ - [ ] It should handle `POST` requests.
+ - [ ] It must authenticate the user (e.g., via a session or API key).
+ - [ ] It needs to verify that the authenticated user is the owner of the agent they are trying to price a skill for.
+ - [ ] It will take `agent_id`, `skill_name`, `amount`, and `currency_mint` as input from the request body.
+ - [ ] Use an `INSERT ... ON CONFLICT` (or "upsert") query to create or update the price in the `agent_skill_prices` table.
+
+## Code Example (`api/marketplace/set-skill-price.js`)
+
+```javascript
+import { sql } from '../_lib/db.js';
+import { json, method, cors, error, auth } from '../_lib/http.js';
+
+export default async function setSkillPrice(req, res) {
+ if (cors(req, res)) return;
+ if (!method(req, res, ['POST'])) return;
+ const authUser = await auth(req, res);
+ if (!authUser) return;
+
+ const { agent_id, skill_name, amount, currency_mint } = req.body;
+
+ if (!agent_id || !skill_name || !amount || !currency_mint) {
+ return error(res, 400, 'bad_request', 'Missing required fields.');
+ }
+
+ try {
+ // First, verify ownership of the agent
+ const [agent] = await sql`
+ SELECT id FROM agents WHERE id = ${agent_id} AND user_id = ${authUser.id}
+ `;
+
+ if (!agent) {
+ return error(res, 403, 'forbidden', 'You do not own this agent.');
+ }
+
+ // Now, upsert the price
+ await sql`
+ INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint, updated_at)
+ VALUES (${agent_id}, ${skill_name}, ${amount}, ${currency_mint}, NOW())
+ ON CONFLICT (agent_id, skill_name)
+ DO UPDATE SET
+ amount = EXCLUDED.amount,
+ currency_mint = EXCLUDED.currency_mint,
+ updated_at = NOW();
+ `;
+
+ return json(res, 200, { ok: true, message: 'Price set successfully.' });
+
+ } catch (e) {
+ console.error('Error setting skill price:', e);
+ return error(res, 500, 'server_error', 'Failed to set skill price.');
+ }
+}
+```
+
+## Tracking
+- To mark this task as complete, check all boxes in the instructions and change the status in the frontmatter to `Completed`.
diff --git a/tasks/monetization-feature/03-backend-api-to-set-skill-prices.md b/tasks/monetization-feature/03-backend-api-to-set-skill-prices.md
new file mode 100644
index 000000000..6c881651f
--- /dev/null
+++ b/tasks/monetization-feature/03-backend-api-to-set-skill-prices.md
@@ -0,0 +1,81 @@
+---
+status: not-started
+---
+
+# Prompt 3: Backend - API to Set Skill Prices
+
+**Status:** Not Started
+
+## Objective
+Create an API endpoint that allows an agent creator to set or update the price of their skills.
+
+## Explanation
+With the `agent_skill_prices` table in place, we now need a way for creators to interact with it. This task involves creating a secure API endpoint that accepts pricing information for a skill and saves it to the database.
+
+## Instructions
+1. **Create the API Endpoint:**
+ - Create a new API route file, for example, `/api/agents/[id]/skills.js`.
+ - Implement a `POST` or `PUT` handler for this route.
+ - The route should be protected, ensuring only the authenticated owner of the agent can set prices.
+
+2. **Implement the Handler Logic:**
+ - The handler should accept a request body containing `skill_name`, `amount`, and `currency_mint`.
+ - Validate the input: ensure `amount` is a positive number and `currency_mint` is a valid address.
+ - Use an "upsert" operation:
+ - If a price for that `agent_id` and `skill_name` already exists, `UPDATE` it.
+ - If it doesn't exist, `INSERT` a new row.
+ - Return a success response with the updated pricing information.
+
+## Code Example (Vercel Serverless Function - `api/agents/[id]/skills.js`)
+
+```javascript
+// Example using a hypothetical database client
+import { db } from '@lib/db';
+import { withAuth } from '@lib/auth';
+
+async function handler(req, res) {
+ if (req.method !== 'POST') {
+ return res.status(405).json({ error: 'Method Not Allowed' });
+ }
+
+ const { id: agentId } = req.query;
+ const { userId } = req.auth;
+ const { skill_name, amount, currency_mint } = req.body;
+
+ // 1. Verify ownership
+ const agent = await db.query('SELECT owner_id FROM agents WHERE id = $1', [agentId]);
+ if (!agent.rows.length || agent.rows[0].owner_id !== userId) {
+ return res.status(403).json({ error: 'Forbidden' });
+ }
+
+ // 2. Validate input
+ if (!skill_name || typeof amount !== 'number' || amount < 0 || !currency_mint) {
+ return res.status(400).json({ error: 'Invalid input' });
+ }
+
+ try {
+ // 3. Upsert into database
+ const result = await db.query(
+ `INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (agent_id, skill_name)
+ DO UPDATE SET amount = EXCLUDED.amount, currency_mint = EXCLUDED.currency_mint, updated_at = NOW()
+ RETURNING *`,
+ [agentId, skill_name, amount, currency_mint]
+ );
+
+ return res.status(200).json(result.rows[0]);
+ } catch (error) {
+ console.error('Error setting skill price:', error);
+ return res.status(500).json({ error: 'Internal Server Error' });
+ }
+}
+
+export default withAuth(handler);
+```
+
+## Definition of Done
+- The API endpoint is created and functional.
+- The endpoint is protected and only allows the agent owner to set prices.
+- The database is correctly updated with the new pricing information.
+- Automated tests are added for this endpoint.
diff --git a/tasks/monetization-feature/03-backend-create-purchase-table.md b/tasks/monetization-feature/03-backend-create-purchase-table.md
new file mode 100644
index 000000000..5df176604
--- /dev/null
+++ b/tasks/monetization-feature/03-backend-create-purchase-table.md
@@ -0,0 +1,48 @@
+---
+status: not-started
+---
+
+# Prompt 3: Create Purchases Database Table
+
+**Status:** Not Started
+
+## Objective
+Create a new database table named `skill_purchases` to record and track every time a user buys a skill. This is a critical piece of infrastructure for managing ownership and revenue.
+
+## Explanation
+To know which users have access to which paid skills, we need a permanent record of each successful purchase. This table will link a user, an agent's skill, and the transaction details. It will serve as the source of truth for skill ownership.
+
+## Instructions
+
+1. **Define the Schema:**
+ * Create a new SQL migration file or use your database management tool to define the schema for the `skill_purchases` table.
+ * The table should include the following columns:
+ * `id`: Primary key (e.g., UUID or auto-incrementing integer).
+ * `user_id`: Foreign key referencing the `users` table. The ID of the user who made the purchase.
+ * `agent_id`: Foreign key referencing the `agents` table. The agent who owns the skill.
+ * `skill_name`: The name of the skill that was purchased (e.g., `text-to-speech`).
+ * `transaction_signature`: The signature of the on-chain transaction. This is proof of payment.
+ * `amount`: The price paid for the skill (in the smallest currency unit, e.g., lamports).
+ * `currency_mint`: The mint address of the currency used for payment (e.g., USDC mint).
+ * `created_at`: Timestamp of when the purchase was recorded.
+
+2. **Apply the Migration:**
+ * Run the migration to create the new table in your database.
+
+## Example SQL Schema (PostgreSQL)
+
+```sql
+CREATE TABLE "skill_purchases" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ "user_id" uuid NOT NULL REFERENCES "users" ("id"),
+ "agent_id" uuid NOT NULL REFERENCES "agents" ("id"),
+ "skill_name" varchar(255) NOT NULL,
+ "transaction_signature" varchar(255) UNIQUE NOT NULL,
+ "amount" bigint NOT NULL,
+ "currency_mint" varchar(255) NOT NULL,
+ "created_at" timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX "idx_skill_purchases_user_id" ON "skill_purchases" ("user_id");
+CREATE INDEX "idx_skill_purchases_agent_id" ON "skill_purchases" ("agent_id");
+```
diff --git a/tasks/monetization-feature/03-backend-set-skill-price-api.md b/tasks/monetization-feature/03-backend-set-skill-price-api.md
new file mode 100644
index 000000000..a88b63b6f
--- /dev/null
+++ b/tasks/monetization-feature/03-backend-set-skill-price-api.md
@@ -0,0 +1,62 @@
+---
+status: not-started
+---
+
+# Prompt 3: Backend - Create API for Setting Skill Prices
+
+## Objective
+Create a secure API endpoint for agent creators to set or update the prices for their skills.
+
+## Explanation
+Now that the `agent_skill_prices` table exists, we need an API endpoint to allow creators to manage the prices of their skills. This endpoint will receive the skill ID, price, and currency, validate the request, and then insert or update the price in the database. It's crucial that only the creator of a skill can set its price.
+
+## Instructions
+1. **Create the API Route:**
+ * Create a new API route, for example, `POST /api/agents/:agentId/skills/:skillId/price`.
+ * This route should be protected and require user authentication.
+
+2. **Implement the Endpoint Logic:**
+ * In the request handler, first, verify that the authenticated user is the owner of the agent and the skill. This is a critical security check.
+ * Validate the incoming request body. It should contain `amount` (as a number) and `currency_mint` (as a string).
+ * Implement the database logic to `INSERT` a new price record into `agent_skill_prices`. If a price for that skill by that creator already exists, `UPDATE` the existing record (an "upsert" operation).
+ * Return a success response if the operation is successful, or an error response if the user is not authorized or the input is invalid.
+
+## Code Example (Backend API - e.g., using Express.js)
+
+```javascript
+// POST /api/agents/:agentId/skills/:skillId/price
+// (Middleware for authentication and agent ownership should be applied before this handler)
+
+async function setSkillPrice(req, res) {
+ const { userId } = req.auth; // From auth middleware
+ const { agentId, skillId } = req.params;
+ const { amount, currency_mint } = req.body;
+
+ // 1. Validate input
+ if (typeof amount !== 'number' || !currency_mint || typeof currency_mint !== 'string') {
+ return res.status(400).json({ error: 'Invalid input' });
+ }
+
+ // 2. Verify ownership (this logic depends on your schema)
+ const isOwner = await verifySkillOwnership(userId, agentId, skillId);
+ if (!isOwner) {
+ return res.status(403).json({ error: 'Forbidden' });
+ }
+
+ // 3. Upsert the price in the database
+ try {
+ const { rows } = await db.query(
+ `INSERT INTO agent_skill_prices (skill_id, creator_id, amount, currency_mint)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (skill_id, creator_id)
+ DO UPDATE SET amount = EXCLUDED.amount, currency_mint = EXCLUDED.currency_mint, updated_at = NOW()
+ RETURNING *`,
+ [skillId, userId, amount, currency_mint]
+ );
+ res.status(200).json({ price: rows[0] });
+ } catch (error) {
+ console.error('Error setting skill price:', error);
+ res.status(500).json({ error: 'Internal server error' });
+ }
+}
+```
diff --git a/tasks/monetization-feature/03-backend-set-skill-prices-api.md b/tasks/monetization-feature/03-backend-set-skill-prices-api.md
new file mode 100644
index 000000000..baabc86e3
--- /dev/null
+++ b/tasks/monetization-feature/03-backend-set-skill-prices-api.md
@@ -0,0 +1,66 @@
+---
+status: not-started
+---
+
+# Prompt 3: Backend API to Set Skill Prices
+
+**Status:** Not Started
+
+## Objective
+Create a backend API endpoint that allows agent creators to set or update the price for a specific skill.
+
+## Explanation
+With the database table in place, we need a way for the frontend to communicate pricing information to the server. A secure API endpoint is required for this. The endpoint should ensure that only the owner of an agent can change the prices of its skills.
+
+## Instructions
+- [ ] **Create a new API file or modify an existing one.** A good place could be `api/agent-actions.js` or a new file like `api/agent-pricing.js`.
+- [ ] **Define the endpoint.** Use `POST /api/agents/:id/skills/price`.
+- [ ] **Implement authentication.** The endpoint must be protected. Verify that the authenticated user is the owner of the agent specified by `:id`.
+- [ ] **Validate the request body.** The body should contain `skill_name`, `amount`, and `currency_mint`. Use a library like `zod` for validation.
+- [ ] **Implement the database logic.** The endpoint should perform an "upsert" operation:
+ - If a price for the agent's skill already exists, `UPDATE` it.
+ - If it doesn't exist, `INSERT` a new row.
+- [ ] **Return a success response.** On successful creation or update, return a `200 OK` or `201 Created` status with the updated pricing information.
+- [ ] **Handle errors.** Return appropriate error codes (e.g., `401 Unauthorized`, `404 Not Found`, `400 Bad Request`, `500 Internal Server Error`).
+
+## Code Example (Express.js-like)
+
+```javascript
+// In api/agent-actions.js or similar
+
+// POST /api/agents/:id/skills/price
+// Body: { "skill_name": "...", "amount": 1000000, "currency_mint": "..." }
+
+export default async function handler(req, res) {
+ // 1. Get authenticated user
+ const user = await getAuthenticatedUser(req);
+ const agentId = req.query.id;
+
+ // 2. Verify ownership
+ const agent = await db.query('SELECT * FROM agents WHERE id = $1', [agentId]);
+ if (!agent || agent.owner_id !== user.id) {
+ return res.status(401).json({ error: 'Unauthorized' });
+ }
+
+ // 3. Validate body
+ const { skill_name, amount, currency_mint } = req.body;
+ // ... validation logic ...
+
+ // 4. Upsert price in DB
+ const result = await db.query(
+ `INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (agent_id, skill_name)
+ DO UPDATE SET amount = $3, currency_mint = $4, updated_at = NOW()
+ RETURNING *`,
+ [agentId, skill_name, amount, currency_mint]
+ );
+
+ // 5. Return response
+ res.status(200).json(result.rows[0]);
+}
+```
+
+## Tracking Completion
+- [ ] Mark this file's status as `Completed` in the frontmatter when done.
+- [ ] Check off all instructions.
diff --git a/tasks/monetization-feature/04-backend-api-set-skill-price.md b/tasks/monetization-feature/04-backend-api-set-skill-price.md
new file mode 100644
index 000000000..7ddf02ee6
--- /dev/null
+++ b/tasks/monetization-feature/04-backend-api-set-skill-price.md
@@ -0,0 +1,89 @@
+---
+status: not-started
+---
+
+# Prompt 4: API to Set Skill Prices
+
+**Status:** Not Started
+
+## Objective
+Create a secure backend API endpoint that allows the creator of an agent to set or update the price for one of their agent's skills.
+
+## Explanation
+To enable monetization, creators need a way to manage the prices of their skills. This endpoint will provide that functionality. It must be secure, ensuring that only the agent's owner can change the prices.
+
+## Instructions
+
+1. **Create the API Endpoint:**
+ * Create a new API file, e.g., `api/agent/set-skill-price.js`.
+ * This endpoint should accept a `POST` request.
+
+2. **Implement Authentication & Authorization:**
+ * The endpoint must be protected. Ensure a user is logged in.
+ * Verify that the authenticated user is the owner of the agent whose skill price is being set. You will need to fetch the agent's details from the database using the provided `agent_id` and compare the owner's ID with the current user's ID.
+
+3. **Handle the Request Body:**
+ * The request body should contain:
+ * `agent_id`: The ID of the agent.
+ * `skill_name`: The name of the skill to price.
+ * `amount`: The price in the smallest currency unit (e.g., lamports).
+ * `currency_mint`: The currency's mint address.
+
+4. **Update the Database:**
+ * In your `agent_skill_prices` table, perform an "upsert" operation:
+ * If a price for that `agent_id` and `skill_name` already exists, **update** it.
+ * If it doesn't exist, **insert** a new row.
+ * Return a success response.
+
+## Code Example (Node.js / Vercel Serverless Function)
+
+```javascript
+// In /api/agent/set-skill-price.js
+
+import { supabase } from '../_lib/supabase';
+import { authenticate } from '../_lib/auth';
+
+export default async function handler(req, res) {
+ if (req.method !== 'POST') {
+ return res.status(405).json({ error: 'Method not allowed' });
+ }
+
+ const user = await authenticate(req);
+ if (!user) {
+ return res.status(401).json({ error: 'Unauthorized' });
+ }
+
+ const { agent_id, skill_name, amount, currency_mint } = req.body;
+
+ // 1. Verify ownership
+ const { data: agent, error: agentError } = await supabase
+ .from('agents')
+ .select('owner_id')
+ .eq('id', agent_id)
+ .single();
+
+ if (agentError || !agent || agent.owner_id !== user.id) {
+ return res.status(403).json({ error: 'You do not own this agent.' });
+ }
+
+ // 2. Upsert the price
+ const { error: priceError } = await supabase
+ .from('agent_skill_prices')
+ .upsert({
+ agent_id,
+ skill_name,
+ amount,
+ currency_mint,
+ updated_at: new Date(),
+ }, {
+ onConflict: 'agent_id, skill_name'
+ });
+
+ if (priceError) {
+ console.error('Error setting skill price:', priceError);
+ return res.status(500).json({ error: 'Failed to set skill price.' });
+ }
+
+ return res.status(200).json({ success: true });
+}
+```
diff --git a/tasks/monetization-feature/04-backend-create-purchase-table.md b/tasks/monetization-feature/04-backend-create-purchase-table.md
new file mode 100644
index 000000000..344b3eda1
--- /dev/null
+++ b/tasks/monetization-feature/04-backend-create-purchase-table.md
@@ -0,0 +1,42 @@
+---
+status: not-started
+---
+
+# Prompt 4: Backend - Create Purchase History Table
+
+**Status:** Not Started
+
+## Objective
+Create a database table to log every skill purchase, serving as a permanent record of transactions.
+
+## Explanation
+To manage access to paid skills, we need to record who purchased what. The `skill_purchases` table will store the user who made the purchase, the agent and skill they bought, the transaction details (like a Solana transaction signature), and the amount paid. This table is crucial for verifying access and for creator analytics.
+
+## Instructions
+- [ ] **Connect to your database.**
+- [ ] **Execute the following SQL schema to create the `skill_purchases` table.** This schema links a user to a specific agent's skill. It's designed to prevent duplicate purchase records for the same skill and includes a unique transaction signature.
+
+## SQL Schema
+
+```sql
+CREATE TABLE IF NOT EXISTS skill_purchases (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ skill_name VARCHAR(255) NOT NULL,
+ amount_paid BIGINT NOT NULL,
+ currency_mint VARCHAR(44) NOT NULL,
+ transaction_ref VARCHAR(255) UNIQUE NOT NULL, -- e.g., Solana Tx Signature or Stripe Charge ID
+ purchase_date TIMESTAMPTZ DEFAULT NOW(),
+
+ -- Ensures a user can only buy a specific skill on an agent once
+ UNIQUE (user_id, agent_id, skill_name)
+);
+
+-- Add indexes for common query patterns
+CREATE INDEX IF NOT EXISTS idx_skill_purchases_user_id ON skill_purchases(user_id);
+CREATE INDEX IF NOT EXISTS idx_skill_purchases_agent_id ON skill_purchases(agent_id);
+```
+
+## Tracking
+- To mark this task as complete, check the box in the instructions above and change the status in the frontmatter to `Completed`.
diff --git a/tasks/monetization-feature/04-frontend-skill-pricing-ui.md b/tasks/monetization-feature/04-frontend-skill-pricing-ui.md
new file mode 100644
index 000000000..70f82f09a
--- /dev/null
+++ b/tasks/monetization-feature/04-frontend-skill-pricing-ui.md
@@ -0,0 +1,76 @@
+---
+status: not-started
+---
+
+# Prompt 4: Frontend - UI for Skill Price Management
+
+## Objective
+Create a user interface in the agent editor page for creators to set and manage the prices of their skills.
+
+## Explanation
+To complement the backend API for setting skill prices, we need a user-friendly interface for creators. This UI will be part of the agent editor, likely in a new "Monetization" or "Skills" tab. It will list the agent's skills and provide input fields for creators to set the price for each one.
+
+## Instructions
+1. **Locate the Agent Editor:**
+ * Find the main agent editor component, likely in `agent-edit.html` and its corresponding JavaScript file.
+
+2. **Add a "Monetization" Tab:**
+ * Add a new tab to the agent editor for managing monetization settings.
+ * Inside this tab, fetch and display a list of the agent's skills.
+
+3. **Create the Pricing Form:**
+ * For each skill, display a form with:
+ * An input field for the `amount`.
+ * A dropdown (`<select>`) for the `currency_mint` (e.g., pre-populated with USDC, BONK, etc.).
+ * A "Save" button.
+ * When the creator saves a price, make a `POST` request to the API endpoint created in the previous prompt (`/api/agents/:agentId/skills/:skillId/price`).
+ * Display feedback to the user on success or failure (e.g., a "Saved!" message or an error alert).
+
+## Code Example (Frontend - `agent-edit.html` structure)
+
+```html
+<!-- Inside the agent editor's tab panel -->
+<div id="monetization-panel" class="edit-panel">
+ <h2>Skill Pricing</h2>
+ <div id="skill-list-pricing">
+ <!-- Skills will be dynamically rendered here -->
+ </div>
+</div>
+```
+
+## Code Example (Frontend - JavaScript logic)
+
+```javascript
+// Inside the agent editor's JavaScript file
+
+function renderSkillPricing(skills, agentId) {
+ const container = document.getElementById('skill-list-pricing');
+ container.innerHTML = skills.map(skill => `
+ <div class="skill-price-row">
+ <span class="skill-name">${escapeHtml(skill.name)}</span>
+ <div class="price-inputs">
+ <input type="number" class="price-amount" placeholder="e.g., 1.99" data-skill-id="${skill.id}">
+ <select class="price-currency" data-skill-id="${skill.id}">
+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v">USDC</option>
+ <option value="DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263">BONK</option>
+ </select>
+ <button class="save-price-btn" data-skill-id="${skill.id}">Save</button>
+ </div>
+ </div>
+ `).join('');
+
+ container.addEventListener('click', async (e) => {
+ if (e.target.matches('.save-price-btn')) {
+ const skillId = e.target.dataset.skillId;
+ const amountInput = container.querySelector(`.price-amount[data-skill-id="${skillId}"]`);
+ const currencySelect = container.querySelector(`.price-currency[data-skill-id="${skillId}"]`);
+
+ const amount = parseFloat(amountInput.value) * 1e6; // Convert to lamports
+ const currency_mint = currencySelect.value;
+
+ // Make API call to POST /api/agents/${agentId}/skills/${skillId}/price
+ // ... handle success/error and show feedback ...
+ }
+ });
+}
+```
diff --git a/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.md b/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.md
new file mode 100644
index 000000000..04df0136c
--- /dev/null
+++ b/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.md
@@ -0,0 +1,102 @@
+---
+status: not-started
+---
+
+# Prompt 4: Frontend - UI for Setting Skill Prices
+
+**Status:** Not Started
+
+## Objective
+Create a user interface within the agent creation or editing page that allows creators to set prices for their skills.
+
+## Explanation
+Now that the backend can handle skill pricing, we need to provide a way for creators to use it. This task involves designing and building a new section in the UI where a creator can see a list of their agent's skills and attach a price to each one.
+
+## Instructions
+1. **Locate the Agent Editor UI:**
+ - Find the HTML file and JavaScript module responsible for the agent editing page (e.g., `agent-edit.html` and `src/agent-edit.js`).
+
+2. **Design the UI Component:**
+ - Within the skills section of the agent editor, for each skill listed, add a form input for `price` and a dropdown for `currency`.
+ - Initially, the currency can be a static list (e.g., "USDC").
+ - Add a "Save Prices" button.
+
+3. **Implement the Component:**
+ - When the agent editor loads, it should fetch the agent's details, including the existing `skill_prices`.
+ - Populate the input fields with the existing prices for each skill.
+ - When the "Save Prices" button is clicked, the UI should gather the pricing data for all skills that have a price set.
+
+## Code Example (HTML in `agent-edit.html`)
+
+This is a conceptual example of what the new HTML might look like.
+
+```html
+<!-- Inside the agent editor form, where skills are listed -->
+<div class="form-section">
+ <h3>Skill Monetization</h3>
+ <div id="skill-pricing-list">
+ <!-- Skills will be rendered here by JavaScript -->
+ </div>
+ <button type="button" id="save-skill-prices-btn">Save Prices</button>
+</div>
+```
+
+## Code Example (JavaScript in `src/agent-edit.js`)
+
+```javascript
+// ... inside the function that renders the agent editor ...
+
+const skills = agent.skills || [];
+const skillPrices = agent.skill_prices || {};
+const skillPricingList = document.getElementById('skill-pricing-list');
+
+skillPricingList.innerHTML = skills.map(skill => {
+ const price = skillPrices[skill.name];
+ const amountInUsdc = price ? (price.amount / 1e6).toFixed(2) : '';
+ return `
+ <div class="skill-price-entry">
+ <span class="skill-name">${escapeHtml(skill.name)}</span>
+ <div class="price-input-wrap">
+ <input
+ type="number"
+ step="0.01"
+ min="0"
+ class="price-input"
+ data-skill-name="${escapeHtml(skill.name)}"
+ placeholder="e.g., 0.99"
+ value="${amountInUsdc}"
+ />
+ <span class="currency-label">USDC</span>
+ </div>
+ </div>
+ `;
+}).join('');
+```
+
+## CSS Example
+
+Add styles to `/agent-edit.css` for the new elements.
+
+```css
+.skill-price-entry {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 8px 0;
+ border-bottom: 1px solid #333;
+}
+.price-input-wrap {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.price-input {
+ width: 80px;
+ /* ... other styles */
+}
+```
+
+## Definition of Done
+- The UI for setting skill prices is implemented on the agent editing page.
+- Existing prices are correctly displayed when the page loads.
+- The "Save Prices" button is present.
diff --git a/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.md b/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.md
new file mode 100644
index 000000000..57b77749f
--- /dev/null
+++ b/tasks/monetization-feature/04-frontend-ui-for-skill-pricing.md
@@ -0,0 +1,68 @@
+---
+status: not-started
+---
+
+# Prompt 4: UI for Skill Pricing
+
+**Status:** Not Started
+
+## Objective
+Build the user interface in the agent editor for creators to set and manage prices for their skills.
+
+## Explanation
+Now that the backend can handle skill pricing, we need to provide a user interface for creators. This UI will be part of the agent editing page. It should list all of the agent's skills and provide input fields for creators to set a price for each one. The UI should be intuitive, allowing for easy adding, updating, and removing of prices.
+
+## Instructions
+- **Locate the Agent Editor UI:**
+ - The main file for the agent editor is likely `agent-edit.html`.
+ - The corresponding JavaScript that handles the logic is likely in `src/agent-edit.js` or similar.
+
+- **Design the Pricing Section:**
+ - Within the agent editor, find the area where skills are listed or managed.
+ - For each skill, add a section for pricing. This should include:
+ - An input field for the price amount.
+ - A dropdown or input to select the currency (e.g., "USDC").
+ - A "Save" button to save the price.
+ - A "Remove" button to clear the price.
+ - The UI should clearly distinguish between free and priced skills.
+
+- **Implement the UI Logic:**
+ - When the agent data is loaded, populate the pricing inputs with existing values from the `agent.skill_prices` object.
+ - When the "Save" button is clicked, call the `POST /api/agents/[id]/skill-prices` endpoint you created in the previous prompt.
+ - When the "Remove" button is clicked, call the `DELETE /api/agents/[id]/skill-prices` endpoint.
+ - Provide feedback to the user on success or failure (e.g., a "Saved!" message or an error alert).
+
+## Code Example (Frontend - `agent-edit.html` structure)
+
+This is a conceptual example of the HTML structure. You will need to integrate this into your existing templating or DOM-building logic.
+
+```html
+<!-- Inside the agent editor's skills list -->
+<div class="skill-item">
+ <span class="skill-name">greet</span>
+ <div class="skill-pricing-form">
+ <input type="number" class="skill-price-input" placeholder="e.g., 1.50" value="1.50">
+ <select class="skill-currency-select">
+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6f">USDC</option>
+ </select>
+ <button class="btn-save-price">Save</button>
+ <button class="btn-remove-price">Remove</button>
+ </div>
+</div>
+```
+
+## CSS Example
+
+Add styles to `/agent-edit.css` to make the form look clean.
+
+```css
+.skill-pricing-form {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 8px;
+}
+.skill-price-input {
+ width: 80px;
+}
+```
diff --git a/tasks/monetization-feature/05-backend-api-check-skill-access.md b/tasks/monetization-feature/05-backend-api-check-skill-access.md
new file mode 100644
index 000000000..168011ca1
--- /dev/null
+++ b/tasks/monetization-feature/05-backend-api-check-skill-access.md
@@ -0,0 +1,63 @@
+---
+status: not-started
+---
+
+# Prompt 5: Backend API - Check Skill Access
+
+**Status:** Not Started
+
+## Objective
+Create a fast, efficient API endpoint to verify if a user has purchased access to a specific skill on a specific agent.
+
+## Explanation
+Before executing a paid skill, the system needs to check if the current user has the right to use it. This endpoint will serve that purpose. It should be highly optimized for speed, as it might be called frequently during agent interactions. It will query the `skill_purchases` table to see if a valid record exists for the given user, agent, and skill.
+
+## Instructions
+- [ ] **Create a new API file:** `api/marketplace/check-skill-access.js`.
+- [ ] **Implement the endpoint logic:**
+ - [ ] It should handle `GET` requests.
+ - [ ] It must authenticate the user.
+ - [ ] It should accept `agent_id` and `skill_name` as query parameters.
+ - [ ] It will perform a lookup in the `skill_purchases` table for a matching record (`user_id`, `agent_id`, `skill_name`).
+ - [ ] It should return a simple boolean `has_access` in the JSON response.
+
+## Code Example (`api/marketplace/check-skill-access.js`)
+
+```javascript
+import { sql } from '../_lib/db.js';
+import { json, method, cors, error, auth } from '../_lib/http.js';
+
+export default async function checkSkillAccess(req, res) {
+ if (cors(req, res)) return;
+ if (!method(req, res, ['GET'])) return;
+ const authUser = await auth(req, res);
+ if (!authUser) return;
+
+ const { agent_id, skill_name } = req.query;
+
+ if (!agent_id || !skill_name) {
+ return error(res, 400, 'bad_request', 'Missing agent_id or skill_name.');
+ }
+
+ try {
+ const [purchase] = await sql`
+ SELECT id FROM skill_purchases
+ WHERE user_id = ${authUser.id}
+ AND agent_id = ${agent_id}
+ AND skill_name = ${skill_name}
+ LIMIT 1;
+ `;
+
+ const has_access = !!purchase;
+
+ return json(res, 200, { ok: true, has_access });
+
+ } catch (e) {
+ console.error('Error checking skill access:', e);
+ return error(res, 500, 'server_error', 'Failed to check access.');
+ }
+}
+```
+
+## Tracking
+- To mark this task as complete, check all boxes in the instructions and change the status in the frontmatter to `Completed`.
diff --git a/tasks/monetization-feature/05-backend-api-purchase-skill.md b/tasks/monetization-feature/05-backend-api-purchase-skill.md
new file mode 100644
index 000000000..adf2f9c7d
--- /dev/null
+++ b/tasks/monetization-feature/05-backend-api-purchase-skill.md
@@ -0,0 +1,90 @@
+---
+status: not-started
+---
+
+# Prompt 5: API to Purchase a Skill
+
+**Status:** Not Started
+
+## Objective
+Create the core backend API endpoint that allows a user to purchase a skill. This endpoint will verify the transaction and record the purchase in the database.
+
+## Explanation
+This is the most critical part of the monetization flow. The user will have confirmed the transaction on the frontend with their wallet. The frontend will then send the transaction signature to this backend endpoint. The backend must verify that the transaction was successful and that the correct amount was transferred to the right recipient before recording the purchase.
+
+## Instructions
+
+1. **Create the API Endpoint:**
+ * Create `api/skill/purchase.js` to handle `POST` requests.
+
+2. **Validate the Request:**
+ * The request body should include:
+ * `agent_id`
+ * `skill_name`
+ * `transaction_signature`
+ * The user must be authenticated.
+
+3. **Verify the Solana Transaction:**
+ * Use the Solana RPC `getTransaction` method with the provided `transaction_signature`.
+ * Check that the transaction was successful (`err` is null).
+ * Fetch the skill price from the `agent_skill_prices` table.
+ * Inspect the transaction's post-balances and pre-balances to confirm:
+ * The buyer's balance decreased by the correct amount.
+ * The seller's (agent owner's) balance increased by the correct amount.
+ * The currency mint matches the one specified for the skill.
+
+4. **Record the Purchase:**
+ * If transaction verification is successful, insert a new record into the `skill_purchases` table.
+ * Store the `user_id`, `agent_id`, `skill_name`, `transaction_signature`, `amount`, and `currency_mint`.
+
+5. **Return a Response:**
+ * Return a success message if the purchase was recorded.
+ * Return a detailed error if verification fails at any step.
+
+## Code Example (Node.js with `@solana/web3.js`)
+
+```javascript
+// In /api/skill/purchase.js
+
+import { Connection, PublicKey } from '@solana/web3.js';
+import { supabase } from '../_lib/supabase';
+import { authenticate } from '../_lib/auth';
+
+const SOLANA_RPC_URL = process.env.SOLANA_RPC_URL;
+const connection = new Connection(SOLANA_RPC_URL, 'confirmed');
+
+export default async function handler(req, res) {
+ const user = await authenticate(req);
+ if (!user) return res.status(401).json({ error: 'Unauthorized' });
+
+ const { agent_id, skill_name, signature } = req.body;
+
+ // 1. Fetch expected price and seller wallet
+ // ... (get price from agent_skill_prices and seller wallet from agents table)
+
+ // 2. Verify transaction
+ try {
+ const tx = await connection.getTransaction(signature, { maxSupportedTransactionVersion: 0 });
+ if (tx.meta.err) throw new Error('Transaction failed on-chain');
+
+ // ... (logic to parse transaction accounts and balances)
+ // ... (compare actual transfer amount/wallets with expected price/wallets)
+
+ // 3. Record purchase in DB if verification passes
+ const { error } = await supabase.from('skill_purchases').insert({
+ user_id: user.id,
+ agent_id,
+ skill_name,
+ transaction_signature: signature,
+ // ... (amount, currency_mint)
+ });
+
+ if (error) throw error;
+
+ res.status(200).json({ success: true, message: 'Purchase successful!' });
+ } catch (err) {
+ console.error('Purchase verification failed:', err);
+ res.status(400).json({ success: false, error: 'Transaction verification failed.' });
+ }
+}
+```
diff --git a/tasks/monetization-feature/05-backend-create-purchases-table.md b/tasks/monetization-feature/05-backend-create-purchases-table.md
new file mode 100644
index 000000000..c4680c061
--- /dev/null
+++ b/tasks/monetization-feature/05-backend-create-purchases-table.md
@@ -0,0 +1,58 @@
+---
+status: not-started
+---
+
+# Prompt 5: Create Purchase-Tracking Table
+
+**Status:** Not Started
+
+## Objective
+Create the `skill_purchases` table in the database to track which users have purchased access to which skills.
+
+## Explanation
+When a user buys a skill, we need to record that transaction to grant them permanent access. This table will serve as the source of truth for skill ownership. The agent's runtime will check this table to determine if a user is authorized to execute a premium skill.
+
+## Instructions
+- **Create a SQL Migration File:**
+ - As before, create a new timestamped migration file, e.g., `YYYYMMDDHHMMSS_create_skill_purchases.sql`.
+
+- **Define the Table Schema:**
+ - The table needs to link a user, an agent, and a skill.
+ - It should also store details about the purchase transaction for auditing and records.
+ - A unique constraint on `user_id`, `agent_id`, and `skill_name` will prevent duplicate purchase records.
+
+## SQL Example
+
+```sql
+-- migrations/YYYYMMDDHHMMSS_create_skill_purchases.sql
+
+CREATE TABLE IF NOT EXISTS skill_purchases (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL,
+ agent_id UUID NOT NULL,
+ skill_name VARCHAR(255) NOT NULL,
+
+ -- Purchase details
+ purchase_amount BIGINT NOT NULL,
+ purchase_currency_mint VARCHAR(255) NOT NULL,
+ transaction_signature VARCHAR(255) NOT NULL, -- The on-chain tx signature
+
+ purchased_at TIMESTAMPTZ DEFAULT NOW(),
+
+ -- Foreign keys
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+ FOREIGN KEY (agent_id) REFERENCES agent_identities(id) ON DELETE CASCADE,
+
+ -- Each user can only buy a specific skill from a specific agent once
+ UNIQUE (user_id, agent_id, skill_name)
+);
+
+-- Add indexes for faster lookups
+CREATE INDEX idx_skill_purchases_user_skill ON skill_purchases(user_id, agent_id, skill_name);
+CREATE INDEX idx_skill_purchases_transaction ON skill_purchases(transaction_signature);
+```
+## How to Run
+- Use your migration tool or `psql` to apply this schema change to the database.
+ ```bash
+ psql -d YOUR_DATABASE_URL -f migrations/YYYYMMDDHHMMSS_create_skill_purchases.sql
+ ```
diff --git a/tasks/monetization-feature/05-solana-payment-setup.md b/tasks/monetization-feature/05-solana-payment-setup.md
new file mode 100644
index 000000000..d7dd92360
--- /dev/null
+++ b/tasks/monetization-feature/05-solana-payment-setup.md
@@ -0,0 +1,78 @@
+---
+status: not-started
+---
+
+# Prompt 5: Frontend - Solana Wallet Connection for Payments
+
+## Objective
+Integrate a Solana wallet adapter to allow users to connect their wallets, which is the first step in enabling payments for skills.
+
+## Explanation
+To purchase skills, users will need to connect their Solana wallet (like Phantom or Solflare) to the platform. We will use the official Solana wallet-adapter library to provide a smooth and familiar connection experience for users. This prompt focuses on adding a "Connect Wallet" button and managing the wallet connection state.
+
+## Instructions
+1. **Install Dependencies:**
+ * Add the required Solana wallet-adapter libraries to your project's dependencies in `package.json`. You'll need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-react` (or a vanilla JS equivalent), and adapters for popular wallets like `@solana/wallet-adapter-wallets`.
+
+2. **Add a "Connect Wallet" Button:**
+ * In the main navigation header of the marketplace (`marketplace.html`), add a "Connect Wallet" button.
+ * This button will be visible to users who are not yet connected.
+
+3. **Implement the Wallet Connection Logic:**
+ * Initialize the wallet adapter provider.
+ * When the "Connect Wallet" button is clicked, trigger the wallet adapter's connection modal.
+ * Once connected, the button should change to show the user's truncated public key and a "Disconnect" option.
+ * Store the connection state and the user's public key in a global state so that it can be accessed by other components (like the purchase modal that will be built later).
+
+## Code Example (Frontend - `marketplace.js` or a new module)
+
+```javascript
+import { WalletAdapterNetwork } from '@solana/wallet-adapter-base';
+import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';
+import { WalletModalProvider, WalletMultiButton } from '@solana/wallet-adapter-react-ui';
+import {
+ GlowWalletAdapter,
+ PhantomWalletAdapter,
+ SlopeWalletAdapter,
+ SolflareWalletAdapter,
+ TorusWalletAdapter,
+} from '@solana/wallet-adapter-wallets';
+import { clusterApiUrl } from '@solana/web3.js';
+import React, { useMemo } from 'react';
+
+// (This example uses React, but the same principles apply to a vanilla JS implementation)
+
+function App() {
+ const network = WalletAdapterNetwork.Devnet;
+ const endpoint = useMemo(() => clusterApiUrl(network), [network]);
+
+ const wallets = useMemo(
+ () => [
+ new PhantomWalletAdapter(),
+ new SolflareWalletAdapter(),
+ // ... other wallets
+ ],
+ [network]
+ );
+
+ return (
+ <ConnectionProvider endpoint={endpoint}>
+ <WalletProvider wallets={wallets} autoConnect>
+ <WalletModalProvider>
+ {/* Your app components */}
+ <WalletMultiButton />
+ </WalletModalProvider>
+ </WalletProvider>
+ </ConnectionProvider>
+ );
+}
+```
+
+## HTML Example (`marketplace.html`)
+
+```html
+<!-- In the marketplace header -->
+<div class="wallet-adapter-button-container">
+ <!-- The wallet adapter button will be rendered here -->
+</div>
+```
diff --git a/tasks/monetization-feature/06-backend-api-list-purchased-skills.md b/tasks/monetization-feature/06-backend-api-list-purchased-skills.md
new file mode 100644
index 000000000..aaccae95e
--- /dev/null
+++ b/tasks/monetization-feature/06-backend-api-list-purchased-skills.md
@@ -0,0 +1,78 @@
+---
+status: not-started
+---
+
+# Prompt 6: API to List Purchased Skills
+
+**Status:** Not Started
+
+## Objective
+Create a backend API endpoint that returns a list of all skills a specific user has purchased.
+
+## Explanation
+The frontend needs a way to know which skills the current user owns so it can update the UI accordingly (e.g., change a "Purchase" button to "Owned" or "Unlocked"). This endpoint provides that data.
+
+## Instructions
+
+1. **Create the API Endpoint:**
+ * Create a new endpoint, for example, `/api/user/purchased-skills.js`.
+ * This should handle `GET` requests.
+
+2. **Authentication:**
+ * The endpoint must be protected. The user must be logged in to view their own purchased skills.
+
+3. **Query the Database:**
+ * Fetch the authenticated user's ID.
+ * Query the `skill_purchases` table for all records where `user_id` matches the current user's ID.
+ * You might want to join with the `agents` table to get more details about the agent whose skill was purchased.
+
+4. **Format and Return the Data:**
+ * Return an array of purchased skill objects. Each object could contain `agent_id`, `agent_name`, `skill_name`, and `purchased_at`.
+
+## Code Example (Node.js / Vercel Serverless Function)
+
+```javascript
+// In /api/user/purchased-skills.js
+
+import { supabase } from '../_lib/supabase';
+import { authenticate } from '../_lib/auth';
+
+export default async function handler(req, res) {
+ const user = await authenticate(req);
+ if (!user) {
+ return res.status(401).json({ error: 'Unauthorized' });
+ }
+
+ const { data, error } = await supabase
+ .from('skill_purchases')
+ .select(`
+ skill_name,
+ created_at,
+ agent:agents (
+ id,
+ name,
+ avatar_uri
+ )
+ `)
+ .eq('user_id', user.id);
+
+ if (error) {
+ console.error('Error fetching purchased skills:', error);
+ return res.status(500).json({ error: 'Failed to fetch purchased skills.' });
+ }
+
+ // Format the data to be more convenient for the client
+ const formattedData = data.reduce((acc, purchase) => {
+ const agentId = purchase.agent.id;
+ if (!acc[agentId]) {
+ acc[agentId] = [];
+ }
+ acc[agentId].push(purchase.skill_name);
+ return acc;
+ }, {});
+ // Result format: { "agent_id_1": ["skill_1", "skill_2"], "agent_id_2": ["skill_3"] }
+
+
+ return res.status(200).json(formattedData);
+}
+```
diff --git a/tasks/monetization-feature/06-ui-add-purchase-button.md b/tasks/monetization-feature/06-ui-add-purchase-button.md
new file mode 100644
index 000000000..e0de7db23
--- /dev/null
+++ b/tasks/monetization-feature/06-ui-add-purchase-button.md
@@ -0,0 +1,71 @@
+---
+status: not-started
+---
+
+# Prompt 6: UI - Add "Purchase" Button for Priced Skills
+
+**Status:** Not Started
+
+## Objective
+Update the agent detail page UI to display a "Purchase" or "Buy" button next to skills that are not free and have not yet been purchased by the user.
+
+## Explanation
+Following on from Prompt 1 where we displayed the price, we now need to add a call to action. This involves checking if the user already owns the skill. We will use the `check-skill-access` API endpoint created in the previous step. The button's state will depend on three factors: is the skill priced, and does the user own it?
+
+## Instructions
+- [ ] **Modify `src/marketplace.js`:**
+ - [ ] In the `renderDetail` function, before rendering the skills list, fetch the user's access status for all skills on the current agent. You can create a new function for this that calls your `/api/marketplace/check-skill-access` endpoint for each skill.
+ - [ ] Store the owned skills in a `Set` for quick lookups.
+ - [ ] In the `map` function that renders each skill, add a condition:
+ - If `price` exists and the skill is in the `ownedSkills` set, show an "Owned" badge.
+ - If `price` exists and the skill is *not* in the `ownedSkills` set, render a purchase button.
+ - If the skill is free, show the "Free" badge as before.
+
+## Code Example (`src/marketplace.js`)
+
+```javascript
+// A new helper function to get all owned skills for an agent
+async function getOwnedSkills(agentId, skills) {
+ const owned = new Set();
+ // In a real app, you might want a single API call for this,
+ // but for now, parallel checks are fine.
+ await Promise.all(skills.map(async (s) => {
+ const name = typeof s === 'string' ? s : s.name;
+ try {
+ const res = await fetch(`/api/marketplace/check-skill-access?agent_id=${agentId}&skill_name=${name}`);
+ const data = await res.json();
+ if (data.has_access) {
+ owned.add(name);
+ }
+ } catch (e) { console.error('Failed to check skill access', e); }
+ }));
+ return owned;
+}
+
+// Inside renderDetail function, before rendering skills
+const skillsArr = a.skills ? (Array.isArray(a.skills) ? a.skills : Object.values(a.skills)) : [];
+const ownedSkills = await getOwnedSkills(a.id, skillsArr);
+
+const skillPrices = a.skill_prices || {};
+$('d-skills').innerHTML = skillsArr.length
+ ? skillsArr.map((s) => {
+ const name = typeof s === 'string' ? s : (s.name || '');
+ const price = skillPrices[name];
+
+ let badgeOrButton = `<span class="price-badge price-free">Free</span>`;
+ if (price) {
+ if (ownedSkills.has(name)) {
+ badgeOrButton = `<span class="price-badge price-owned">✓ Owned</span>`;
+ } else {
+ badgeOrButton = `<button class="purchase-btn" data-agent-id="${a.id}" data-skill-name="${name}">
+ Buy for ${(price.amount / 1e6).toFixed(2)} USDC
+ </button>`;
+ }
+ }
+ return `<span class="skill-entry">${escapeHtml(name)}${badgeOrButton}</span>`;
+ }).join(' ')
+ : '<div>This Agent has no skills defined.</div>';
+```
+
+## Tracking
+- To mark this task as complete, check all boxes in the instructions and change the status in the frontmatter to `Completed`.
diff --git a/tasks/monetization-feature/07-frontend-add-purchase-button.md b/tasks/monetization-feature/07-frontend-add-purchase-button.md
new file mode 100644
index 000000000..ea2ecb311
--- /dev/null
+++ b/tasks/monetization-feature/07-frontend-add-purchase-button.md
@@ -0,0 +1,93 @@
+---
+status: not-started
+---
+
+# Prompt 7: Add Purchase Button to UI
+
+**Status:** Not Started
+
+## Objective
+Update the agent detail page in the marketplace to display a "Purchase" or "Unlock" button next to paid skills that the user has not yet purchased.
+
+## Explanation
+Now that the backend can identify priced skills, we need to provide a clear call-to-action for the user. This prompt focuses on the UI changes required to show the correct button based on the skill's price and the user's purchase history. This is the first step in building the frontend purchasing flow.
+
+## Instructions
+
+1. **Fetch User's Purchased Skills:**
+ * In `src/marketplace.js`, when the marketplace page loads, make a call to the new `/api/user/purchased-skills` endpoint if the user is logged in.
+ * Store the returned list of purchased skills in a variable accessible by the `renderDetail` function.
+
+2. **Modify the `renderDetail` Function:**
+ * Inside the `renderDetail` function, you already have logic to display a price badge. Now, extend that logic.
+ * For each skill, perform the following checks:
+ a. Does the skill have a price? (`skillPrices[name]`)
+ b. If it has a price, has the current user already purchased this skill for this agent? (Check against the list of purchased skills).
+ * Render the UI conditionally:
+ * If the skill has no price, show the "Free" badge.
+ * If the skill has a price and the user **has not** purchased it, show the price and a "Purchase" button.
+ * If the skill has a price and the user **has** purchased it, show an "Owned" or "Unlocked" badge and disable or hide the purchase button.
+
+## Code Example (Frontend - `src/marketplace.js`)
+
+```javascript
+// In src/marketplace.js, assuming `userPurchases` is fetched and available
+
+// Inside renderDetail function
+const userPurchasesForThisAgent = userPurchases[a.id] || [];
+const skillPrices = a.skill_prices || {};
+
+$('d-skills').innerHTML = skillsArr.length
+ ? skillsArr.map((s) => {
+ const name = typeof s === 'string' ? s : (s.name || '');
+ const price = skillPrices[name];
+ let badge = `<span class="price-badge price-free">Free</span>`;
+
+ if (price) {
+ const isPurchased = userPurchasesForThisAgent.includes(name);
+ const priceDisplay = (price.amount / 1e6).toFixed(2);
+
+ if (isPurchased) {
+ badge = `<span class="price-badge price-owned">✓ Owned</span>`;
+ } else {
+ badge = `
+ <span class="price-badge price-paid">${priceDisplay} USDC</span>
+ <button class="btn-purchase" data-agent-id="${a.id}" data-skill-name="${name}">
+ Purchase
+ </button>
+ `;
+ }
+ }
+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
+ }).join(' ')
+ : '<div>This Agent has no skills defined.</div>';
+
+// Add event listeners for the new buttons after setting innerHTML
+document.querySelectorAll('.btn-purchase').forEach(btn => {
+ btn.addEventListener('click', handlePurchaseClick);
+});
+```
+
+## CSS Example (add to `/marketplace.css`)
+
+```css
+.btn-purchase {
+ margin-left: 8px;
+ padding: 3px 8px;
+ font-size: 10px;
+ background-color: #fde047;
+ color: #1c1917;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+ font-weight: 600;
+ transition: background-color 0.2s;
+}
+.btn-purchase:hover {
+ background-color: #facc15;
+}
+.price-owned {
+ color: #a7f3d0;
+ background-color: rgba(52, 211, 153, 0.1);
+}
+```