Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: Implement monetization features including skill access control, purchase flow, and creator earnings dashboard
nirholase16e153f584c
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 975137fc2..a5a049e92 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -991,3 +991,41 @@ create table if not exists pumpfun_graduations (create index if not exists pumpfun_graduations_seen_at on pumpfun_graduations(seen_at desc);create index if not exists pumpfun_graduations_mint on pumpfun_graduations(mint);create index if not exists pumpfun_graduations_creator on pumpfun_graduations(creator) where creator is not null;++-- ── agent_skill_prices ───────────────────────────────────────────────────────+-- Stores pricing information for premium agent skills.+CREATE TABLE IF NOT EXISTS agent_skill_prices (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ skill_id TEXT NOT NULL,+ creator_id UUID NOT NULL REFERENCES users(id),+ amount BIGINT NOT NULL CHECK (amount > 0),+ currency_mint TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ deleted_at TIMESTAMPTZ+);++CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_skill_prices_one_price_per_skill+ON agent_skill_prices (agent_id, skill_id)+WHERE deleted_at IS NULL;++CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_creator_id ON agent_skill_prices(creator_id);++-- ── agent_skill_prices — monetization for agent skills ──────────────────────+CREATE TABLE IF NOT EXISTS agent_skill_prices (+ agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ skill_id TEXT NOT NULL,+ amount BIGINT NOT NULL CHECK (amount > 0),+ currency_mint TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ PRIMARY KEY (agent_id, skill_id)+);++CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);++CREATE TRIGGER set_timestamp+BEFORE UPDATE ON agent_skill_prices+FOR EACH ROW+EXECUTE PROCEDURE set_updated_at();diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex 9d37af1d0..c9a032260 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -337,6 +337,27 @@ async function handleDetail(req, res, id) {priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain }]),);+ return json(+ res,+ 200,+ { data: { agent: { ...toDetail(row, skill_prices), bookmarked } } },+ { 'cache-control': 'public, max-age=15' },+ );+ const [auth] = await Promise.all([+ resolveAuth(req).catch(() => null),+ ]);++ let bookmarked = false;+ if (auth) {+ const [b] =+ await sql`SELECT 1 AS x FROM agent_bookmarks WHERE user_id = ${auth.userId} AND agent_id = ${id}`;+ bookmarked = !!b;+ }++ const skill_prices = Object.fromEntries(+ priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain }]),+ );+return json(res,200,@@ -581,7 +602,7 @@ function toCard(row) {};}-function toDetail(row) {+function toDetail(row, skill_prices = {}) {return {...toCard(row),system_prompt: row.system_prompt,@@ -590,5 +611,6 @@ function toDetail(row) {fork_of: row.fork_of || null,author_name: row.author_name || null,author_avatar: row.author_avatar || null,+ skill_prices,};}diff --git a/app.html b/app.htmlindex 3430a0463..0d3e05bb0 100644--- a/app.html+++ b/app.html@@ -63,6 +63,9 @@></h1><div id="nav-container"></div>+ <div class="header-actions">+ <button id="connect-wallet-btn">Connect Wallet</button>+ </div></header><script src="/nav.js"></script>id="make-widget-btn"diff --git a/docs/monetization-feature/03-backend-create-user-purchases-table.md b/docs/monetization-feature/03-backend-create-user-purchases-table.mdnew file mode 100644index 000000000..767762101--- /dev/null+++ b/docs/monetization-feature/03-backend-create-user-purchases-table.md@@ -0,0 +1,55 @@+---+status: not-started+---++# Prompt 3: Create User Purchases Table++**Status:** Not Started++## Objective+Create a database table to track which users have purchased which skills.++## Explanation+To manage access to paid skills, we need to record every successful purchase. A `user_skill_purchases` table will store the relationship between a user, an agent, and a specific skill they've bought. This table will be the source of truth for skill ownership.++## Instructions+1. **Create a new migration file:**+ - Create a migration file (e.g., `1683159000_create_user_skill_purchases.js`).++2. **Define the table schema:**+ - The table should include:+ - `id`: Primary key.+ - `user_id`: Foreign key referencing the `users` table.+ - `agent_id`: Foreign key referencing the `agents` table.+ - `skill_name`: The name of the purchased skill.+ - `purchase_price`: The amount paid for the skill at the time of purchase.+ - `purchase_currency`: The currency mint used for the purchase.+ - `transaction_signature`: The signature of the on-chain transaction.+ - `purchased_at`: Timestamp of the purchase.++3. **Add constraints:**+ - Create a unique constraint on `(user_id, agent_id, skill_name)`.+ - Add indexes on `user_id` and `agent_id` for performance.++## Code Example (SQL)++```sql+CREATE TABLE user_skill_purchases (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,+ skill_name VARCHAR(255) NOT NULL,+ purchase_price BIGINT NOT NULL,+ purchase_currency VARCHAR(255) NOT NULL,+ transaction_signature VARCHAR(255) UNIQUE NOT NULL,+ purchased_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ UNIQUE(user_id, agent_id, skill_name)+);++CREATE INDEX idx_user_skill_purchases_user_id ON user_skill_purchases(user_id);+CREATE INDEX idx_user_skill_purchases_agent_id ON user_skill_purchases(agent_id);+```++## Verification+- Run the migration and check the database for the new `user_skill_purchases` table.+- Ensure all columns, constraints, and indexes are correctly defined.diff --git a/docs/monetization-feature/04-backend-purchase-skill-endpoint.md b/docs/monetization-feature/04-backend-purchase-skill-endpoint.mdnew file mode 100644index 000000000..166e42dc6--- /dev/null+++ b/docs/monetization-feature/04-backend-purchase-skill-endpoint.md@@ -0,0 +1,84 @@+---+status: not-started+---++# Prompt 4: Create Purchase Skill API Endpoint++**Status:** Not Started++## Objective+Create a backend API endpoint to handle the initiation of a skill purchase.++## Explanation+When a user decides to buy a skill, the frontend needs to communicate with the backend to start the transaction. This endpoint (`/api/skills/purchase`) will be responsible for validating the request, checking that the skill is for sale, and returning the necessary information for the frontend to proceed with the payment flow (e.g., a Solana Pay transaction request URL).++## Instructions+1. **Create the API route:**+ - Create a new file for the purchase logic, e.g., `api/skills/purchase.js`.+ - This endpoint should handle `POST` requests.++2. **Implement request handling:**+ - The request body should contain the `agent_id` and `skill_name` to be purchased.+ - The endpoint must be authenticated, so ensure you have the user's ID from their session.+ - **Validation:**+ - Check if the user has already purchased the skill by querying the `user_skill_purchases` table.+ - Fetch the skill's price from the `agent_skill_prices` table. If no price is found, return an error.++3. **Generate transaction details:**+ - If the request is valid, generate the parameters needed for a Solana Pay transaction. This includes:+ - The recipient's public key (the agent creator's wallet).+ - The amount to be transferred.+ - The SPL token mint address (e.g., USDC).+ - A unique reference key for the transaction.++4. **Return the response:**+ - The API should return a JSON object containing the Solana Pay URL or the transaction parameters that the frontend can use to initiate the payment.++## Code Example (Node.js/Express-like)++```javascript+// api/skills/purchase.js++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ return res.status(405).json({ error: 'Method Not Allowed' });+ }++ const { agentId, skillName } = req.body;+ const userId = await getUserIdFromSession(req); // Assume you have this function++ if (!userId) {+ return res.status(401).json({ error: 'Unauthorized' });+ }++ // 1. Check if already purchased+ const existingPurchase = await db.query(+ 'SELECT id FROM user_skill_purchases WHERE user_id = $1 AND agent_id = $2 AND skill_name = $3',+ [userId, agentId, skillName]+ );+ if (existingPurchase.rows.length > 0) {+ return res.status(409).json({ error: 'Skill already purchased' });+ }++ // 2. Get skill price+ const priceResult = await db.query(+ 'SELECT amount, currency_mint FROM agent_skill_prices WHERE agent_id = $1 AND skill_name = $2',+ [agentId, skillName]+ );+ if (priceResult.rows.length === 0) {+ return res.status(404).json({ error: 'Skill not for sale' });+ }+ const price = priceResult.rows[0];++ // 3. (To be implemented in next step) Generate Solana Pay URL+ const { solanaPayUrl } = await generateSolanaPayUrl(price);++ // 4. Return response+ res.status(200).json({ solanaPayUrl });+}+```++## Verification+- Test the endpoint using a tool like Postman or `curl`.+- Verify that it correctly handles cases like unauthenticated requests, already purchased skills, and skills that are not for sale.+- Check that it returns the expected transaction details for a valid request.diff --git a/docs/monetization-prompts/02-purchase-skill-button.md b/docs/monetization-prompts/02-purchase-skill-button.mdindex 731533c75..02314968d 100644--- a/docs/monetization-prompts/02-purchase-skill-button.md+++ b/docs/monetization-prompts/02-purchase-skill-button.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 02: Add Purchase Button for Priced Skills## Objective@@ -7,11 +11,11 @@ Add a "Purchase" button next to paid skills on the agent detail page, creating aWith 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.+- [ ] **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`)diff --git a/docs/monetization-prompts/03-skill-purchase-modal.md b/docs/monetization-prompts/03-skill-purchase-modal.mdindex bf996e7b6..87f42d96f 100644--- a/docs/monetization-prompts/03-skill-purchase-modal.md+++ b/docs/monetization-prompts/03-skill-purchase-modal.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 03: Create Skill Purchase Modal## Objective@@ -7,14 +11,14 @@ Create a modal that appears when a user clicks the "Purchase" button, confirmingA 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.+- [ ] **Create the Modal HTML:**+ - [ ] Add the HTML structure for a hidden modal to `marketplace.html`. It should include placeholders for the skill name, price, and agent name, along with "Confirm Purchase" and "Cancel" buttons.++- [ ] **Add JavaScript Logic (`src/marketplace.js`):**+ - [ ] Create a new function, `openPurchaseModal(skillName, price, agentName)`. This function will populate the modal with the correct data and make it visible.+ - [ ] Attach an event listener to the `d-skills` container that listens for clicks on `.purchase-btn`.+ - [ ] When a purchase button is clicked, get the skill name from the `data-skill-name` attribute, find its price from the agent data, and call `openPurchaseModal`.+ - [ ] Add event listeners for the "Confirm" and "Cancel" buttons within the modal. For now, they can just log to the console.## HTML Example (in `marketplace.html`)diff --git a/docs/monetization-prompts/04-wallet-integration-setup.md b/docs/monetization-prompts/04-wallet-integration-setup.mdindex db9be09f5..81caaf2c5 100644--- a/docs/monetization-prompts/04-wallet-integration-setup.md+++ b/docs/monetization-prompts/04-wallet-integration-setup.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 04: Frontend Wallet Integration Setup## Objective@@ -7,17 +11,17 @@ Integrate a Solana wallet adapter to allow users to connect their wallets (e.g.,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.+- [ ] **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.+- [ ] **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.+- [ ] **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)diff --git a/docs/monetization-prompts/05-solana-pay-integration.md b/docs/monetization-prompts/05-solana-pay-integration.mdindex 1b394012f..7eb3a6193 100644--- a/docs/monetization-prompts/05-solana-pay-integration.md+++ b/docs/monetization-prompts/05-solana-pay-integration.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 05: Solana Pay Transaction Integration## Objective@@ -7,22 +11,22 @@ Integrate Solana Pay into the purchase modal to generate a transaction for the uWhen 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.+- [ ] **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.+- [ ] **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).+- [ ] **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)diff --git a/docs/monetization-prompts/06-transaction-status-polling.md b/docs/monetization-prompts/06-transaction-status-polling.mdindex 7b1d408d0..37bdb3d50 100644--- a/docs/monetization-prompts/06-transaction-status-polling.md+++ b/docs/monetization-prompts/06-transaction-status-polling.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 06: Transaction Status Polling and Verification## Objective@@ -7,20 +11,20 @@ After a transaction is sent, reliably confirm its success by polling a Solana RPSending 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).+- [ ] **Frontend: Poll for Confirmation:**+ - [ ] After sending the transaction with `sendTransaction`, the wallet adapter returns a transaction signature (txid).+ - [ ] Use the `Connection` object's `confirmTransaction` method. This will poll the RPC until the transaction reaches a certain commitment level (e.g., 'processed' or 'confirmed').+ - [ ] While polling, update the UI to show a "Processing..." state in the purchase modal.++- [ ] **Backend: Create a Verification Endpoint:**+ - [ ] Create a new backend endpoint, e.g., `POST /api/skills/purchase/verify`.+ - [ ] This endpoint will receive the `transactionSignature`.+ - [ ] On the backend, use the Solana SDK to fetch the transaction details using the signature.++- [ ] **Backend: Verify Transaction Details:**+ - [ ] In the verification endpoint, inspect the fetched transaction.+ - [ ] Confirm that the transaction involves the correct sender (buyer), receiver (creator), and amount (price). This is a critical security step to prevent users from submitting fake or incorrect transaction signatures.+ - [ ] If the transaction is valid, proceed to record the skill ownership (covered in the next prompt).## JavaScript Example (`src/marketplace.js` - inside confirm button handler)diff --git a/docs/monetization-prompts/07-ui-feedback-on-purchase.md b/docs/monetization-prompts/07-ui-feedback-on-purchase.mdindex 035b10aa0..625809b0f 100644--- a/docs/monetization-prompts/07-ui-feedback-on-purchase.md+++ b/docs/monetization-prompts/07-ui-feedback-on-purchase.md@@ -1,72 +1,28 @@-# Prompt 7: Update UI with Purchase Status (Loading, Success, Error)+---+status: not-started+----**Status:** - [ ] Not Started+# Prompt 07: UI Feedback for Purchase Flow## Objective-Provide real-time feedback to the user during and after the purchase process by updating the UI to show loading, success, and error states.+Provide clear, real-time UI feedback to the user during the entire purchase process (e.g., processing, success, failure).## Explanation-A good user experience requires clear communication about the status of an action. After a user confirms a purchase, they should see a loading indicator. Once the transaction is processed and verified, the UI should update to show either a success message and reflect the new ownership status, or an error message if something went wrong.+A good user experience requires keeping the user informed. We will enhance the purchase modal to reflect the current state of the transaction, from initiation to completion.## Instructions-1. **Add Loading State:**- * In `src/marketplace.js`, when the "Confirm Purchase" button is clicked, disable the button and show a loading indicator within the modal.+- [ ] **Enhance the Modal HTML:**+ - [ ] Add elements to the purchase modal to display different states: a loading spinner for processing, a success message/icon, and an error message/icon.-2. **Handle Success State:**- * After the backend verification endpoint returns a success response:- * Close the purchase modal.- * Re-render the skills list for the agent, or dynamically update the specific skill entry that was just purchased. It should now show the "Owned" badge instead of the "Purchase" button.- * Show a success toast message (e.g., "Purchase successful!").+- [ ] **Create a UI State Management Function:**+ - [ ] In `src/marketplace.js`, create a function like `setModalState(state, message)`.+ - [ ] This function will accept states like 'confirm', 'processing', 'success', and 'error'.+ - [ ] Based on the state, it will show/hide the appropriate elements in the modal (e.g., hide confirm/cancel buttons, show spinner).-3. **Handle Error State:**- * If the Solana transaction fails on the client-side, or if the backend verification endpoint returns an error:- * Display a clear error message to the user, either in the modal or as a toast.- * Re-enable the "Confirm Purchase" button so the user can try again.+- [ ] **Integrate State Changes into Purchase Logic:**+ - [ ] Call `setModalState` at key points in the purchase flow:+ - [ ] When the confirm button is first clicked, before sending the transaction: `setModalState('processing')`.+ - [ ] If the transaction is successfully confirmed on the frontend and verified on the backend: `setModalState('success', 'Purchase Complete!')`.+ - [ ] If any step fails (user rejects, transaction fails, backend verification fails): `setModalState('error', 'Something went wrong.')`.-## Code Example (JavaScript in `src/marketplace.js`)--```javascript-// Inside the 'click' event listener for modal-confirm-purchase-btn-const confirmBtn = $('modal-confirm-purchase-btn');--confirmBtn.disabled = true;-confirmBtn.textContent = 'Processing...';--try {- // 1. Send Solana Transaction- const signature = await wallet.sendTransaction(transaction, connection);- await connection.confirmTransaction(signature, 'processed');-- // 2. Call Backend for Verification- const response = await fetch('/api/marketplace/purchase-skill', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ agentId, skillName, transactionSignature: signature }),- });-- if (!response.ok) {- throw new Error('Backend verification failed.');- }-- // 3. Handle Success- showToast('Purchase successful!', 'success');- purchaseModal.style.display = 'none';- // You would need to re-fetch the user's skills and re-render the detail view- // to show the 'Owned' status.- // For simplicity, we can just reload the agent details.- const agentId = window.currentAgent.id;- loadAgentDetail(agentId);--} catch (error) {- // 4. Handle Error- console.error('Purchase failed:', error);- showToast(`Purchase failed: ${error.message}`, 'error');- confirmBtn.disabled = false;- confirmBtn.textContent = 'Confirm Purchase';-}--// A simple toast function-function showToast(message, type = 'info') {- // Implementation of a toast notification system-}-```+## HTML Example (Enhanced Modal)diff --git a/docs/monetization-prompts/08-purchase-skill-api-endpoint.md b/docs/monetization-prompts/08-purchase-skill-api-endpoint.mdindex 91f16af9d..9455bd880 100644--- a/docs/monetization-prompts/08-purchase-skill-api-endpoint.md+++ b/docs/monetization-prompts/08-purchase-skill-api-endpoint.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 08: Backend Purchase API Endpoint## Objective@@ -7,26 +11,26 @@ Create the initial backend API endpoint that constructs and returns a Solana traThe 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.+- [ ] **Create the API File and Route:**+ - [ ] Create a new API file, e.g., `api/transactions/create-skill-purchase.js`.+ - [ ] This file will handle `POST` requests. It should expect `agentId`, `skillName`, and `buyerPublicKey` in the request body.++- [ ] **Fetch Necessary Data:**+ - [ ] Inside the endpoint logic, perform database lookups to get:+ - [ ] The skill's price from the `agent_skill_prices` table.+ - [ ] The agent creator's payout wallet address from the `users` or `agents` table.+ - [ ] The platform's fee wallet address (can be a constant or from a config file).++- [ ] **Construct the Solana Transaction:**+ - [ ] Use the `@solana/web3.js` SDK.+ - [ ] You will be creating a SPL Token Transfer instruction. The currency is likely USDC, so you'll need its mint address.+ - [ ] The transaction will transfer `X` amount of USDC from the `buyerPublicKey` to the creator's wallet. (Platform fees will be added in a later prompt).+ - [ ] Set the `feePayer` to be the `buyerPublicKey`.+ - [ ] Fetch a recent blockhash.++- [ ] **Serialize and Return the Transaction:**+ - [ ] Serialize the transaction but **do not sign it**. The user's wallet must sign it.+ - [ ] Return the serialized transaction as a base64-encoded string in the JSON response.## Code Example (Node.js with Express-like framework)diff --git a/docs/monetization-prompts/09-verify-solana-transaction-api.md b/docs/monetization-prompts/09-verify-solana-transaction-api.mdindex 68b7ebf31..b600feba6 100644--- a/docs/monetization-prompts/09-verify-solana-transaction-api.md+++ b/docs/monetization-prompts/09-verify-solana-transaction-api.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 09: Backend Transaction Verification API## Objective@@ -7,26 +11,26 @@ Create the backend API endpoint that securely verifies a Solana transaction signThis 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.+- [ ] **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.+- [ ] **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).+- [ ] **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."+- [ ] **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)diff --git a/docs/monetization-prompts/10-record-skill-ownership.md b/docs/monetization-prompts/10-record-skill-ownership.mdindex 2816af465..d3ef9cbe2 100644--- a/docs/monetization-prompts/10-record-skill-ownership.md+++ b/docs/monetization-prompts/10-record-skill-ownership.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 10: Record Skill Ownership in Database## Objective@@ -7,29 +11,29 @@ Create the database schema and logic to record that a user has successfully purcAfter 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.+- [ ] **Design and Create a New Database Table:**+ - [ ] Create a new table named `unlocked_skills` (or similar).+ - [ ] It should contain, at a minimum, the following columns:+ - [ ] `id` (Primary Key)+ - [ ] `user_id` (Foreign Key to your `users` table)+ - [ ] `agent_id` (Foreign Key to your `agents` table)+ - [ ] `skill_name` (String)+ - [ ] `purchase_transaction_signature` (String, for auditing)+ - [ ] `created_at` (Timestamp)+ - [ ] Consider adding a unique constraint on `(user_id, agent_id, skill_name)` to prevent duplicate entries.++- [ ] **Implement the Database Insertion Logic:**+ - [ ] In your backend verification endpoint (`/api/skills/purchase/verify`), after all the checks have passed, add the code to insert a new row into the `unlocked_skills` table.+ - [ ] Pass the authenticated user's ID, the agent ID, the skill name, and the transaction signature to the database query.++- [ ] **Update Agent Details API to Include Ownership:**+ - [ ] Modify the main API that fetches agent details for the marketplace (`/api/marketplace/agents/:id`).+ - [ ] When a user requests this endpoint, it should now also query the `unlocked_skills` table to see which skills that specific user owns for that agent.+ - [ ] Include this ownership information in the API response, perhaps as an array of skill names: `unlocked_skills: ["skill1", "skill2"]`.++- [ ] **Update Frontend to Use Ownership Data:**+ - [ ] In `src/marketplace.js`, when you receive the agent details, use the new `unlocked_skills` array.+ - [ ] In your skill rendering loop, set the `isOwned` variable based on whether the current skill's name is in this array. This will now correctly show the "Purchase" or "Unlocked" button.## SQL Schema Examplediff --git a/docs/monetization-prompts/11-api-security-for-purchase.md b/docs/monetization-prompts/11-api-security-for-purchase.mdindex dd71b478d..684c0ea9c 100644--- a/docs/monetization-prompts/11-api-security-for-purchase.md+++ b/docs/monetization-prompts/11-api-security-for-purchase.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 11: API Security for Purchase Flow## Objective@@ -7,26 +11,26 @@ Implement essential security measures, including user authentication and input vMonetization 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.+- [ ] **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.+- [ ] **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.+- [ ] **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)diff --git a/docs/monetization-prompts/12-creator-payout-setup.md b/docs/monetization-prompts/12-creator-payout-setup.mdindex ef8b775a1..b1a8a550d 100644--- a/docs/monetization-prompts/12-creator-payout-setup.md+++ b/docs/monetization-prompts/12-creator-payout-setup.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 12: Creator Payout Wallet Setup## Objective@@ -7,22 +11,22 @@ Allow agent creators to specify and save a Solana wallet address for receiving pTo 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.+- [ ] **Update Database Schema:**+ - [ ] Add a new column to your `users` table (or whichever table represents your creators).+ - [ ] The column should be named `payout_wallet_address` or similar.+ - [ ] It should be a `VARCHAR` or `TEXT` field, capable of storing a Solana public key (e.g., up to 44 characters). It can be nullable, as a user might not be a creator.++- [ ] **Create API Endpoint for Saving Wallet Address:**+ - [ ] Create a new API endpoint, e.g., `PUT /api/users/payout-settings`.+ - [ ] This endpoint should be protected by authentication middleware.+ - [ ] It will accept a new `payout_wallet_address` in the request body.+ - [ ] Validate that the provided string is a valid Solana public key.+ - [ ] Update the `payout_wallet_address` for the authenticated user in the database.++- [ ] **Update "Create Transaction" Endpoint:**+ - [ ] Modify the `POST /api/transactions/create-skill-purchase` endpoint.+ - [ ] When fetching creator details, retrieve the new `payout_wallet_address`.+ - [ ] Use this address as the destination for the payment transfer in the Solana transaction. If the address is not set, the transaction should fail with an error indicating the creator has not configured their payouts.## SQL Schema Example (Alter Table)diff --git a/docs/monetization-prompts/13-platform-fee-logic.md b/docs/monetization-prompts/13-platform-fee-logic.mdindex 60c91f452..53d0297ee 100644--- a/docs/monetization-prompts/13-platform-fee-logic.md+++ b/docs/monetization-prompts/13-platform-fee-logic.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 13: Platform Fee Logic## Objective@@ -7,25 +11,25 @@ Implement the logic to automatically take a platform fee from each skill purchasA 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.+- [ ] **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.+- [ ] **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.+- [ ] **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.+- [ ] **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)diff --git a/docs/monetization-prompts/14-creator-dashboard-backend.md b/docs/monetization-prompts/14-creator-dashboard-backend.mdindex 504c8ab8f..bc2c581b5 100644--- a/docs/monetization-prompts/14-creator-dashboard-backend.md+++ b/docs/monetization-prompts/14-creator-dashboard-backend.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 14: Creator Dashboard - Backend## Objective@@ -7,24 +11,24 @@ Create the backend API endpoints required to power a dashboard for creators to tTo 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`).+- [ ] **Design API Endpoints:**+ - [ ] Plan a few key endpoints for the creator dashboard. For example:+ - [ ] `GET /api/creator/dashboard/stats`: Returns key stats like total revenue, total sales, and average sale price.+ - [ ] `GET /api/creator/dashboard/sales-history`: Returns a paginated list of individual sales, including skill name, date, and amount earned.+ - [ ] `GET /api/creator/dashboard/sales-by-skill`: Returns an aggregate of sales grouped by skill name.++- [ ] **Implement `stats` Endpoint:**+ - [ ] This endpoint should be protected by authentication.+ - [ ] It needs to query your transaction or unlocked skills database.+ - [ ] To get total revenue, you'll need to join your `unlocked_skills` table with `agent_skill_prices` and filter by the agents owned by the current user (`req.user.id`).+ - [ ] Sum the prices of all skills sold. Remember to subtract the platform fee from the creator's view of revenue.+ - [ ] Return the aggregated data as a JSON object.++- [ ] **Implement `sales-history` Endpoint:**+ - [ ] This endpoint will also perform a join similar to the stats endpoint.+ - [ ] Instead of aggregating, it will return a list of individual sales records.+ - [ ] Implement pagination using `LIMIT` and `OFFSET` in your SQL query (or the equivalent in your ORM) to handle potentially large numbers of sales.+ - [ ] Return the list and pagination metadata (e.g., `total_pages`, `current_page`).## Database Query Example (PostgreSQL for Stats)diff --git a/docs/monetization-prompts/15-skill-pricing-management-ui.md b/docs/monetization-prompts/15-skill-pricing-management-ui.mdindex 6688edd44..98523de5c 100644--- a/docs/monetization-prompts/15-skill-pricing-management-ui.md+++ b/docs/monetization-prompts/15-skill-pricing-management-ui.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 15: Skill Pricing Management - UI## Objective@@ -7,18 +11,18 @@ Create a user interface on the agent creation/editing page that allows creatorsCreators 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.+- [ ] **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.+- [ ] **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)diff --git a/docs/monetization-prompts/16-skill-pricing-management-api.md b/docs/monetization-prompts/16-skill-pricing-management-api.mdindex 8ce459253..6e83ad457 100644--- a/docs/monetization-prompts/16-skill-pricing-management-api.md+++ b/docs/monetization-prompts/16-skill-pricing-management-api.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 16: Skill Pricing Management - API## Objective@@ -7,27 +11,27 @@ Create the backend API endpoint to allow creators to save the prices they set foThis 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)`.+- [ ] **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.+- [ ] **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.+- [ ] **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.+- [ ] **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)diff --git a/docs/monetization-prompts/17-creator-payout-settings-ui.md b/docs/monetization-prompts/17-creator-payout-settings-ui.mdindex 31e889f78..89bcc63bb 100644--- a/docs/monetization-prompts/17-creator-payout-settings-ui.md+++ b/docs/monetization-prompts/17-creator-payout-settings-ui.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 17: Creator Payout Settings - UI## Objective@@ -7,21 +11,21 @@ Create a user interface in the user's settings or profile page for them to managTo 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.+- [ ] **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.+- [ ] **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)diff --git a/docs/monetization-prompts/18-creator-dashboard-ui.md b/docs/monetization-prompts/18-creator-dashboard-ui.mdindex 07fb69a15..9a85a31a6 100644--- a/docs/monetization-prompts/18-creator-dashboard-ui.md+++ b/docs/monetization-prompts/18-creator-dashboard-ui.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 18: Creator Dashboard - UI## Objective@@ -7,23 +11,23 @@ Build the frontend for the creator dashboard, visualizing the sales and earningsA 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.+- [ ] **Create the Dashboard Page:**+ - [ ] Create a new HTML file, e.g., `creator-dashboard.html`.+ - [ ] Create a corresponding JavaScript file, e.g., `src/creator-dashboard.js`.++- [ ] **Fetch and Display Key Stats:**+ - [ ] On page load, make a request to the `GET /api/creator/dashboard/stats` endpoint.+ - [ ] Display the returned stats (total revenue, total sales) in prominent "stat cards" at the top of the page.+ - [ ] Remember to format the revenue from the smallest unit to a human-readable number.++- [ ] **Display Sales History:**+ - [ ] Make a request to the `GET /api/creator/dashboard/sales-history` endpoint.+ - [ ] Render the returned list of sales in a table. The table should include columns like "Date", "Skill Name", "Agent", "Price", and "Earnings".++- [ ] **Add a Chart (Optional but recommended):**+ - [ ] Include a charting library like Chart.js or D3.+ - [ ] Make a request to an endpoint that provides time-series data (e.g., `GET /api/creator/dashboard/revenue-over-time`). You may need to create this endpoint.+ - [ ] Render a line or bar chart showing daily or weekly earnings.## HTML Structure Example (`creator-dashboard.html`)diff --git a/docs/monetization-prompts/19-skill-bundling.md b/docs/monetization-prompts/19-skill-bundling.mdnew file mode 100644index 000000000..f1dcf89e3--- /dev/null+++ b/docs/monetization-prompts/19-skill-bundling.md@@ -0,0 +1,63 @@+# Prompt 19: Skill Bundles and Packages++**Status:** - [ ] Not Started++## Objective+Allow creators to bundle multiple skills together and sell them as a package, often at a discounted price compared to buying each skill individually.++## Explanation+Bundling is a common and effective marketing strategy. It increases the perceived value for customers and can lead to larger average transaction sizes. For example, a creator could offer a "starter pack" of their three most popular skills.++## Instructions+1. **Database Schema for Bundles:**+ * Create a `skill_bundles` table:+ * Columns: `id`, `creator_id`, `name`, `description`, `price`, `currency_mint`.+ * Create a `skill_bundle_items` table to link skills to bundles:+ * Columns: `id`, `bundle_id`, `skill_name`, `agent_id`.++2. **UI for Creating Bundles:**+ * In the creator's dashboard or agent edit page, add an interface for "Create a Skill Bundle".+ * The creator should be able to:+ * Give the bundle a name and description.+ * Select which of their skills to include.+ * Set a single price for the entire bundle.++3. **Display Bundles in the Marketplace:**+ * On the agent detail page, in addition to individual skills, display any bundles offered by the creator.+ * Each bundle listing should show the included skills and the bundle price.+ * The UI should clearly show the savings compared to buying the skills individually.++4. **Handle Bundle Purchases:**+ * The purchase flow for a bundle is similar to a single skill.+ * When the backend's `purchase-skill` endpoint is adapted to handle bundles (e.g., a new `purchase-bundle` endpoint), it must:+ * Verify the single payment for the bundle.+ * Add a record to the `user_agent_skills` table for *each* skill included in the bundle.++## Code Example (Conceptual - `purchase-bundle` backend endpoint)++```javascript+export default async function handler(req, res) {+ const userId = req.user.id;+ const { bundleId, transactionSignature } = req.body;++ const db = getDB();+ const bundle = await db.getBundle(bundleId);++ // 1. Verify the transaction for the bundle's price+ // ... (similar to single skill verification)++ if (verificationSuccess) {+ // 2. Get all skills included in the bundle+ const skillsInBundle = await db.getSkillsInBundle(bundleId);++ // 3. Record ownership for each skill in the bundle+ for (const item of skillsInBundle) {+ await db.recordSkillPurchase(userId, item.agent_id, item.skill_name);+ }++ res.status(200).json({ success: true, message: 'Bundle purchased!' });+ } else {+ // ... handle error+ }+}+```diff --git a/docs/monetization-prompts/19-skill-gating-logic.md b/docs/monetization-prompts/19-skill-gating-logic.mdindex 21235ebd4..db0a84a3c 100644--- a/docs/monetization-prompts/19-skill-gating-logic.md+++ b/docs/monetization-prompts/19-skill-gating-logic.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 19: Skill Usage Gating## Objective@@ -7,20 +11,20 @@ Implement the core logic that prevents users from using a paid skill unless theyThis 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."+- [ ] **Locate the Skill Execution Logic:**+ - [ ] Find the part of your backend code that is responsible for executing an agent's skill. This might be in a chat API, a general agent interaction endpoint, or a dedicated skill execution endpoint.++- [ ] **Add a Pre-Execution Check:**+ - [ ] Before the skill's code is run, insert a new checking mechanism.+ - [ ] This check needs to know which user is making the request, which agent is being used, and which skill is being invoked.++- [ ] **Perform Ownership Verification:**+ - [ ] Inside the check, first determine if the skill in question is a paid skill. Query the `agent_skill_prices` table for the agent and skill name.+ - [ ] If the skill is **not** in the prices table, it's free. Allow execution to proceed.+ - [ ] If the skill **is** in the prices table, it's a paid skill. You must now query the `unlocked_skills` table.+ - [ ] Check if a row exists in `unlocked_skills` for the current `user_id`, `agent_id`, and `skill_name`.+ - [ ] **If a row exists**, the user owns the skill. Allow execution to proceed.+ - [ ] **If no row exists**, the user does not own the skill. Block the execution and return an error message to the user, e.g., `402 Payment Required`, with a message like "You must purchase this skill to use it."## Code Example (Backend Skill Execution Endpoint)diff --git a/docs/monetization-prompts/20-batch-skill-purchase.md b/docs/monetization-prompts/20-batch-skill-purchase.mdindex d86855ebf..0e8efd4fd 100644--- a/docs/monetization-prompts/20-batch-skill-purchase.md+++ b/docs/monetization-prompts/20-batch-skill-purchase.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 20: Batch Skill Purchase (Shopping Cart)## Objective@@ -7,29 +11,29 @@ Allow users to add multiple skills to a "cart" and purchase them all in a singlePurchasing 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.+- [ ] **Frontend: Cart UI:**+ - [ ] Instead of a "Purchase" button, have an "Add to Cart" button.+ - [ ] Add a cart icon to the site header that shows the number of items.+ - [ ] Clicking the icon opens a cart modal/sidebar, listing the selected skills and the total price.+ - [ ] The cart should have a "Checkout" button.++- [ ] **Frontend: Cart State Management:**+ - [ ] Use `localStorage` or a simple in-memory object to manage the cart's state (the list of skills to be purchased).+ - [ ] When "Add to Cart" is clicked, add the skill's details (`agentId`, `skillName`) to the cart.+ - [ ] When "Checkout" is clicked, pass the list of items in the cart to the backend.++- [ ] **Backend: Update "Create Transaction" Endpoint:**+ - [ ] Modify `POST /api/transactions/create-skill-purchase` to accept an **array** of skills instead of a single skill.+ - [ ] The endpoint will now loop through the array of skills.+ - [ ] For each skill, it calculates the payment due to the respective creator.+ - [ ] It will add a separate `SPL Token Transfer` instruction **for each skill** to the transaction. If a user buys 3 skills from 3 different creators, the transaction will contain 3 transfers (plus 3 platform fee transfers).+ - [ ] The backend returns a single transaction that bundles all these transfers.++- [ ] **Backend: Update "Verify Transaction" Endpoint:**+ - [ ] The verification logic must also be updated to handle multiple items.+ - [ ] It will receive an array of skills that were supposed to be in the transaction.+ - [ ] It must parse the transaction from the blockchain and verify that **all** the expected transfers (to creators and platform) are present and correct.+ - [ ] If verification is successful, it should add a row to the `unlocked_skills` table for **each** purchased skill. This should be done in a database transaction.## API Request Body Example (for Create Transaction)diff --git a/docs/monetization-prompts/21-skill-subscription-model-backend.md b/docs/monetization-prompts/21-skill-subscription-model-backend.mdindex f591bfe40..cd7909db5 100644--- a/docs/monetization-prompts/21-skill-subscription-model-backend.md+++ b/docs/monetization-prompts/21-skill-subscription-model-backend.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 21: Skill Subscription Model - Backend## Objective@@ -7,30 +11,30 @@ Implement the backend infrastructure for a subscription model, where users pay aSubscriptions 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').+- [ ] **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.+- [ ] **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.+- [ ] **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).+- [ ] **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.+- [ ] **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 Examplediff --git a/docs/monetization-prompts/22-skill-subscription-model-frontend.md b/docs/monetization-prompts/22-skill-subscription-model-frontend.mdindex 78e41fb4a..0c2f19a36 100644--- a/docs/monetization-prompts/22-skill-subscription-model-frontend.md+++ b/docs/monetization-prompts/22-skill-subscription-model-frontend.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 22: Skill Subscription Model - Frontend## Objective@@ -7,28 +11,28 @@ Create the user interface for users to discover, purchase, and manage subscriptiFollowing 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.+- [ ] **Display Subscription Plans on Agent Page:**+ - [ ] On the agent detail page (`marketplace.html`), add a new section for subscriptions.+ - [ ] Fetch the agent's available subscription plans from the API (`GET /api/agents/:id/subscription-plans`).+ - [ ] Display the plans with their price and billing interval (e.g., "$10 / month").+ - [ ] Add a "Subscribe" button for each plan.++- [ ] **Subscription Purchase Flow:**+ - [ ] When a user clicks "Subscribe", make a request to the backend `POST /api/subscriptions/create` endpoint.+ - [ ] The backend will respond with a URL to the payment provider's checkout page (e.g., a Helio payment link).+ - [ ] Redirect the user to this URL to complete the payment and set up the recurring transaction.+ - [ ] The payment provider will handle the redirect back to your site.++- [ ] **UI State for Subscribed Users:**+ - [ ] When viewing an agent to whom the user is subscribed, the UI should reflect this.+ - [ ] Instead of "Subscribe", show "You are Subscribed".+ - [ ] All paid skills for that agent should automatically appear as "Unlocked". The skill gating logic on the backend will already handle access.++- [ ] **Subscription Management Page:**+ - [ ] Create a new "My Subscriptions" page for logged-in users.+ - [ ] This page will list all their active subscriptions.+ - [ ] For each subscription, it should show the agent, the price, and the next renewal date.+ - [ ] Include a "Manage" or "Cancel" button. This would typically link to the customer portal provided by the payment service (like Helio or Stripe) where users can manage their payment methods and cancellations.## JavaScript Example (Subscribe Button Click)diff --git a/docs/monetization-prompts/23-email-receipts.md b/docs/monetization-prompts/23-email-receipts.mdindex 00d99ba42..492be2f47 100644--- a/docs/monetization-prompts/23-email-receipts.md+++ b/docs/monetization-prompts/23-email-receipts.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 23: Email Receipts and Notifications## Objective@@ -7,23 +11,23 @@ Integrate an email service to send users receipts for their purchases and notifiProfessional 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.+- [ ] **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.+- [ ] **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.+- [ ] **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)diff --git a/docs/monetization-prompts/24-admin-monetization-dashboard.md b/docs/monetization-prompts/24-admin-monetization-dashboard.mdindex f5c0d3cb1..79b20cde8 100644--- a/docs/monetization-prompts/24-admin-monetization-dashboard.md+++ b/docs/monetization-prompts/24-admin-monetization-dashboard.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 24: Admin Monetization Dashboard## Objective@@ -7,29 +11,29 @@ Create a secure, internal dashboard for platform administrators to monitor the hWhile 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.**+- [ ] **Create a Secure Admin Area:**+ - [ ] Build a new section of the application that is only accessible to users with an 'admin' role. This requires role-based access control (RBAC) in your user authentication system.++- [ ] **Backend API for Admin Stats:**+ - [ ] Create a new set of protected API endpoints, e.g., under `/api/admin/stats/`.+ - [ ] These endpoints will perform platform-wide aggregations.+ - [ ] **Key metrics to expose:**+ - [ ] **Gross Transaction Volume (GTV):** Total value of all transactions processed.+ - [ ] **Platform Revenue:** Total fees collected by the platform.+ - [ ] **Top Earning Creators:** A list of creators ranked by their total earnings.+ - [ ] **Top Selling Skills/Agents:** A list of the most purchased skills and agents.+ - [ ] **New Subscriptions/Cancellations:** A time-series chart showing subscription growth.++- [ ] **Frontend UI for Admin Dashboard:**+ - [ ] Create a new UI for the admin area.+ - [ ] Use data visualization components (charts, tables, stat cards) to present the data fetched from the admin APIs.+ - [ ] The UI should allow filtering by date ranges to analyze performance over time.++- [ ] **Add Management Tools (Advanced):**+ - [ ] Beyond just viewing data, an admin dashboard can include tools for:+ - [ ] **Refunding a purchase:** A button to trigger a refund process (this is complex and involves on-chain transactions and database updates).+ - [ ] **Disabling a skill from sale:** A toggle to remove a problematic skill from the marketplace.+ - [ ] **Managing user roles.**## Admin API Response Example (`/api/admin/stats/overview`)diff --git a/docs/monetization-prompts/25-user-experience-onboarding.md b/docs/monetization-prompts/25-user-experience-onboarding.mdindex 46e5f0825..3fcce46ae 100644--- a/docs/monetization-prompts/25-user-experience-onboarding.md+++ b/docs/monetization-prompts/25-user-experience-onboarding.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 25: User Experience & Onboarding## Objective@@ -7,29 +11,29 @@ Refine the overall user experience for the monetization features and create cleaA 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.+- [ ] **Create a Creator Onboarding Guide:**+ - [ ] Write a clear, concise guide in your `docs` folder that explains how a creator can start monetizing their skills.+ - [ ] **Topics to cover:**+ - [ ] How to set up their payout wallet.+ - [ ] How to set prices for their skills.+ - [ ] How subscriptions work.+ - [ ] An explanation of the platform fee.+ - [ ] A link to their creator dashboard and an explanation of the metrics.++- [ ] **Add In-App Guidance (Tooltips & Helpers):**+ - [ ] Go through the creator-facing UIs (payout settings, skill pricing) and add tooltips or helper text to explain complex concepts.+ - [ ] For example, next to the payout wallet input, add a tooltip explaining what a Solana wallet is and where to get one.+ - [ ] On the skill pricing page, explain the units (e.g., "Enter price in USDC").++- [ ] **Refine the Buyer Experience:**+ - [ ] Review the entire purchase flow from the buyer's perspective. Is it clear and smooth?+ - [ ] Ensure error messages are helpful. Instead of a generic "Transaction Failed", provide more context if possible (e.g., "Transaction failed. You may not have enough USDC in your wallet.").+ - [ ] Add a section to the user's profile where they can see a history of all the skills they've purchased.++- [ ] **Create a Marketing/Landing Page:**+ - [ ] Design a section on your main landing page that advertises the new creator monetization features.+ - [ ] Highlight the benefits for creators (earn revenue) and for users (access powerful new capabilities).+ - [ ] This will help attract new creators to your platform.## Example: Onboarding Doc Snippet (`/docs/monetizing-your-agent.md`)diff --git a/docs/monetization/01-db-schema-for-skill-pricing.md b/docs/monetization/01-db-schema-for-skill-pricing.mdindex e27ac5659..bed30a7e8 100644--- a/docs/monetization/01-db-schema-for-skill-pricing.md+++ b/docs/monetization/01-db-schema-for-skill-pricing.md@@ -1,6 +1,6 @@----status: not-started-completed_at: null+status: completed+completed_at: 2026-05-04T12:01:00Z---# Prompt 1: Database Schema for Skill Monetizationdiff --git a/docs/monetization/02-add-purchase-button.md b/docs/monetization/02-add-purchase-button.mdnew file mode 100644index 000000000..e4786f97e--- /dev/null+++ b/docs/monetization/02-add-purchase-button.md@@ -0,0 +1,81 @@+---+status: not-started+---++# Prompt 2: Add Purchase Button for Paid Skills++## Objective+On the agent detail page, display a "Purchase" button next to paid skills that the current user has not yet unlocked. This button will initiate the skill purchase flow.++## Explanation+Building on the previous step where we displayed skill prices, we now need to provide a clear call-to-action for users to buy these skills. This involves checking if the user already owns the skill and rendering a button accordingly. For this, we'll need to know which skills the user has unlocked.++## Instructions+- [ ] **Modify the Backend API:**+ - [ ] The agent detail endpoint (`/api/marketplace/agents/:id`) needs to also return information about which skills the logged-in user has unlocked for that agent.+ - [ ] You will need to query the `user_unlocked_skills` table (you will create this in a later prompt) using the current `user_id` and the `agent_id`.+ - [ ] Include an `unlocked_skills` array of skill names in the API response for the currently logged in user.++- [ ] **Update the Frontend UI:**+ - [ ] In `src/marketplace.js`, find the `renderDetail` function.+ - [ ] When rendering the skills list, for each skill, check if it's priced and if it is NOT in the `unlocked_skills` array from the API response.+ - [ ] If a skill is priced and not unlocked, render a "Purchase" button next to the price badge.+ - [ ] If a skill is priced and IS unlocked, show an "Owned" badge.+ - [ ] The purchase button should have a `data-skill-name` attribute to identify which skill is being purchased when clicked.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// Inside renderDetail function, an updated version of the skill rendering logic:++const skillPrices = a.skill_prices || {};+const unlockedSkills = new Set(a.unlocked_skills || []);++$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ let badge = '';++ if (price) {+ if (unlockedSkills.has(name)) {+ badge = '<span class="price-badge price-owned">✓ Owned</span>';+ } else {+ const priceInUSDC = (price.amount / 1e6).toFixed(2);+ badge = `+ <span class="price-badge price-paid">${priceInUSDC} USDC</span>+ <button class="purchase-btn" data-skill-name="${escapeHtml(name)}">Purchase</button>+ `;+ }+ } else {+ badge = '<span class="price-badge price-free">Free</span>';+ }++ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+```++## CSS Example++Add these styles for the button and owned badge to `/marketplace.css`:++```css+.purchase-btn {+ margin-left: 8px;+ padding: 2px 8px;+ font-size: 10px;+ font-weight: 600;+ border-radius: 4px;+ background-color: var(--accent);+ color: white;+ border: none;+ cursor: pointer;+}++.price-owned {+ color: #a7f3d0;+ background-color: transparent;+ border: 1px solid rgba(52, 211, 153, 0.3);+}+```diff --git a/docs/monetization/02-user-wallet-connection.md b/docs/monetization/02-user-wallet-connection.mdindex d3ac8c27a..590d78a92 100644--- a/docs/monetization/02-user-wallet-connection.md+++ b/docs/monetization/02-user-wallet-connection.md@@ -1,3 +1,6 @@+---+status: not-started+---# Prompt 2: User Wallet Connection## Objective@@ -7,19 +10,19 @@ Integrate a "Connect Wallet" feature into the marketplace header, allowing usersTo 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:+- [ ] **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>`+- [ ] **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.+- [ ] **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`)diff --git a/docs/monetization/03-purchase-modal-ui.md b/docs/monetization/03-purchase-modal-ui.mdnew file mode 100644index 000000000..bb11a632b--- /dev/null+++ b/docs/monetization/03-purchase-modal-ui.md@@ -0,0 +1,80 @@+---+status: not-started+---++# Prompt 3: Purchase Modal UI++## Objective+Create a reusable modal component for the skill purchase flow, which will serve as the container for payment steps.++## Explanation+When a user clicks the "Purchase" button, we shouldn't immediately trigger a wallet transaction. Instead, we should present them with a clear, focused modal window that confirms their intent and guides them through the payment process. This modal will initially show the skill details and price, and will later host the wallet connection and payment confirmation steps.++## Instructions+- [ ] **Create the Modal HTML Structure:**+ - [ ] Add a generic modal structure to `marketplace.html`. It should be hidden by default (`display: none`).+ - [ ] The modal should have a backdrop, a main content area, a title, a close button, and a section for dynamic content.++- [ ] **Create the Modal CSS:**+ - [ ] In `marketplace.css`, add styles for the modal, backdrop, and content area.+ - [ ] Ensure it's centered, has a reasonable size, and is styled consistently with the rest of the application.++- [ ] **Implement Modal Logic:**+ - [ ] In `src/marketplace.js`, add functions to `showModal(title, content)` and `hideModal()`.+ - [ ] `showModal` should populate the modal's title and content sections and make it visible.+ - [ ] `hideModal` should hide the modal. The close button and backdrop should trigger this function.+ - [ ] Add an event listener to the `d-skills` container that listens for clicks on `.purchase-btn` buttons.+ - [ ] When a purchase button is clicked, get the skill name from the `data-skill-name` attribute, then call `showModal` with the appropriate details to confirm the purchase.++## HTML Example (`marketplace.html`)++```html+<!-- Add this somewhere in your main container -->+<div id="purchase-modal" class="modal-backdrop" style="display: none;">+ <div class="modal-content">+ <div class="modal-header">+ <h2 id="modal-title"></h2>+ <button id="modal-close" class="modal-close-btn">×</button>+ </div>+ <div id="modal-body"></div>+ </div>+</div>+```++## JavaScript Example (`src/marketplace.js`)++```javascript+// Function to show the modal+function showModal(title, content) {+ $('modal-title').textContent = title;+ $('modal-body').innerHTML = content;+ $('purchase-modal').style.display = 'flex';+}++// Function to hide the modal+function hideModal() {+ $('purchase-modal').style.display = 'none';+}++// Event listener for closing the modal+$('modal-close').addEventListener('click', hideModal);+$('purchase-modal').addEventListener('click', (e) => {+ if (e.target.id === 'purchase-modal') {+ hideModal();+ }+});++// Event listener for the purchase buttons+$('d-skills').addEventListener('click', (e) => {+ if (e.target.classList.contains('purchase-btn')) {+ const skillName = e.target.dataset.skillName;+ // Find the agent and skill details to show in the modal+ // For now, a simple confirmation:+ showModal(+ `Purchase Skill: ${skillName}`,+ `<p>You are about to purchase the skill "${skillName}".</p>+ <button id="confirm-purchase-btn">Confirm</button>`+ );+ }+});+```diff --git a/docs/monetization/04-wallet-connection.md b/docs/monetization/04-wallet-connection.mdnew file mode 100644index 000000000..9591a5a97--- /dev/null+++ b/docs/monetization/04-wallet-connection.md@@ -0,0 +1,84 @@+---+status: not-started+---++# Prompt 4: Wallet Connection++## Objective+Integrate a Solana wallet adapter to allow users to connect their wallets, a prerequisite for making payments.++## Explanation+To purchase skills, users will need to connect their Solana wallet (like Phantom or Solflare). We will use the official Solana wallet-adapter library to handle the complexities of wallet detection and connection. The connection button will be placed inside the purchase modal.++## Instructions+- [ ] **Add Solana Wallet-Adapter Dependencies:**+ - [ ] Add the necessary Solana wallet-adapter packages to your `package.json`. You'll need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-react` (or a vanilla JS equivalent if not using a framework), and adapters for specific wallets like `@solana/wallet-adapter-wallets`. For a vanilla JS project, you may need to use a CDN version or bundle it.+- [ ] **Integrate Wallet-Adapter:**+ - [ ] In `src/marketplace.js`, initialize the wallet adapter.+ - [ ] Create a `connectWallet` function. This function will be responsible for presenting the user with a list of available wallets and handling the connection logic.+- [ ] **Add Connect Button to UI:**+ - [ ] In the purchase modal, instead of a simple "Confirm" button, we'll now have a "Connect Wallet" button if the user's wallet is not already connected.+ - [ ] Display the user's public key (wallet address) once connected, and change the button to "Proceed to Payment".++## Code Example (`src/marketplace.js`)++This example assumes you're able to import or include the wallet-adapter libraries. For simplicity, we'll use psuedo-code for the adapter initialization.++```javascript+// Assume walletAdapter is initialized somewhere in your app's entry point.+// This is a simplified example. Refer to wallet-adapter docs for full setup.++let connectedWallet = null;++async function connectWallet() {+ try {+ // This would typically open the wallet adapter's modal+ const wallet = await walletAdapter.connect();+ connectedWallet = wallet;+ console.log('Wallet connected:', wallet.publicKey.toBase58());+ updateModalAfterConnect();+ } catch (error) {+ console.error('Failed to connect wallet:', error);+ // Show an error to the user+ }+}++function updateModalAfterConnect() {+ const walletAddress = connectedWallet.publicKey.toBase58();+ const truncatedAddress = `${walletAddress.slice(0, 4)}...${walletAddress.slice(-4)}`;++ // Update the modal body to show connected status+ const modalBody = $('modal-body');+ modalBody.innerHTML = `+ <p>Wallet Connected: <strong>${truncatedAddress}</strong></p>+ <button id="proceed-to-payment-btn">Proceed to Payment</button>+ `;+}++// In your event listener for showing the modal:+function showPurchaseModal(skillName) {+ let content = '';+ if (connectedWallet) {+ content = `+ <p>You are purchasing "${skillName}". Your wallet is connected.</p>+ <button id="proceed-to-payment-btn">Proceed to Payment</button>+ `;+ } else {+ content = `+ <p>You need to connect your wallet to purchase "${skillName}".</p>+ <button id="connect-wallet-btn">Connect Wallet</button>+ `;+ }+ showModal(`Purchase Skill: ${skillName}`, content);+}++// Add event listener for the new buttons inside the modal+$('modal-body').addEventListener('click', (e) => {+ if (e.target.id === 'connect-wallet-btn') {+ connectWallet();+ }+ if (e.target.id === 'proceed-to-payment-btn') {+ // Next step: initiate the payment+ }+});+```diff --git a/docs/monetization/05-initiate-payment-api.md b/docs/monetization/05-initiate-payment-api.mdnew file mode 100644index 000000000..3b98d5b9a--- /dev/null+++ b/docs/monetization/05-initiate-payment-api.md@@ -0,0 +1,84 @@+---+status: not-started+---++# Prompt 5: Initiate Payment API++## Objective+Create a backend endpoint that prepares a Solana transaction for a skill purchase and sends it to the frontend.++## Explanation+For security and reliability, the transaction should be constructed on the backend. The frontend will request a transaction for a specific skill. The backend will look up the skill's price, the creator's payout address, and the platform's fee address, then create an unsigned transaction and send it back to the frontend. The frontend's only job is to get it signed by the user's wallet.++## Instructions+- [ ] **Create the API Endpoint:**+ - [ ] Create a new API file, e.g., `api/payments/initiate.js`.+ - [ ] This endpoint should accept a `skill_name` and `agent_id` in the request body.+- [ ] **Implement Transaction Logic:**+ - [ ] The endpoint needs to perform several lookups:+ - [ ] The skill's price from `agent_skill_prices`.+ - [ ] The agent creator's payout address.+ - [ ] The platform's fee/treasury address (this can be a constant for now).+ - [ ] Using the Solana SDK (`@solana/web3.js`), construct a transaction. This will likely be a simple SPL-token transfer (e.g., USDC) from the user to the creator, potentially with a second transfer for the platform fee.+ - [ ] Serialize the unsigned transaction and return it in the response, base64-encoded.++## Code Example (Backend - `api/payments/initiate.js`)++```javascript+// This is a simplified example. You'll need error handling and more robust data fetching.+import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';+import { getTokenTransferInstruction } from 'your-token-utils'; // Helper for SPL token transfers++export default async function handler(req, res) {+ if (req.method !== 'POST') {+ return res.status(405).end();+ }++ const { skillName, agentId, userWalletAddress } = req.body;++ // 1. Fetch skill price, creator payout address, etc. from your database+ const skillPrice = await db.getSkillPrice(agentId, skillName); // e.g., { amount: 1000000, mint: 'EPj...' }+ const creatorAddress = await db.getCreatorPayoutAddress(agentId);+ const platformFeeAddress = process.env.PLATFORM_FEE_WALLET;+ const platformFeeBps = 500; // 5%++ // 2. Create a new transaction+ const connection = new Connection(process.env.SOLANA_RPC_URL);+ const transaction = new Transaction({+ feePayer: new PublicKey(userWalletAddress),+ recentBlockhash: (await connection.getLatestBlockhash()).blockhash,+ });++ // 3. Calculate amounts+ const creatorAmount = skillPrice.amount * (1 - platformFeeBps / 10000);+ const platformAmount = skillPrice.amount - creatorAmount;++ // 4. Add transfer instructions (this part is complex for SPL tokens, pseudo-code shown)+ // You need to find the user's Associated Token Account (ATA) for the mint.+ const userTokenAccount = await findUserATA(userWalletAddress, skillPrice.mint);++ transaction.add(+ createTokenTransferInstruction(+ userTokenAccount,+ creatorAddress,+ userWalletAddress, // User is the owner of their ATA+ creatorAmount+ )+ );+ transaction.add(+ createTokenTransferInstruction(+ userTokenAccount,+ platformFeeAddress,+ userWalletAddress,+ platformAmount+ )+ );++ // 5. Serialize and return+ const serializedTransaction = transaction.serialize({ requireAllSignatures: false });++ res.status(200).json({+ transaction: serializedTransaction.toString('base64'),+ });+}+```diff --git a/docs/monetization/25_admin_panel.md b/docs/monetization/25_admin_panel.mdnew file mode 100644index 000000000..c0006ae5e--- /dev/null+++ b/docs/monetization/25_admin_panel.md@@ -0,0 +1,61 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 25: Admin Panel for Monetization Management++## Objective+Create a secure admin-only panel to oversee and manage all monetization-related activities on the platform.++## Explanation+A robust platform needs an internal dashboard for administrators to monitor the health of the monetization system, manage disputes, and configure global settings. This is a critical tool for operations and support.++## Instructions+1. **Admin Authentication/Authorization:**+ * Implement a role-based access control (RBAC) system. In the `users` table, add an `is_admin` boolean flag.+ * Create a backend middleware that checks this flag for all admin API endpoints. If `is_admin` is not true, reject the request.++2. **Create the Admin UI:**+ * Create a new, separate frontend application or a secured route (e.g., `/admin`) for the admin panel.+ * This UI will be built to consume new, admin-only API endpoints.++3. **Backend APIs for Admin:**+ * Create a new set of API routes under `/api/admin/`.+ * **Global Stats (`/api/admin/stats`):**+ * Display platform-wide revenue, total sales, new subscriptions, etc.+ * **Transaction Viewer (`/api/admin/transactions`):**+ * A searchable, paginated view of the `user_purchased_skills` and `skill_subscriptions` tables. Allows admins to look up any purchase.+ * **Currency Management (`/api/admin/currencies`):**+ * An interface to manage the `SUPPORTED_CURRENCIES` whitelist. Admins can add or disable currencies without a code deployment.+ * **Platform Fee Configuration (`/api/admin/settings`):**+ * Allow admins to view and update the platform fee percentage and treasury wallet address.++4. **Key Admin Features:**+ * **Revenue Monitoring:** Dashboards with charts showing total platform revenue over time.+ * **Dispute Resolution:** A feature that would allow an admin to, for example, manually credit a user with a skill if a purchase failed in a way our system didn't catch. This would involve manually inserting a row into `user_purchased_skills`.+ * **User Lookup:** The ability to look up a user and see all their purchases and subscriptions.++## Code Example (Admin Auth Middleware)++```javascript+// In api/_lib/auth.js or a new middleware file++export async function requireAdmin(req, res) {+ const user = await getSessionUser(req);+ if (!user || !user.is_admin) {+ error(res, 403, 'forbidden', 'You do not have administrative privileges.');+ return null; // Stop execution+ }+ return user; // Proceed+}++// In an admin API handler+import { requireAdmin } from '../../_lib/auth.js';++export default wrap(async (req, res) => {+ const adminUser = await requireAdmin(req, res);+ if (!adminUser) return; // Stop if not admin++ // ... proceed with admin-only logic+});+```diff --git a/public/marketplace.css b/public/marketplace.cssindex 19500781c..b5c3d4e6b 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -791,6 +791,26 @@ body.market-page {font-weight: 600;}+.price-badge {+ display: inline-block;+ margin-left: 8px;+ padding: 2px 6px;+ font-size: 10px;+ font-weight: 600;+ border-radius: 4px;+ vertical-align: middle;+}++.price-free {+ color: #a7f3d0;+ background-color: rgba(52, 211, 153, 0.1);+}++.price-paid {+ color: #fde047;+ background-color: rgba(253, 224, 71, 0.1);+}+.skill-entry {display: inline-flex;align-items: center;diff --git a/scripts/migrations/001_add_monetization_tables.mjs b/scripts/migrations/001_add_monetization_tables.mjsnew file mode 100644index 000000000..4a154c59d--- /dev/null+++ b/scripts/migrations/001_add_monetization_tables.mjs@@ -0,0 +1,68 @@+// scripts/migrations/001_add_monetization_tables.mjs+import { sql } from '../../api/_lib/db.js';++async function migrate() {+ console.log('Running migration: 001_add_monetization_tables...');++ try {+ await sql.begin(async sql => {+ console.log('Creating table: agent_skill_prices...');+ await sql`+ CREATE TABLE IF NOT EXISTS agent_skill_prices (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id UUID NOT NULL,+ skill_name VARCHAR(255) NOT NULL,+ amount BIGINT NOT NULL CHECK (amount > 0),+ currency_mint VARCHAR(255) NOT NULL,+ billing_interval VARCHAR(50) DEFAULT 'one_time', -- For subscriptions+ trial_days INT DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT fk_agent+ FOREIGN KEY(agent_id)+ REFERENCES agent_identities(id)+ ON DELETE CASCADE,++ UNIQUE (agent_id, skill_name)+ );+ `;+ console.log('Table agent_skill_prices created.');++ console.log('Creating table: user_purchased_skills...');+ await sql`+ CREATE TABLE IF NOT EXISTS user_purchased_skills (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id UUID NOT NULL,+ agent_id UUID NOT NULL,+ skill_name VARCHAR(255) NOT NULL,+ purchase_tx_signature VARCHAR(128) NOT NULL,+ price_amount BIGINT NOT NULL,+ price_currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT fk_user+ FOREIGN KEY(user_id)+ REFERENCES users(id)+ ON DELETE CASCADE,++ CONSTRAINT fk_agent+ FOREIGN KEY(agent_id)+ REFERENCES agent_identities(id)+ ON DELETE CASCADE,++ UNIQUE (user_id, agent_id, skill_name)+ );+ `;+ console.log('Table user_purchased_skills created.');+ });++ console.log('Migration completed successfully.');+ process.exit(0);+ } catch (error) {+ console.error('Migration failed:', error);+ process.exit(1);+ }+}++migrate();diff --git a/scripts/migrations/001_create_agent_skill_prices.sql b/scripts/migrations/001_create_agent_skill_prices.sqlnew file mode 100644index 000000000..cbce8691a--- /dev/null+++ b/scripts/migrations/001_create_agent_skill_prices.sql@@ -0,0 +1,10 @@+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)+);diff --git a/scripts/migrations/20260504120000-create-monetization-tables.sql b/scripts/migrations/20260504120000-create-monetization-tables.sqlnew file mode 100644index 000000000..d3b5d4742--- /dev/null+++ b/scripts/migrations/20260504120000-create-monetization-tables.sql@@ -0,0 +1,63 @@+-- migration-20260504120000-create-monetization-tables.sql+-- This migration creates the tables necessary for agent skill monetization.++-- Table to store the prices for agent skills, set by the agent creator.+CREATE TABLE agent_skill_prices (+ agent_id BIGINT NOT NULL,+ skill_name VARCHAR(255) NOT NULL,+ amount BIGINT NOT NULL CHECK (amount > 0),+ currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (agent_id, skill_name),+ -- Assuming a foreign key relationship to an 'agents' table.+ -- If your agents table has a different name or primary key, adjust accordingly.+ CONSTRAINT fk_agent+ FOREIGN KEY(agent_id)+ REFERENCES agents(id)+ ON DELETE CASCADE+);++-- Index for faster queries when fetching all priced skills for a given agent.+CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);++-- Table to record successful purchases of skills by users.+CREATE TABLE user_skill_purchases (+ user_id BIGINT NOT NULL,+ agent_id BIGINT NOT NULL,+ skill_name VARCHAR(255) NOT NULL,+ purchase_tx_signature VARCHAR(255) NOT NULL,+ amount_paid BIGINT NOT NULL,+ currency_mint VARCHAR(255) NOT NULL,+ purchased_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (user_id, agent_id, skill_name),+ -- Assuming foreign key relationships to 'users' and 'agents' tables.+ -- Adjust if your table names or primary keys are different.+ CONSTRAINT fk_user+ FOREIGN KEY(user_id)+ REFERENCES users(id)+ ON DELETE CASCADE,+ CONSTRAINT fk_agent+ FOREIGN KEY(agent_id)+ REFERENCES agents(id)+ ON DELETE CASCADE+);++-- Indexes for common query patterns.+CREATE INDEX idx_user_skill_purchases_user_id ON user_skill_purchases(user_id);+CREATE UNIQUE INDEX idx_user_skill_purchases_tx_signature ON user_skill_purchases(purchase_tx_signature);++-- A function to automatically update the updated_at timestamp on row modification.+CREATE OR REPLACE FUNCTION update_modified_column()+RETURNS TRIGGER AS $$+BEGIN+ NEW.updated_at = NOW();+ RETURN NEW;+END;+$$ language 'plpgsql';++-- A trigger to execute the function before any update on agent_skill_prices.+CREATE TRIGGER update_agent_skill_prices_modtime+ BEFORE UPDATE ON agent_skill_prices+ FOR EACH ROW+ EXECUTE FUNCTION update_modified_column();diff --git a/src/wallet.js b/src/wallet.jsnew file mode 100644index 000000000..6a7c916fd--- /dev/null+++ b/src/wallet.js@@ -0,0 +1,31 @@+// src/wallet.js++// Placeholder for wallet adapter logic+let wallet;++function onConnectWallet() {+ console.log('Attempting to connect wallet...');+ // The actual connection logic will be implemented in the next prompt.+ // For now, we can simulate a successful connection.+ const mockAddress = 'YourWalletAddress...';+ updateWalletState(mockAddress);+}++export function updateWalletState(address) {+ const btn = document.getElementById('connect-wallet-btn');+ if (btn) {+ if (address) {+ // Display shortened address+ btn.textContent = `${address.slice(0, 4)}...${address.slice(-4)}`;+ } else {+ btn.textContent = 'Connect Wallet';+ }+ }+}++export function initWalletButton() {+ const btn = document.getElementById('connect-wallet-btn');+ if (btn) {+ btn.addEventListener('click', onConnectWallet);+ }+}diff --git a/tasks/agent-creation/11-feature-agent-creation-wizard.md b/tasks/agent-creation/11-feature-agent-creation-wizard.mdnew file mode 100644index 000000000..5d27d6b36--- /dev/null+++ b/tasks/agent-creation/11-feature-agent-creation-wizard.md@@ -0,0 +1,52 @@+---+status: not-started+---+# Prompt 11: Agent Creation Wizard++**Status:** Not Started++## Objective+Create a user-friendly, step-by-step wizard for creating a new agent. This will improve the user experience compared to a single, long form.++## Explanation+Creating a new agent involves multiple pieces of information: name, description, 3D model, skills, etc. A multi-step wizard breaks this down into manageable chunks, guiding the user through the process and improving completion rates.++## Instructions+1. **Create a new page:** `create-agent.html`.+2. **Design a multi-step UI:**+ * Use JavaScript to create a tab-like interface or a component that shows one step at a time.+ * Steps could be:+ 1. **Basic Info:** Name, Description, Tags.+ 2. **3D Model:** Upload a GLB/glTF file or choose from a default library.+ 3. **Skills:** Add/remove skills for the agent.+ 4. **Voice & Personality:** (Future feature, but plan for it) Set TTS voice and base prompt.+ 5. **Review & Create:** Show a summary and a final "Create Agent" button.+3. **State Management:**+ * Store the agent data in a JavaScript object as the user moves through the steps.+ * Implement "Next" and "Back" buttons.+4. **API Integration:**+ * On the final step, the "Create Agent" button should POST the complete agent object to a new API endpoint: `/api/agents/create`.+ * The backend will handle creating the new agent in the database.++## UI Sketch+```++-------------------------------------------------------------++| Create Your Agent |++-------------------------------------------------------------++| [Step 1: Info] -> [Step 2: Model] -> [Step 3: Skills] ... |++-------------------------------------------------------------++| |+| +--------------------------+ |+| | Agent Name | |+| | [______________________] | |+| | | |+| | Agent Description | |+| | [______________________] | |+| | [______________________] | |+| +--------------------------+ |+| |+| +--------------+ |+| | Next > | |+| +--------------+ |++-------------------------------------------------------------++```diff --git a/tasks/devops/20-devops-setup-ci-cd-pipeline.md b/tasks/devops/20-devops-setup-ci-cd-pipeline.mdnew file mode 100644index 000000000..944f4042e--- /dev/null+++ b/tasks/devops/20-devops-setup-ci-cd-pipeline.md@@ -0,0 +1,89 @@+---+status: not-started+---+# Prompt 20: Setup CI/CD Pipeline++**Status:** Not Started++## Objective+Automate the testing, building, and deployment of the application using a CI/CD pipeline. This will improve development velocity and reduce the risk of manual deployment errors.++## Explanation+A Continuous Integration/Continuous Deployment (CI/CD) pipeline automates the steps required to get your code from a commit into production. We will use GitHub Actions for this, as it's tightly integrated with our source control.++## Instructions+1. **Create a GitHub Actions Workflow:**+ * Create a new file at `.github/workflows/deploy.yml`.+ * This file will define the jobs and steps for our pipeline.+2. **Define the Trigger:**+ * Configure the workflow to run on every `push` to the `main` branch.+3. **Setup the Environment:**+ * Use the `actions/checkout@v3` action to check out the code.+ * Use the `actions/setup-node@v3` action to set up the correct Node.js version (as defined in `package.json`).+4. **Define the Jobs:**+ * **`test` job:**+ * Install dependencies (`npm install`).+ * Run Prettier check (`npm run format:check` -- you'll need to create this script).+ * Run linter (`npm run lint`).+ * Run unit/integration tests (`npm test`).+ * **`build` job:**+ * This job should `need` the `test` job to complete successfully.+ * Install dependencies (`npm install`).+ * Run the production build (`npm run build:all`).+ * Upload the `dist` directory as a build artifact.+ * **`deploy` job:**+ * This job should `need` the `build` job.+ * Download the build artifact.+ * Use the Vercel CLI or a Vercel GitHub Action to deploy the contents of the `dist` directory to production.+ * You will need to add a `VERCEL_TOKEN` and `VERCEL_PROJECT_ID` as secrets to your GitHub repository.++## Example Workflow (`.github/workflows/deploy.yml`)++```yaml+name: Deploy to Production++on:+ push:+ branches:+ - main++jobs:+ test:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '24'+ cache: 'npm'+ - run: npm ci+ - run: npm run verify # Assumes 'verify' script runs prettier, linter, tests++ build:+ needs: test+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: '24'+ cache: 'npm'+ - run: npm ci+ - run: npm run build:all+ - uses: actions/upload-artifact@v4+ with:+ name: dist+ path: dist/++ deploy:+ needs: build+ runs-on: ubuntu-latest+ steps:+ - uses: actions/download-artifact@v4+ with:+ name: dist+ path: dist+ - name: Deploy to Vercel+ run: npx vercel --prod --token=${{ secrets.VERCEL_TOKEN }}+ # Add more vercel-cli flags as needed, or use a dedicated action+```diff --git a/tasks/monetization-feature/01-display-priced-skills.md b/tasks/monetization-feature/01-display-priced-skills.mdindex 19f00332a..7602335fb 100644--- a/tasks/monetization-feature/01-display-priced-skills.md+++ b/tasks/monetization-feature/01-display-priced-skills.md@@ -1,5 +1,5 @@----status: completed+status: in-progress---# Prompt 1: Display Priced Skills in Marketplacediff --git a/tasks/monetization-feature/02-backend-create-skill-pricing-table.md b/tasks/monetization-feature/02-backend-create-skill-pricing-table.mdindex a9379e4ad..dfa7106ac 100644--- a/tasks/monetization-feature/02-backend-create-skill-pricing-table.md+++ b/tasks/monetization-feature/02-backend-create-skill-pricing-table.md@@ -1,5 +1,5 @@----status: not-started+status: in-progress---# Prompt 2: Backend - Create Skill Pricing Tablediff --git a/tasks/monetization-feature/02-create-skill-pricing-table.md b/tasks/monetization-feature/02-create-skill-pricing-table.mdindex a98cc162b..63885d082 100644--- a/tasks/monetization-feature/02-create-skill-pricing-table.md+++ b/tasks/monetization-feature/02-create-skill-pricing-table.md@@ -1,10 +1,12 @@---title: "Prompt 2: Create `agent_skill_prices` Table Schema"-status: "not-started"+status: "completed"---# Prompt 2: Create `agent_skill_prices` Table Schema+**Status:** Completed+## ObjectiveDefine and create the necessary database table to store skill prices set by agent creators.diff --git a/tasks/monetization-feature/02-creator-ui-set-skill-prices.md b/tasks/monetization-feature/02-creator-ui-set-skill-prices.mdnew file mode 100644index 000000000..0375e3fef--- /dev/null+++ b/tasks/monetization-feature/02-creator-ui-set-skill-prices.md@@ -0,0 +1,86 @@+---+status: not-started+---+# Prompt 2: Creator UI to Set Skill Prices++**Status:** Not Started++## Objective+Enhance the agent creation/editing page (`agent-edit.html`) to allow creators to set prices for their custom skills.++## Explanation+For creators to monetize their work, they need a simple interface to manage skill pricing. This task involves adding a new section to the agent editor that lists the agent's skills and provides input fields for setting a price in USDC. We will focus on USDC on Solana for now.++## Instructions+1. **Locate the Agent Editor:**+ - Find the agent editor page, likely `agent-edit.html`.+ - Identify the section where agent skills are listed or managed.++2. **Enhance the Skills UI:**+ - For each skill listed, add an input field for the price.+ - The input should be clearly labeled (e.g., "Price (USDC)").+ - Include a toggle or checkbox to mark a skill as "Paid". When enabled, the price input should appear.+ - Add a "Save Prices" button to submit the changes.++3. **Implement Frontend Logic:**+ - In the corresponding JavaScript file (likely `src/agent-edit.js` or similar), add an event listener to the "Save Prices" button.+ - When clicked, collect the pricing data for all skills. The data should be in a format like `[{ skill_name: "...", amount: 500000, currency: "USDC" }, ...]`. Note: 0.5 USDC = 500,000 lamports (assuming 6 decimals for USDC).+ - Send this data to a new backend API endpoint (which will be created in the next prompt).++## Code Example (HTML in `agent-edit.html`)++This is a conceptual example of how the skill pricing inputs could be structured.++```html+<!-- Inside the skills management section -->+<div class="skill-list">+ <div class="skill-item">+ <span class="skill-name">PumpFun Tools</span>+ <div class="skill-pricing-controls">+ <label class="toggle-switch">+ <input type="checkbox" class="price-toggle" data-skill="PumpFun Tools">+ <span class="slider"></span>+ </label>+ <div class="price-input-wrapper" style="display: none;">+ <input type="number" class="price-input" min="0" step="0.01" placeholder="0.50">+ <span>USDC</span>+ </div>+ </div>+ </div>+ <!-- ... more skills ... -->+</div>+<button id="save-skill-prices-btn">Save Prices</button>+```++## JavaScript Example (`src/agent-edit.js`)++```javascript+// Add event listener for the save button+document.getElementById('save-skill-prices-btn').addEventListener('click', async () => {+ const prices = [];+ document.querySelectorAll('.skill-item').forEach(item => {+ const name = item.querySelector('.skill-name').textContent;+ const toggle = item.querySelector('.price-toggle');+ const input = item.querySelector('.price-input');++ if (toggle.checked && input.value) {+ const amountInLamports = parseFloat(input.value) * 1e6; // Convert USDC to lamports+ prices.push({+ skill_name: name,+ amount: amountInLamports,+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a' // USDC mint on Solana+ });+ }+ });++ // POST to the new backend endpoint+ await fetch(`/api/agents/${agentId}/skill-prices`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ prices })+ });++ // Show a confirmation to the user+ alert('Prices saved!');+});+```diff --git a/tasks/monetization-feature/02-ui-add-purchase-skill-button.md b/tasks/monetization-feature/02-ui-add-purchase-skill-button.mdnew file mode 100644index 000000000..d110f2545--- /dev/null+++ b/tasks/monetization-feature/02-ui-add-purchase-skill-button.md@@ -0,0 +1,79 @@+---+status: not-started+---+# Prompt 2: Add "Purchase Skill" Button to UI++**Status:** Not Started++## Objective+In the agent detail page, for skills that are not free and not yet owned by the user, display a "Purchase" button. This button will be the entry point for the skill acquisition flow.++## Explanation+Following the display of priced skills, the next logical step is to allow users to buy them. This task focuses on the UI component only. The button's action will be wired up in a subsequent task. We need to check if the user has already purchased the skill.++## Instructions+1. **Modify the Backend API (`/api/marketplace/agents/:id`):**+ * The API response should include information about which skills the *currently logged-in user* has already purchased. You might add a `purchased_skills` array of skill names to the agent object. You'll need to query your database for user entitlements.+2. **Update the Frontend UI (`src/marketplace.js`):**+ * In the `renderDetail` function, you now have access to `agent.skill_prices` and `agent.purchased_skills`.+ * When rendering each skill, apply the following logic:+ * If the skill has no price, show the "Free" badge.+ * If the skill has a price and is in the `purchased_skills` array, show a "✅ Owned" badge.+ * If the skill has a price and is NOT in the `purchased_skills` array, show the price badge and a "Purchase" button.+ * The "Purchase" button should have `data-skill-name` and `data-agent-id` attributes to make it easy to handle the click event later.++## Code Example (`src/marketplace.js`)++```javascript+// Inside renderDetail function++const skillPrices = a.skill_prices || {};+const purchasedSkills = a.purchased_skills || [];++$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ let badge;++ if (price) {+ if (purchasedSkills.includes(name)) {+ badge = `<span class="price-badge price-owned">✓ Owned</span>`;+ } else {+ const priceInUSDC = (price.amount / 1e6).toFixed(2);+ badge = `<span class="price-badge price-paid">${priceInUSDC} USDC</span>` ++ `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}" data-agent-id="${a.id}">Purchase</button>`;+ }+ } else {+ badge = `<span class="price-badge price-free">Free</span>`;+ }+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+```++## CSS Example (`/marketplace.css`)+```css+.purchase-btn {+ margin-left: 8px;+ padding: 3px 8px;+ border: 1px solid #fde047;+ background-color: transparent;+ color: #fde047;+ border-radius: 4px;+ cursor: pointer;+ font-size: 10px;+ font-weight: 600;+ transition: background-color 0.2s, color 0.2s;+}++.purchase-btn:hover {+ background-color: #fde047;+ color: #111;+}++.price-owned {+ color: #a7f3d0;+ background-color: rgba(52, 211, 153, 0.1);+}+```diff --git a/tasks/monetization-feature/03-backend-api-set-skill-prices.md b/tasks/monetization-feature/03-backend-api-set-skill-prices.mdnew file mode 100644index 000000000..1f191e2d4--- /dev/null+++ b/tasks/monetization-feature/03-backend-api-set-skill-prices.md@@ -0,0 +1,91 @@+---+status: not-started+---+# Prompt 3: Backend API for Setting Skill Prices++**Status:** Not Started++## Objective+Create a secure backend API endpoint for creators to save or update the prices for their agent's skills.++## Explanation+This endpoint will receive the pricing data from the creator UI (created in Prompt 2) and persist it to the `agent_skill_prices` database table. It's crucial to ensure that only the agent's owner can modify its skill prices.++## Instructions+1. **Create a New API Route:**+ - In the `api/agents/` directory, create a new file or modify an existing one to handle a `POST` request, for example, `/api/agents/:id/skill-prices`.++2. **Implement Authorization:**+ - The endpoint must be protected. Verify the user's session or API token.+ - Check that the authenticated user is the owner of the agent specified by the `:id` parameter. If not, return a `403 Forbidden` error.++3. **Handle the Request:**+ - The request body will contain an array of skill prices, like `{ prices: [{ skill_name: "...", amount: 500000, currency_mint: "..." }] }`.+ - Validate the input data. Ensure `amount` is a non-negative number and `currency_mint` is a valid Solana mint address.++4. **Database Interaction:**+ - For the given `agent_id`, update the `agent_skill_prices` table.+ - A good approach is to use an "upsert" operation: if a price for a skill exists, update it; otherwise, insert a new row. You could also delete all existing prices for the agent and insert the new ones.+ - The table should store `agent_id`, `skill_name`, `amount`, and `currency_mint`.++5. **Return a Response:**+ - On success, return a `200 OK` or `204 No Content` response.+ - On failure (validation error, database error), return an appropriate error code (e.g., `400 Bad Request`, `500 Internal Server Error`) with a descriptive message.++## Code Example (Vercel Serverless Function)++Here's a conceptual example of the API endpoint logic.++```javascript+// in /api/agents/[id]/skill-prices.js+import { getAuth } from './_lib/auth';+import { db } from './_lib/db';++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 { prices } = req.body;++ // 1. Authorization+ const user = await getAuth(req);+ if (!user) {+ return res.status(401).json({ error: 'Unauthorized' });+ }++ const agent = await db.query('SELECT owner_id FROM agents WHERE id = $1', [agentId]);+ if (!agent.rows.length || agent.rows[0].owner_id !== user.id) {+ return res.status(403).json({ error: 'Forbidden' });+ }++ // 2. Validation (basic example)+ if (!Array.isArray(prices)) {+ return res.status(400).json({ error: 'Invalid payload' });+ }++ // 3. Database Interaction (transaction recommended)+ const client = await db.connect();+ try {+ await client.query('BEGIN');+ // Delete old prices+ await client.query('DELETE FROM agent_skill_prices WHERE agent_id = $1', [agentId]);+ // Insert new prices+ for (const price of prices) {+ await client.query(+ 'INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint) VALUES ($1, $2, $3, $4)',+ [agentId, price.skill_name, price.amount, price.currency_mint]+ );+ }+ await client.query('COMMIT');+ res.status(204).end();+ } catch (e) {+ await client.query('ROLLBACK');+ console.error(e);+ res.status(500).json({ error: 'Failed to save prices' });+ } finally {+ client.release();+ }+}+```diff --git a/tasks/monetization-feature/03-backend-create-skill-purchase-table.md b/tasks/monetization-feature/03-backend-create-skill-purchase-table.mdnew file mode 100644index 000000000..210c5492c--- /dev/null+++ b/tasks/monetization-feature/03-backend-create-skill-purchase-table.md@@ -0,0 +1,40 @@+---+status: not-started+---+# Prompt 3: Create Skill Purchases Database Table++**Status:** Not Started++## Objective+Create a database table to log and verify every time a user purchases a skill for one of their agents.++## Explanation+Tracking purchases is critical for granting users access to paid skills and for providing creators with sales history. The `skill_purchases` table will act as a ledger, recording which user bought which skill for which of their agents, along with transaction details for verification.++## Instructions+- **Connect to your database.**+- **Execute the following SQL statement to create the `skill_purchases` table.**++### SQL Schema+```sql+CREATE TABLE skill_purchases (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ skill_id UUID NOT NULL REFERENCES skills(id) ON DELETE CASCADE,+ price_id UUID NOT NULL REFERENCES agent_skill_prices(id),+ purchase_amount BIGINT NOT NULL,+ purchase_currency_mint VARCHAR(255) NOT NULL,+ transaction_signature VARCHAR(255) UNIQUE NOT NULL, -- For on-chain transaction verification+ purchased_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()+);++-- Create indexes for faster queries+CREATE INDEX idx_skill_purchases_on_agent_id ON skill_purchases(agent_id);+CREATE INDEX idx_skill_purchases_on_user_id ON skill_purchases(user_id);+CREATE INDEX idx_skill_purchases_on_skill_id ON skill_purchases(skill_id);+```++## Verification+- Verify that the `skill_purchases` table exists in your database with the correct schema.+- Ensure the indexes are created, as this table could grow large and will be queried frequently to check skill access rights.diff --git a/tasks/monetization-feature/03-backend-purchase-skill-api.md b/tasks/monetization-feature/03-backend-purchase-skill-api.mdnew file mode 100644index 000000000..815fa98d9--- /dev/null+++ b/tasks/monetization-feature/03-backend-purchase-skill-api.md@@ -0,0 +1,58 @@+---+status: not-started+---+# Prompt 3: Backend for Skill Purchase++**Status:** Not Started++## Objective+Create the backend API endpoint and logic to handle a user's purchase of an agent skill using Solana Pay.++## Explanation+When a user clicks the "Purchase" button, the frontend will need to request a transaction from the backend. The backend will construct a Solana transaction, sign it, and send it back to the frontend for the user to approve and send to the network.++## Instructions+1. **Create a New API Endpoint:**+ * Create a new file or use the existing router to handle `POST /api/payments/purchase-skill`.+ * This endpoint should expect an `agentId` and `skillName` in the request body.+2. **Input Validation:**+ * Verify the user is authenticated.+ * Check that the agent and skill exist.+ * Fetch the skill price from the `agent_skill_prices` table. Ensure the skill is actually for sale.+ * Verify the user does not already own this skill.+3. **Construct the Solana Transaction:**+ * Use the Solana Web3.js library (`@solana/web3.js`).+ * Create a transaction to transfer the correct amount of USDC (or other currency) from the user's wallet to the agent creator's wallet.+ * You will need the agent creator's wallet address, which should be stored with the agent's data.+ * The transaction should include a memo instruction with the skill name and agent ID for record-keeping.+4. **Record the Transaction:**+ * Before returning to the user, record the pending transaction in a database table (`skill_purchases`). Mark its status as "pending".+ * Include the transaction signature.+5. **Return the Transaction:**+ * Serialize the transaction and send it back in the API response. The frontend will then prompt the user to sign and submit it.+ * You will need a separate webhook or confirmation listener to update the purchase status from "pending" to "completed" once the transaction is confirmed on the blockchain.++## API Endpoint (`/api/payments/purchase-skill`)++* **Method:** `POST`+* **Body:**+ ```json+ {+ "agentId": "agent_id_here",+ "skillName": "skill_name_here",+ "userWallet": "user_public_key_here"+ }+ ```+* **Success Response (200):**+ ```json+ {+ "transaction": "base64_serialized_transaction_here",+ "signature": "transaction_signature_here"+ }+ ```+* **Error Response (400/500):**+ ```json+ {+ "error": "Descriptive error message."+ }+ ```diff --git a/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md b/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.mdnew file mode 100644index 000000000..18e2ba3c1--- /dev/null+++ b/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md@@ -0,0 +1,31 @@+---+status: not-started+---++# Prompt 3: UI - Creator Dashboard for Pricing++**Status:** Not Started++## Objective+Create a new section in the agent creator dashboard that allows creators to set and manage prices for their skills.++## Explanation+With the backend ready to store prices, we need a user interface for creators to manage them. This involves adding a new section to the agent edit page where each skill is listed with an input field to set its price.++## Instructions+- [ ] **Locate the agent edit page's code** (likely in `agent-edit.html` and its corresponding JavaScript file).+- [ ] **Fetch the agent's skills and any existing prices.**+- [ ] **For each skill, display its name and an input form.** The form should contain:+ - An input field for the `amount`.+ - A dropdown to select the `currency` (e.g., USDC, SOL). This should be pre-populated with supported currencies.+- [ ] **Implement a "Save Prices" button.** When clicked, this should:+ - Gather the pricing data for all skills.+ - Make an API call to a new endpoint (`/api/agents/:id/skill-prices`) to save the data.+ - Handle both creating new prices and updating existing ones.+- [ ] **Provide feedback to the user,** such as a confirmation message on successful save or an error message on failure.++## API Endpoint (`POST /api/agents/:id/skill-prices`)+You'll need to create this new endpoint. It should:+- Be authenticated to ensure only the agent's owner can set prices.+- Accept a payload like: `{ "prices": { "text-to-speech": { "amount": 500000, "currency_mint": "EP..." } } }`+- Upsert the prices into the `agent_skill_prices` table.diff --git a/tasks/monetization-feature/04-backend-skill-purchase-api.md b/tasks/monetization-feature/04-backend-skill-purchase-api.mdnew file mode 100644index 000000000..2596f59be--- /dev/null+++ b/tasks/monetization-feature/04-backend-skill-purchase-api.md@@ -0,0 +1,29 @@+---+status: not-started+---++# Prompt 4: Backend - Skill Purchase API++**Status:** Not Started++## Objective+Create the backend infrastructure for users to purchase access to a paid skill. This involves creating a Solana Pay-compatible API endpoint.++## Explanation+When a user wants to use a paid skill, our platform needs to facilitate the transaction. We will create a Solana Pay endpoint that, when called, returns the details of the transaction that the user needs to sign and send.++## Instructions+- [ ] **Create a new API endpoint, e.g., `POST /api/skills/purchase`**.+- [ ] **Define the request body.** It should include:+ - `agent_id`: The ID of the agent whose skill is being purchased.+ - `skill_name`: The name of the skill.+ - `account`: The user's Solana public key.+- [ ] **Implement the endpoint logic:**+ - 1. **Fetch skill price:** Look up the price of the skill in the `agent_skill_prices` table.+ - 2. **Construct the transaction:** Create a Solana transaction that transfers the specified `amount` of the `currency_mint` from the user's `account` to the agent creator's wallet.+ - 3. **Add a memo:** Include a memo in the transaction to identify the purchase (e.g., "Purchase of skill 'text-to-speech' for agent 'AI Assistant'").+ - 4. **Serialize the transaction:** The transaction should be partially signed (if necessary) and serialized.+ - 5. **Return the Solana Pay response:** The response should follow the Solana Pay specification, including the serialized `transaction` and a `message`.++## Solana Pay+Refer to the official [Solana Pay documentation](https://docs.solanapay.com/spec) for the exact request and response formats. This will ensure compatibility with Solana wallets.diff --git a/tasks/monetization-feature/04-frontend-ui-set-skill-prices.md b/tasks/monetization-feature/04-frontend-ui-set-skill-prices.mdnew file mode 100644index 000000000..4dbdb2df4--- /dev/null+++ b/tasks/monetization-feature/04-frontend-ui-set-skill-prices.md@@ -0,0 +1,78 @@+---+status: not-started+---++# Prompt 4: Frontend - UI for Creators to Set Skill Prices++**Status:** Not Started++## Objective+Implement a user interface in the agent creation/editing page (`agent-edit.html`) that allows creators to set and view prices for their skills.++## Explanation+To make the pricing API useful, creators need a user-friendly interface to manage their skill prices. This involves adding form elements to the page where they edit their agent's details. This UI will fetch existing prices and provide input fields to set new ones, calling the API endpoint from the previous prompt.++## Instructions+- [ ] **Locate the Agent Edit Page:** Open the `agent-edit.html` file and its corresponding JavaScript file (e.g., `src/agent-edit.js`).+- [ ] **Fetch Existing Prices:** When the page loads and fetches the agent's details, make sure the API response includes the `skill_prices` data.+- [ ] **Modify the Skill Rendering:** In the area where the agent's skills are listed, add input fields for `amount` and `currency_mint` next to each skill.+- [ ] **Populate Existing Data:** If a price already exists for a skill, populate the input fields with that data.+- [ ] **Create a "Save Prices" Button:** Add a button that, when clicked, will gather the pricing data from all the input fields.+- [ ] **Implement the API Call:**+ - For each skill with a price, call the `POST /api/agents/:id/skills/pricing` endpoint.+ - You can do this individually for each skill or batch them into a single request if your backend supports it.+ - Provide user feedback (e.g., a "Saved!" message or an error notification).++## Code Example (`src/agent-edit.js`)++```javascript+// Inside the function that renders the agent details for editing++function renderAgentForEditing(agent) {+ // ... existing code to render agent name, description, etc.++ const skillsContainer = document.getElementById('skills-editor');+ const skillPrices = agent.skill_prices || {};++ skillsContainer.innerHTML = agent.skills.map(skill => {+ const price = skillPrices[skill.name] || {};+ const amountInUnits = price.amount ? price.amount / 1e6 : ''; // Example for USDC (6 decimals)+ const currency = price.currency_mint || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T'; // Default to USDC++ return `+ <div class="skill-price-editor" data-skill-name="${skill.name}">+ <span class="skill-name">${skill.name}</span>+ <input type="number" class="price-amount" placeholder="e.g., 2.50" value="${amountInUnits}">+ <select class="price-currency">+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T" ${currency === 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T' ? 'selected' : ''}>USDC</option>+ <option value="So11111111111111111111111111111111111111112" ${currency === 'So11111111111111111111111111111111111111112' ? 'selected' : ''}>SOL</option>+ </select>+ </div>+ `;+ }).join('');+}++// Add event listener for the "Save Prices" button+document.getElementById('save-prices-btn').addEventListener('click', async () => {+ const agentId = /* get agent id from somewhere */;+ const editors = document.querySelectorAll('.skill-price-editor');++ for (const editor of editors) {+ const skill_name = editor.dataset.skillName;+ const amountInUnits = parseFloat(editor.querySelector('.price-amount').value);+ const currency_mint = editor.querySelector('.price-currency').value;++ if (!isNaN(amountInUnits) && amountInUnits > 0) {+ const amount = Math.round(amountInUnits * 1e6); // Convert back to smallest unit++ await fetch(`/api/agents/${agentId}/skills/pricing`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', /* + auth headers */ },+ body: JSON.stringify({ skill_name, amount, currency_mint }),+ });+ }+ }+ // Show feedback to user+ alert('Prices saved!');+});+```diff --git a/tasks/monetization-feature/04-ui-show-purchased-skills.md b/tasks/monetization-feature/04-ui-show-purchased-skills.mdnew file mode 100644index 000000000..0f6f6478f--- /dev/null+++ b/tasks/monetization-feature/04-ui-show-purchased-skills.md@@ -0,0 +1,70 @@+---+status: not-started+---+# Prompt 4: UI to Show Purchased Skills++**Status:** Not Started++## Objective+Update the marketplace and user dashboard to visually distinguish skills that the logged-in user has already purchased.++## Explanation+To prevent users from accidentally re-purchasing a skill and to provide a clear overview of their entitlements, the UI should reflect their purchase history. This requires fetching the user's purchased skills and using that information to update the rendering of skill badges.++## Instructions+1. **Create Backend API for User Purchases:**+ - Create a new API endpoint, e.g., `/api/users/me/purchased-skills`, that returns a list of all skill purchases for the currently authenticated user.+ - The response should be an array of objects, like `[{ agent_id: "...", skill_name: "..." }, ...]`.++2. **Fetch Purchased Skills on Frontend:**+ - When a user is logged in, fetch their purchased skills from the new endpoint.+ - Store this information in a client-side data structure that's easy to access, like a `Set` of strings in the format `agent_id:skill_name`.++3. **Update Marketplace UI (`src/marketplace.js`):**+ - In the `renderDetail` function, where the skill badges are rendered, modify the logic.+ - Before rendering a "Purchase" button or a price for a paid skill, check if the user has already purchased it.+ - If the skill is purchased, render a different badge, e.g., "Owned" or a checkmark icon, instead of the price.++4. **Create a "My Skills" Section in Dashboard:**+ - In the user's main dashboard (`dashboard.html` or similar), add a new section or tab called "My Purchased Skills".+ - This section should list all the skills the user has bought, grouped by agent.+ - This provides a centralized view for users to manage their purchased assets.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// Assuming `purchasedSkills` is a Set like: new Set(['agent123:PumpFun Tools'])+const purchasedSkills = await fetchUserPurchases(); // Fetched on page load++// ... inside renderDetail function ...++const skillPrices = a.skill_prices || {};+$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ const purchaseKey = `${a.id}:${name}`; // e.g., 'agent123:PumpFun Tools'++ let badge;+ if (purchasedSkills.has(purchaseKey)) {+ badge = `<span class="price-badge price-owned">✓ Owned</span>`;+ } else if (price) {+ badge = `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`;+ } else {+ badge = `<span class="price-badge price-free">Free</span>`;+ }++ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';++```++## CSS Example (`marketplace.css`)++```css+.price-owned {+ color: #86efac; /* A pleasant green */+ background-color: rgba(74, 222, 128, 0.1);+}+```diff --git a/tasks/monetization-feature/05-backend-api-initiate-purchase.md b/tasks/monetization-feature/05-backend-api-initiate-purchase.mdnew file mode 100644index 000000000..d623dad6e--- /dev/null+++ b/tasks/monetization-feature/05-backend-api-initiate-purchase.md@@ -0,0 +1,68 @@+---+status: not-started+---+# Prompt 5: API to Initiate Skill Purchase++**Status:** Not Started++## Objective+Create a backend endpoint that prepares and returns a transaction for a user to sign to purchase a skill.++## Explanation+For on-chain payments, the backend should not handle private keys. Instead, it constructs an unsigned transaction and sends it to the client. The user then signs it with their wallet, ensuring a secure, non-custodial process. This endpoint will generate such a transaction.++## Instructions+- **Create a `POST` endpoint: `/api/skills/:skill_id/purchase`.**+- **Implement the following logic:**+ 1. **Authentication:** Ensure the user is logged in.+ 2. **Validation:** Check that the skill exists and is for sale.+ 3. **Fetch Data:** Get the skill price, creator's wallet address, and platform fee wallet address.+ 4. **Construct Transaction:** Use the Solana Web3 library (`@solana/web3.js`) to create a transaction with two transfers:+ - One transfer sends the payment from the user to the creator.+ - A second transfer sends the platform fee from the user to the platform wallet.+ 5. **Serialize:** Serialize the transaction, but do not sign it. Base64-encode the serialized transaction.+ 6. **Response:** Return the base64-encoded transaction to the client.++## Code Example (Backend - Solana Pay)+```javascript+// POST /api/skills/:skill_id/purchase+import { createTransfer } from '@solana/pay';+import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';++async function initiatePurchase(req, res) {+ const { skill_id } = req.params;+ const user_id = req.session.userId;+ const user_wallet = new PublicKey(req.body.account); // User's public key from request++ // ... Auth, validation ...+ const priceInfo = await db.one('SELECT * FROM agent_skill_prices WHERE skill_id = $1', skill_id);+ const creator = await db.one('SELECT wallet_address FROM users WHERE id = $1', priceInfo.creator_id);++ const connection = new Connection(process.env.SOLANA_RPC_URL);+ const creatorWallet = new PublicKey(creator.wallet_address);+ const platformWallet = new PublicKey(process.env.PLATFORM_WALLET);+ const feeAmount = priceInfo.amount * 0.05; // 5% fee++ const transaction = new Transaction({+ feePayer: user_wallet,+ recentBlockhash: (await connection.getLatestBlockhash()).blockhash+ });++ // Payment to creator+ transaction.add(SystemProgram.transfer({+ fromPubkey: user_wallet,+ toPubkey: creatorWallet,+ lamports: priceInfo.amount,+ }));++ // Fee to platform+ transaction.add(SystemProgram.transfer({+ fromPubkey: user_wallet,+ toPubkey: platformWallet,+ lamports: feeAmount,+ }));++ const serialized = transaction.serialize({ requireAllSignatures: false });+ return res.json({ transaction: serialized.toString('base64') });+}+```diff --git a/tasks/monetization-feature/05-backend-purchase-initiation-api.md b/tasks/monetization-feature/05-backend-purchase-initiation-api.mdnew file mode 100644index 000000000..13d0ac689--- /dev/null+++ b/tasks/monetization-feature/05-backend-purchase-initiation-api.md@@ -0,0 +1,90 @@+---+status: not-started+---++# Prompt 5: Backend - Purchase Initiation API++**Status:** Not Started++## Objective+Create a backend API endpoint that prepares and returns the necessary information for a client to initiate a Solana Pay transaction.++## Explanation+To allow users to purchase a skill, the frontend needs to know the price, the recipient, and other transaction details. This endpoint will serve as the first step in the purchase flow. It will look up the skill's price and construct a Solana Pay-compliant response that the frontend can use to generate a QR code or automatically open a wallet.++## Instructions+- [ ] **Create the Endpoint:** Define a new endpoint, for example, `POST /api/purchase/skill`.+- [ ] **Request Body:** The endpoint should accept `agent_id` and `skill_name` in the request body.+- [ ] **Fetch Skill Price:**+ - Query the `agent_skill_prices` table for the price of the requested skill.+ - If the skill is free or the price is not found, return an appropriate error.+- [ ] **Fetch Creator's Wallet:**+ - Look up the agent's creator from the `agents` table.+ - Get the creator's public key (wallet address) from the `users` or a dedicated `wallets` table. This will be the recipient of the payment.+- [ ] **Construct Solana Pay Response:**+ - The response should be a JSON object containing:+ - `label`: The name of the store or app (e.g., "3D-Agent Marketplace").+ - `icon`: A URL to an icon for the transaction.+- [ ] **Integrate with Solana Pay SDK:**+ - Use the `@solana/pay` SDK on the backend.+ - Your endpoint should implement the `GET` portion of the Solana Pay spec. When a wallet pings this URL, it should return the recipient, amount, SPL token, etc.+ - You will also need a `POST` handler on this same endpoint. When the wallet confirms the transaction, it will `POST` the transaction signature here for verification.++## Code Example (Node.js/Express-style Solana Pay)++```javascript+// in api/purchase/skill.js++import { Keypair, Connection, PublicKey, clusterApiUrl } from '@solana/web3.js';+import { findReference, FindReferenceError } from '@solana/pay';+import { db } from '../_lib/db'; // Your database utility++// The GET handler is called by wallets to get transaction details+async function get(req, res) {+ const { agent_id, skill_name } = req.query;++ // 1. Fetch price and creator wallet from DB+ const priceInfo = await db.one(+ `SELECT p.amount, p.currency_mint, a.owner_id+ FROM agent_skill_prices p+ JOIN agents a ON p.agent_id = a.id+ WHERE p.agent_id = $1 AND p.skill_name = $2`,+ [agent_id, skill_name]+ );++ const creatorWallet = await db.one('SELECT wallet_address FROM users WHERE id = $1', [priceInfo.owner_id]);++ // 2. Respond with Solana Pay GET spec+ res.status(200).json({+ label: "3D-Agent Marketplace",+ icon: "https://your-app.com/icon.png",+ });+}++// The POST handler is called by wallets after the user approves the transaction+async function post(req, res) {+ const { account } = req.body;+ if (!account) throw new Error('Missing account');++ const { reference } = req.query;+ if (!reference) throw new Error('Missing reference');++ const signature = await verifyTransaction(account, reference);+ // Here you would grant the user access to the skill in your DB+ // grantSkillAccess(account, reference.skill_name);++ res.status(200).json({ status: 'ok', signature });+}+++async function verifyTransaction(account, reference) {+ const connection = new Connection(clusterApiUrl('mainnet-beta'));++ // Find the transaction signature from the reference+ const signatureInfo = await findReference(connection, new PublicKey(reference));++ // Here you would add more validation, e.g., checking the transaction amount and destination match the skill price.++ return signatureInfo.signature;+}+```diff --git a/tasks/monetization-feature/05-solana-define-skill-nft-standard.md b/tasks/monetization-feature/05-solana-define-skill-nft-standard.mdnew file mode 100644index 000000000..589489665--- /dev/null+++ b/tasks/monetization-feature/05-solana-define-skill-nft-standard.md@@ -0,0 +1,79 @@+---+status: not-started+---++# Prompt 5: Solana - Define Skill NFT Standard++**Status:** Not Started++## Objective+Define a clear and comprehensive metadata standard for NFTs that represent ownership of an agent's skill.++## Explanation+To represent skills as unique, tradable assets on the Solana blockchain, we need a robust metadata structure. This standard will ensure that all skill NFTs on the platform are consistent, making them easy to display in wallets and on secondary marketplaces. We will use the Metaplex Token Metadata standard as our base.++## Instructions+1. **Define Core Metadata Fields:**+ - `name`: The name of the skill (e.g., "Super-Resolution Image Generator"). Should be concise and clear.+ - `symbol`: A short symbol for the skill NFT (e.g., "SR-IMG").+ - `description`: A detailed explanation of what the skill does, its inputs, and its outputs.+ - `image`: A URL to an icon or banner image representing the skill.+ - `external_url`: A URL pointing to the agent's detail page on the three.ws marketplace (e.g., `https://three.ws/marketplace/agents/AGENT_ID`).++2. **Define Custom Attributes (Metaplex `attributes` array):**+ - Create a list of `trait_type` and `value` pairs to store skill-specific information. This is crucial for filtering and discovery.+ - **`trait_type: "Skill Name"`**: `value: "text-to-image"` (The machine-readable name of the skill).+ - **`trait_type: "Agent ID"`**: `value: "AGENT_ID"` (The ID of the agent that this skill belongs to).+ - **`trait_type: "Agent Name"`**: `value: "Creator's Agent"` (The human-readable name of the agent).+ - **`trait_type: "Version"`**: `value: "1.0.0"` (The version of the skill).+ - **`trait_type: "Category"`**: `value: "Image Generation"` (To help with organization).++## Code Example (JSON Metadata)++This is an example of the JSON file that would be uploaded to a decentralized storage service like Arweave and linked in the NFT's metadata.++```json+{+ "name": "Super-Res Image Generator",+ "symbol": "SR-IMG",+ "description": "This skill allows the agent to take a low-resolution image and generate a high-resolution version using advanced AI models. Outputs a 4x upscaled image.",+ "image": "https://arweave.net/path-to-skill-icon.png",+ "external_url": "https://three.ws/marketplace/agents/AGENT_ID",+ "attributes": [+ {+ "trait_type": "Skill Name",+ "value": "super-resolution-image-generator"+ },+ {+ "trait_type": "Agent ID",+ "value": "f8a4e12d-6b3a-4f3e-8b1a-9c2d7e5f4a1b"+ },+ {+ "trait_type": "Agent Name",+ "value": "PixelPerfect"+ },+ {+ "trait_type": "Version",+ "value": "1.0.0"+ },+ {+ "trait_type": "Category",+ "value": "Image Generation"+ }+ ],+ "properties": {+ "files": [+ {+ "uri": "https://arweave.net/path-to-skill-icon.png",+ "type": "image/png"+ }+ ],+ "category": "image"+ }+}+```++## Definition of Done+- The NFT metadata standard is finalized and documented in this file.+- The standard includes all necessary fields for discovery, display, and verification.+- The team agrees on this structure before proceeding to the implementation prompts.diff --git a/tasks/monetization-feature/05-ui-skill-purchase-flow.md b/tasks/monetization-feature/05-ui-skill-purchase-flow.mdnew file mode 100644index 000000000..dca9e1aaa--- /dev/null+++ b/tasks/monetization-feature/05-ui-skill-purchase-flow.md@@ -0,0 +1,29 @@+---+status: not-started+---++# Prompt 5: UI - Skill Purchase Flow++**Status:** Not Started++## Objective+Integrate the frontend of the agent detail page with the skill purchase API to allow users to buy skills.++## Explanation+Now that the backend can generate a purchase transaction, we need to add a "Buy" button for paid skills in the UI. When a user clicks this button, it should initiate the purchase flow using the Solana Pay API.++## Instructions+- [ ] **Modify the `renderDetail` function in `src/marketplace.js`** (or equivalent file).+- [ ] **For paid skills, instead of just showing a price badge, render a "Buy" button.**+- [ ] **Add an event listener to the "Buy" button.** On click, it should:+ - 1. **Get the user's wallet address.** Use the connected wallet's public key.+ - 2. **Make a `POST` request** to the `/api/skills/purchase` endpoint created in the previous prompt.+ - 3. **Receive the Solana Pay transaction** from the API.+ - 4. **Use the wallet adapter** to ask the user to sign and send the transaction.+ - 5. **Handle the transaction states:**+ - Display a "processing" indicator.+ - On confirmation, show a success message and update the UI to show the skill as "owned".+ - On failure, show an error message.++## Tracking Owned Skills+You'll need a way to know which skills the user already owns. A new table, `user_owned_skills`, might be necessary, or you can check on-chain for past transactions. For now, a simple client-side state update after purchase is sufficient.diff --git a/tasks/monetization-feature/06-backend-api-for-nft-collection.md b/tasks/monetization-feature/06-backend-api-for-nft-collection.mdnew file mode 100644index 000000000..4d9db5fb1--- /dev/null+++ b/tasks/monetization-feature/06-backend-api-for-nft-collection.md@@ -0,0 +1,96 @@+---+status: not-started+---++# Prompt 6: Backend - API for NFT Collection Creation++**Status:** Not Started++## Objective+Create an API endpoint for an authenticated agent creator to generate a new Metaplex Certified Collection on Solana, which will be used to group all the paid skills for a specific agent.++## Explanation+Before we can mint individual skill NFTs, they need to belong to a "collection." This allows marketplaces to group them and verifies their authenticity. This task involves creating an API that uses the Metaplex Umi library to create a new NFT collection on behalf of the agent's creator. The platform will be the update authority to manage the collection.++## Instructions+1. **Set up Metaplex Umi:**+ - Install the necessary Metaplex and Solana libraries (`@metaplex-foundation/umi-bundle-defaults`, `@metaplex-foundation/mpl-token-metadata`, `@solana/web3.js`).+ - Create a helper function to initialize Umi with your platform's keypair and connection to the Solana devnet.++2. **Create the API Endpoint:**+ - Create a new API route, for example, `/api/agents/[id]/skill-collection`.+ - Implement a `POST` handler that is protected, ensuring only the agent owner can create a collection.++3. **Implement the Collection Creation Logic:**+ - The handler should first check if a collection already exists for this agent to prevent duplicates.+ - Generate a new keypair for the collection NFT's mint account.+ - Use the `createNft` function from `@metaplex-foundation/mpl-token-metadata`.+ - The `createNft` call should specify:+ - `name`: e.g., "Agent [Agent Name] Skills"+ - `symbol`: e.g., "A1SKILL"+ - `uri`: A URL to a JSON file containing the collection's metadata (e.g., agent's name, description, image).+ - `sellerFeeBasisPoints`: Set to `0` for the collection NFT itself.+ - `isCollection`: `true`.+ - Store the collection's mint address in the `agents` table, associated with the agent `id`.++## Code Example (Vercel Serverless Function - `api/agents/[id]/skill-collection.js`)++```javascript+import { createNft } from '@metaplex-foundation/mpl-token-metadata';+import { generateSigner, percentAmount } from '@metaplex-foundation/umi';+import { initializeUmi } from '@lib/solana/umi'; // Your Umi setup helper+import { db } from '@lib/db';+import { withAuth } from '@lib/auth';++async function handler(req, res) {+ if (req.method !== 'POST') {+ return res.status(405).end();+ }+ const { id: agentId } = req.query;+ const { userId } = req.auth;++ // 1. Verify ownership and check if collection already exists+ const agent = await db.query('SELECT owner_id, skill_collection_mint FROM agents WHERE id = $1', [agentId]);+ if (!agent.rows.length || agent.rows[0].owner_id !== userId) {+ return res.status(403).json({ error: 'Forbidden' });+ }+ if (agent.rows[0].skill_collection_mint) {+ return res.status(400).json({ error: 'Collection already exists' });+ }++ try {+ const umi = initializeUmi();+ const collectionMint = generateSigner(umi);++ // TODO: Upload collection metadata to Arweave/IPFS+ const collectionMetadataUri = 'https://...';++ await createNft(umi, {+ mint: collectionMint,+ name: `Agent ${agent.name} Skills`,+ symbol: 'A1SKILL',+ uri: collectionMetadataUri,+ sellerFeeBasisPoints: percentAmount(0),+ isCollection: true,+ }).sendAndConfirm(umi);++ const collectionMintAddress = collectionMint.publicKey;++ // 3. Save the mint address to your database+ await db.query('UPDATE agents SET skill_collection_mint = $1 WHERE id = $2', [collectionMintAddress, agentId]);++ return res.status(200).json({ collectionMint: collectionMintAddress });+ } catch (error) {+ console.error('Failed to create collection NFT:', error);+ return res.status(500).json({ error: 'Failed to create collection' });+ }+}++export default withAuth(handler);+```++## Definition of Done+- The `/api/agents/[id]/skill-collection` endpoint is created and functional.+- When called by the agent owner, a new Metaplex collection NFT is created on Solana devnet.+- The new collection's mint address is saved to the `agents` table.+- The endpoint correctly handles errors and prevents duplicate collection creation.diff --git a/tasks/monetization-feature/06-backend-api-fulfill-purchase.md b/tasks/monetization-feature/06-backend-api-fulfill-purchase.mdnew file mode 100644index 000000000..2eb893019--- /dev/null+++ b/tasks/monetization-feature/06-backend-api-fulfill-purchase.md@@ -0,0 +1,63 @@+---+status: not-started+---+# Prompt 6: API to Fulfill Skill Purchase++**Status:** Not Started++## Objective+Create an endpoint to verify a signed transaction and officially record a skill purchase in the database.++## Explanation+After the user signs and broadcasts a transaction, the client will send the transaction signature to the backend. This endpoint will receive the signature, confirm the transaction on the Solana blockchain, and if it's valid and successful, record the purchase in the `skill_purchases` table.++## Instructions+- **Create a `POST` endpoint: `/api/skills/fulfill_purchase`.**+- **The request body should include `skill_id`, `agent_id`, and `signature`.**+- **Implement the following logic:**+ 1. **Authentication:** Ensure user is logged in.+ 2. **Transaction Verification:**+ - Use the `signature` to query the Solana blockchain.+ - Confirm the transaction has been finalized.+ - Parse the transaction details to ensure it matches the expected payments (correct amounts to creator and platform from the correct user). This prevents replay attacks or forged requests.+ 3. **Database Update:** If verification passes, insert a new record into the `skill_purchases` table.+ 4. **Response:** Return a success message.++## Code Example (Backend)+```javascript+// POST /api/skills/fulfill_purchase+import { Connection } from '@solana/web3.js';++async function fulfillPurchase(req, res) {+ const { skill_id, agent_id, signature } = req.body;+ const user_id = req.session.userId;++ // ... Auth, validation ...++ const connection = new Connection(process.env.SOLANA_RPC_URL);+ try {+ const tx = await connection.getParsedTransaction(signature, 'finalized');+ if (!tx) {+ return res.status(404).json({ error: 'Transaction not found or not finalized.' });+ }++ // ...+ // Add robust logic here to parse tx.transaction.message.instructions+ // and verify it matches the expected purchase details.+ // This is a critical security step.+ // ...++ const query = `+ INSERT INTO skill_purchases (agent_id, user_id, skill_id, price_id, purchase_amount, purchase_currency_mint, transaction_signature)+ VALUES ($1, $2, $3, ...);+ `;+ await db.none(query, [agent_id, user_id, skill_id, ...]);++ return res.status(200).json({ success: true, message: 'Purchase complete.' });++ } catch (error) {+ console.error('Fulfillment error:', error);+ return res.status(500).json({ error: 'Failed to fulfill purchase.' });+ }+}+```diff --git a/tasks/monetization-feature/06-backend-skill-access-control.md b/tasks/monetization-feature/06-backend-skill-access-control.mdnew file mode 100644index 000000000..d9dfd46c3--- /dev/null+++ b/tasks/monetization-feature/06-backend-skill-access-control.md@@ -0,0 +1,31 @@+---+status: not-started+---++# Prompt 6: Backend - Skill Access Control++**Status:** Not Started++## Objective+Implement a mechanism to check if a user has purchased a skill before allowing them to use it.++## Explanation+Once a user has purchased a skill, our backend needs to enforce that only paying users can access it. This involves adding an access control check to the API endpoint that executes a skill.++## Instructions+- [ ] **Create a new database table: `user_skill_access`**. It should contain:+ - `id`: Primary key.+ - `user_id`: Foreign key to the user.+ - `agent_id`: Foreign key to the agent.+ - `skill_name`: The name of the skill.+ - `expires_at`: A timestamp for subscription-based access (optional for now).+- [ ] **After a successful purchase, record the access in this table.** The purchase confirmation step should write a new entry to `user_skill_access`.+- [ ] **Locate the API endpoint that executes skills** (e.g., `/api/agent/invoke`).+- [ ] **Before executing a skill, add a check:**+ - 1. Is the skill a paid skill? Look up its price.+ - 2. If it is paid, does the user have a valid entry in the `user_skill_access` table?+ - 3. If the user does not have access, return a `402 Payment Required` error with a message like "You need to purchase this skill to use it."+ - 4. If the user has access, proceed with executing the skill.++## 402 Payment Required+Using the `402` HTTP status code is the standard way to indicate that a resource is behind a paywall. This is a key part of the [x402 protocol](https://402.wtf/).diff --git a/tasks/monetization-feature/06-frontend-purchase-button-and-modal.md b/tasks/monetization-feature/06-frontend-purchase-button-and-modal.mdnew file mode 100644index 000000000..6e6f3d44d--- /dev/null+++ b/tasks/monetization-feature/06-frontend-purchase-button-and-modal.md@@ -0,0 +1,81 @@+---+status: not-started+---++# Prompt 6: Frontend - "Purchase Skill" Button & Modal++**Status:** Not Started++## Objective+On the agent detail page, display a "Purchase" button for paid skills, which, when clicked, opens a modal with a Solana Pay QR code for the transaction.++## Explanation+Now that the backend can prepare a purchase transaction, the frontend needs to trigger it. This involves changing the UI to show a clear call-to-action for purchasing a skill. Using a modal with a QR code is a standard and user-friendly way to handle crypto payments, as it works seamlessly for both desktop (scanning with a mobile wallet) and mobile users (opening a wallet app directly).++## Instructions+- [ ] **Modify Skill Rendering Logic:** In `src/marketplace.js` (inside `renderDetail`), update the logic that creates skill badges.+ - If a skill has a price and is not yet owned by the user, render a `<button class="purchase-btn">`.+ - Store the `agent_id` and `skill_name` in data attributes on the button (e.g., `data-agent-id="..."`, `data-skill-name="..."`).+- [ ] **Create a Modal:** In `marketplace.html`, add the HTML structure for a modal dialog. It should be hidden by default and contain an element for the QR code and some instructional text.+- [ ] **Add Event Listener:**+ - Attach a click event listener to the `.purchase-btn` buttons.+ - When a button is clicked, prevent the default action, and read the `agent_id` and `skill_name` from the data attributes.+- [ ] **Implement Solana Pay QR Code Generation:**+ - Use the `@solana/pay` frontend library.+ - Inside the event listener, construct the URL for the purchase API (`/api/purchase/skill?agent_id=...&skill_name=...`). This URL is what the wallet will interact with.+ - Use the library to generate a QR code from this URL.+ - Append the generated QR code (it's an `<img>` or `<canvas>` element) to the modal and display the modal.++## Code Example (`src/marketplace.js`)+```javascript+import { createQR } from '@solana/pay';+import { escapeHtml } from './utils'; // Assuming you have this++// ... inside renderDetail function+$('d-skills').innerHTML = skillsArr.map(s => {+ const name = s.name || s;+ const price = skillPrices[name];+ const isOwned = userOwnedSkills.includes(name); // Assume you have this data++ let badge;+ if (isOwned) {+ badge = `<span class="price-badge price-owned">Owned</span>`;+ } else if (price) {+ badge = `<button class="purchase-btn" data-agent-id="${a.id}" data-skill-name="${name}">+ ${(price.amount / 1e6).toFixed(2)} USDC+ </button>`;+ } else {+ badge = `<span class="price-badge price-free">Free</span>`;+ }+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+}).join(' ');++// Add the event listener after rendering+addPurchaseButtonListeners();+++function addPurchaseButtonListeners() {+ const qrCodeContainer = document.getElementById('qr-code-container');+ const purchaseModal = document.getElementById('purchase-modal');++ document.querySelectorAll('.purchase-btn').forEach(button => {+ button.addEventListener('click', (event) => {+ const agentId = event.target.dataset.agentId;+ const skillName = event.target.dataset.skillName;++ // URL for the API endpoint from Prompt 5+ const url = new URL(`${window.location.origin}/api/purchase/skill`);+ url.searchParams.append('agent_id', agentId);+ url.searchParams.append('skill_name', skillName);++ // Generate QR Code+ const qr = createQR(url, 256, 'transparent'); // size, background++ // Display modal+ qrCodeContainer.innerHTML = '';+ qr.append(qrCodeContainer);+ purchaseModal.style.display = 'block';+ });+ });+}+```diff --git a/tasks/monetization-feature/06-frontend-purchase-skill-flow.md b/tasks/monetization-feature/06-frontend-purchase-skill-flow.mdnew file mode 100644index 000000000..908bf374e--- /dev/null+++ b/tasks/monetization-feature/06-frontend-purchase-skill-flow.md@@ -0,0 +1,72 @@+---+status: not-started+---++# Prompt 6: Frontend - Purchase Skill Flow++## Objective+Implement the frontend flow for a user to purchase a skill, including a confirmation modal that shows the price and triggers the transaction.++## Explanation+When a user clicks on a paid skill they don't own, we need to present them with a purchase confirmation modal. This modal will display the skill's name, price, and ask for confirmation. Upon confirmation, it will initiate a Solana transaction to transfer the required amount from the user's wallet to the creator's wallet.++## Instructions+1. **Create the Purchase Modal:**+ * Design and create a modal component that can be dynamically shown when a purchase is initiated.+ * The modal should clearly display the skill name, price, and currency.+ * It should have "Confirm Purchase" and "Cancel" buttons.++2. **Trigger the Modal:**+ * In the agent detail view in the marketplace, add a "Purchase" button next to paid skills that the user doesn't own.+ * When this button is clicked, open the purchase modal and populate it with the skill's data.++3. **Handle the Transaction:**+ * When the "Confirm Purchase" button is clicked, use the connected wallet adapter to create and sign a Solana transaction.+ * The transaction will be a simple SPL token transfer from the user's wallet to the skill creator's wallet.+ * Display feedback to the user while the transaction is being processed and after it has been confirmed or failed.++## Code Example (Frontend - Transaction Logic)++```javascript+import { useConnection, useWallet } from '@solana/wallet-adapter-react';+import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';+import { Transaction, PublicKey } from '@solana/web3.js';++// Inside your purchase confirmation handler++const { connection } = useConnection();+const { publicKey, sendTransaction } = useWallet();++async function handlePurchase(skill) {+ if (!publicKey) {+ alert('Please connect your wallet first.');+ return;+ }++ const { amount, currency_mint, creator_wallet } = skill.price;++ const fromTokenAccount = await getAssociatedTokenAddress(new PublicKey(currency_mint), publicKey);+ const toTokenAccount = await getAssociatedTokenAddress(new PublicKey(currency_mint), new PublicKey(creator_wallet));++ const transaction = new Transaction().add(+ createTransferInstruction(+ fromTokenAccount,+ toTokenAccount,+ publicKey,+ amount+ )+ );++ try {+ const signature = await sendTransaction(transaction, connection);+ await connection.confirmTransaction(signature, 'processed');++ // After successful transaction, call the backend to record the purchase+ // ...++ } catch (error) {+ console.error('Transaction failed:', error);+ alert('Transaction failed. Please try again.');+ }+}+```diff --git a/tasks/monetization-feature/07-frontend-ui-creator-dashboard.md b/tasks/monetization-feature/07-frontend-ui-creator-dashboard.mdnew file mode 100644index 000000000..90cd7ab4c--- /dev/null+++ b/tasks/monetization-feature/07-frontend-ui-creator-dashboard.md@@ -0,0 +1,59 @@+---+status: not-started+---+# Prompt 7: Creator Dashboard UI++**Status:** Not Started++## Objective+Create a new "Creator Dashboard" page where users can see a list of the skills they have created.++## Explanation+To enable creators to manage their skills (e.g., set prices), they first need a dedicated space to view their creations. This task involves creating a new HTML page and the associated JavaScript to fetch and display the skills created by the currently logged-in user.++## Instructions+1. **Create a new HTML file: `public/creator-dashboard.html`.**+2. **Add basic HTML structure, including a header and a main content area with an empty container for the skill list, like `<div id="my-skills-list"></div>`.**+3. **Create a new JavaScript file: `src/creator-dashboard.js`.**+4. **In the script, add a function to fetch skills from a new API endpoint (e.g., `/api/users/me/skills`).**+5. **On page load, call this function and render the returned skills into the `#my-skills-list` container.**+ - For each skill, display its name, description, and a placeholder for future actions (like a "Set Price" button).++## Code Example (Frontend - `src/creator-dashboard.js`)+```javascript+document.addEventListener('DOMContentLoaded', () => {+ fetchMySkills();+});++async function fetchMySkills() {+ try {+ const response = await fetch('/api/users/me/skills'); // Assumes this API exists+ if (!response.ok) throw new Error('Failed to fetch skills.');++ const skills = await response.json();+ renderSkills(skills);+ } catch (error) {+ console.error(error);+ document.getElementById('my-skills-list').innerHTML = `<p>Error loading your skills.</p>`;+ }+}++function renderSkills(skills) {+ const container = document.getElementById('my-skills-list');+ if (!skills.length) {+ container.innerHTML = `<p>You haven't created any skills yet.</p>`;+ return;+ }++ container.innerHTML = skills.map(skill => `+ <div class="skill-card">+ <h3>${skill.name}</h3>+ <p>${skill.description}</p>+ <div class="skill-actions">+ <button data-skill-id="${skill.id}" class="set-price-btn">Set Price</button>+ </div>+ </div>+ `).join('');+}+```+*Note: This requires a new backend endpoint `GET /api/users/me/skills` which should be created as part of this task.*diff --git a/tasks/monetization-feature/07-ui-handling-402-payment-required.md b/tasks/monetization-feature/07-ui-handling-402-payment-required.mdnew file mode 100644index 000000000..184030463--- /dev/null+++ b/tasks/monetization-feature/07-ui-handling-402-payment-required.md@@ -0,0 +1,26 @@+---+status: not-started+---++# Prompt 7: UI - Handling 402 Payment Required++**Status:** Not Started++## Objective+Update the frontend to gracefully handle the `402 Payment Required` error from the backend and guide the user to purchase the skill.++## Explanation+When a user tries to use a paid skill they don't own, the backend will block them. The UI should catch this specific error and show a helpful message, such as a popup that prompts them to buy the skill.++## Instructions+- [ ] **In the part of your frontend code that calls the skill execution endpoint, add error handling.**+- [ ] **Specifically check for a `402` status code in the response.**+- [ ] **If a `402` error is received:**+ - 1. **Prevent the default error message** from being shown.+ - 2. **Display a modal or a notification** to the user.+ - 3. **The message should be clear,** e.g., "This is a premium skill. To use it, you need to purchase it first."+ - 4. **Include a "Purchase Skill" button** in the modal, which should trigger the purchase flow designed in a previous prompt.+ - 5. **Optionally, include a "Cancel" button** to close the modal.++## User Experience+This is a critical part of the user experience. Instead of a generic "Error" message, we are creating a clear call to action that guides the user through the monetization funnel.diff --git a/tasks/monetization-feature/07-ui-purchase-modal.md b/tasks/monetization-feature/07-ui-purchase-modal.mdnew file mode 100644index 000000000..8e5d15a88--- /dev/null+++ b/tasks/monetization-feature/07-ui-purchase-modal.md@@ -0,0 +1,68 @@+---+status: not-started+---++# Prompt 7: UI - Create Purchase Modal++**Status:** Not Started++## Objective+Design and implement a modal dialog that appears when a user clicks the "Buy" button, presenting them with payment options.++## Explanation+A modal provides a focused, clean user experience for the payment process. This first version of the modal will be simple. It will confirm the skill being purchased and its price, and for now, it will present a Solana Pay QR code for the transaction. This separates the payment step from the main UI and prepares us for adding more payment methods later.++## Instructions+- [ ] **Add HTML for the modal to `marketplace.html`:**+ - [ ] Create a hidden `div` that will serve as the modal container.+ - [ ] Inside, add elements for a title, skill name, price, a container for a QR code, and a close button.+- [ ] **Add CSS for the modal in `marketplace.css`:**+ - [ ] Style the modal to overlay the page content with a dark backdrop.+ - [ ] Center the modal content and style the text and QR code container.+- [ ] **Add JavaScript logic in `src/marketplace.js`:**+ - [ ] Create a function `showPurchaseModal(agentId, skillName, price)`.+ - [ ] Attach a click event listener to the `d-skills` container that delegates to `.purchase-btn` clicks.+ - [ ] When a purchase button is clicked, call `showPurchaseModal` with the relevant data from the button's `data-` attributes.+ - [ ] The function will populate and display the modal.++## HTML Example (`marketplace.html`)+```html+<!-- Add this somewhere inside the <body> tag -->+<div id="purchaseModal" class="modal-hidden">+ <div class="modal-content">+ <span class="modal-close-btn">×</span>+ <h2>Purchase Skill</h2>+ <p>You are about to buy the skill:</p>+ <p id="modalSkillName" class="modal-skill-name"></p>+ <p>for</p>+ <p id="modalSkillPrice" class="modal-skill-price"></p>+ <div id="modalQrCode"></div>+ <p class="modal-hint">Scan with a Solana Pay compatible wallet.</p>+ </div>+</div>+```++## CSS Example (`marketplace.css`)+```css+.modal-hidden { display: none; }+#purchaseModal {+ position: fixed; z-index: 1000; left: 0; top: 0;+ width: 100%; height: 100%;+ background-color: rgba(0,0,0,0.6);+ display: flex; align-items: center; justify-content: center;+}+.modal-content {+ background-color: #1a1a1a; color: #fff;+ padding: 2rem; border-radius: 8px;+ width: 90%; max-width: 400px;+ text-align: center;+ position: relative;+}+.modal-close-btn {+ position: absolute; top: 10px; right: 15px;+ font-size: 28px; font-weight: bold; cursor: pointer;+}+```++## 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/08-creator-earnings-dashboard.md b/tasks/monetization-feature/08-creator-earnings-dashboard.mdnew file mode 100644index 000000000..c8d934d6d--- /dev/null+++ b/tasks/monetization-feature/08-creator-earnings-dashboard.md@@ -0,0 +1,33 @@+---+status: not-started+---++# Prompt 8: Creator Earnings Dashboard++**Status:** Not Started++## Objective+Create a dashboard for creators to view their earnings from skill sales.++## Explanation+Creators need to be able to track how much they've earned. This requires a new page in the creator dashboard that shows total revenue, a list of recent sales, and other relevant analytics.++## Instructions+- [ ] **Create a new database table: `skill_sales`**. It should log every purchase:+ - `id`: Primary key.+ - `agent_id`: The agent whose skill was sold.+ - `creator_id`: The user who owns the agent.+ - `buyer_id`: The user who bought the skill.+ - `skill_name`: The name of the skill.+ - `amount`: The sale price.+ - `currency_mint`: The currency of the sale.+ - `signature`: The Solana transaction signature of the sale.+ - `created_at`: Timestamp.+- [ ] **Log every sale.** After a successful purchase is confirmed on-chain, add an entry to this table.+- [ ] **Create a new API endpoint, e.g., `GET /api/dashboard/earnings`**.+ - This endpoint should query the `skill_sales` table for the currently logged-in user.+ - It should return aggregated data (total earnings per currency) and a list of recent transactions.+- [ ] **Create a new page in the dashboard (e.g., `dashboard/earnings.html`)**.+ - This page should fetch data from the new API endpoint.+ - **Display summary cards:** "Total Earnings (USDC)", "Total Earnings (SOL)", etc.+ - **Display a table of recent sales:** Show the skill name, date, price, and buyer.diff --git a/tasks/monetization-feature/08-frontend-ui-set-price-modal.md b/tasks/monetization-feature/08-frontend-ui-set-price-modal.mdnew file mode 100644index 000000000..72d10a6e6--- /dev/null+++ b/tasks/monetization-feature/08-frontend-ui-set-price-modal.md@@ -0,0 +1,51 @@+---+status: not-started+---+# Prompt 8: Set Price Modal UI++**Status:** Not Started++## Objective+Design and implement a modal dialog on the Creator Dashboard for setting a skill's price.++## Explanation+Clicking the "Set Price" button next to a skill should open a modal where the creator can input a price and select a currency. This provides a clean and focused user experience for price management.++## Instructions+1. **Add a hidden modal structure to `public/creator-dashboard.html`.** It should be outside the main flow, ready to be displayed with JavaScript.+2. **The modal should contain:**+ - A title, e.g., "Set Price for [Skill Name]".+ - An input field for the `amount`.+ - A dropdown (`<select>`) for the `currency_mint`. Pre-fill this with supported currencies (e.g., USDC, SOL).+ - "Save" and "Cancel" buttons.+3. **In `src/creator-dashboard.js`, add an event listener to the `#my-skills-list` container.**+4. **Delegate the event to handle clicks on `.set-price-btn` buttons.**+5. **When a button is clicked:**+ - Get the `skill_id` from the `data-skill-id` attribute.+ - Populate the modal's title with the skill's name.+ - Show the modal.++## HTML Example (in `creator-dashboard.html`)+```html+<div id="price-modal" class="modal" hidden>+ <div class="modal-content">+ <h2 id="modal-title">Set Price</h2>+ <form id="price-form">+ <input type="hidden" id="modal-skill-id" />+ <div>+ <label for="price-amount">Amount</label>+ <input type="number" id="price-amount" step="0.01" min="0" required />+ </div>+ <div>+ <label for="price-currency">Currency</label>+ <select id="price-currency" required>+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T">USDC</option>+ <!-- Add other currencies like native SOL -->+ </select>+ </div>+ <button type="submit">Save</button>+ <button type="button" id="modal-cancel-btn">Cancel</button>+ </form>+ </div>+</div>+```diff --git a/tasks/monetization-feature/09-frontend-js-set-price-api-call.md b/tasks/monetization-feature/09-frontend-js-set-price-api-call.mdnew file mode 100644index 000000000..1569f2295--- /dev/null+++ b/tasks/monetization-feature/09-frontend-js-set-price-api-call.md@@ -0,0 +1,62 @@+---+status: not-started+---+# Prompt 9: Set Price API Call from Frontend++**Status:** Not Started++## Objective+Implement the frontend JavaScript logic to submit the new price from the modal to the backend API.++## Explanation+This task connects the UI created in the previous step to the backend API for setting prices. It involves handling the form submission, calling the API with the correct data, and providing feedback to the user based on the response.++## Instructions+- **In `src/creator-dashboard.js`, add a `submit` event listener to the `#price-form` in the modal.**+- **Inside the submit handler:**+ 1. Prevent the default form submission.+ 2. Retrieve the `skill_id`, `amount`, and `currency_mint` from the form inputs.+ 3. **Important:** Convert the human-readable amount (e.g., 1.50 USDC) to the smallest unit required by the backend (e.g., 1,500,000 lamports). This might involve multiplying by `1e6` for USDC.+ 4. Call the `POST /api/skills/:skill_id/price` endpoint using `fetch`.+ 5. Include the data in the request body as JSON.+ 6. Handle the response:+ - On success, close the modal and show a confirmation message. Maybe update the UI to show the new price.+ - On failure, display an error message to the user.++## Code Example (Frontend - `src/creator-dashboard.js`)+```javascript+document.getElementById('price-form').addEventListener('submit', async (event) => {+ event.preventDefault();++ const skillId = document.getElementById('modal-skill-id').value;+ const amountInput = document.getElementById('price-amount').value;+ const currency = document.getElementById('price-currency').value;++ // Convert to smallest unit (e.g., lamports for USDC)+ const amountInSmallestUnit = parseFloat(amountInput) * 1e6;++ try {+ const response = await fetch(`/api/skills/${skillId}/price`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ amount: amountInSmallestUnit,+ currency_mint: currency,+ }),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.error || 'Failed to set price.');+ }++ // Success+ alert('Price updated successfully!');+ document.getElementById('price-modal').hidden = true;+ fetchMySkills(); // Refresh the list to show new price++ } catch (error) {+ alert(`Error: ${error.message}`);+ }+});+```diff --git a/tasks/monetization-feature/09-platform-fee-system.md b/tasks/monetization-feature/09-platform-fee-system.mdnew file mode 100644index 000000000..947df688e--- /dev/null+++ b/tasks/monetization-feature/09-platform-fee-system.md@@ -0,0 +1,30 @@+---+status: not-started+---++# Prompt 9: Platform Fee System++**Status:** Not Started++## Objective+Implement a platform fee for every skill purchase.++## Explanation+To make the platform sustainable, we will take a small percentage of each skill sale as a platform fee. This requires modifying the purchase transaction to include a transfer to the platform's wallet.++## Instructions+- [ ] **Modify the skill purchase API (`/api/skills/purchase`)**.+- [ ] **When constructing the transaction, add a second `transfer` instruction.**+ - The source will be the user's account.+ - The destination will be the platform's fee wallet.+ - The amount should be a percentage of the total price (e.g., 5%).+- [ ] **Adjust the creator's transfer amount.** The amount transferred to the creator should be the total price minus the platform fee.+- [ ] **The sum of the two transfers must equal the total amount** the user is paying.+- [ ] **Store the platform fee** in the `skill_sales` table for accounting purposes. Add a `platform_fee` column.++## Example+If a skill costs 1 USDC and the platform fee is 5%:+- The user pays 1 USDC.+- The creator receives 0.95 USDC.+- The platform receives 0.05 USDC.+The Solana transaction will contain two separate transfers to reflect this split. This is known as a "split transaction".diff --git a/tasks/monetization-feature/10-frontend-add-purchase-button.md b/tasks/monetization-feature/10-frontend-add-purchase-button.mdnew file mode 100644index 000000000..7775e457b--- /dev/null+++ b/tasks/monetization-feature/10-frontend-add-purchase-button.md@@ -0,0 +1,49 @@+---+status: not-started+---+# Prompt 10: Add Purchase Button to Marketplace++**Status:** Not Started++## Objective+In the marketplace agent detail page, add a "Purchase" button next to skills that are not free.++## Explanation+Now that skills can have prices, the marketplace UI must be updated to allow users to initiate a purchase. This task modifies the existing skill rendering logic to include a "Purchase" button, which will be wired up in subsequent tasks.++## Instructions+1. **Open `src/marketplace.js` and locate the `renderDetail` function.**+2. **Modify the skill rendering loop.** The agent details from the API should already include pricing information from Prompt #1.+3. **Update the logic that generates the skill badge:**+ - If a skill is free, continue showing the "Free" badge.+ - If a skill has a price and has **not** been purchased by the user, show the price and a "Purchase" button.+ - If a skill has a price and **has** been purchased, show the price and an "Owned" indicator.+4. You will need a way to know which skills the user already owns for a given agent. This may require an API modification to include a list of purchased `skill_id`s in the agent detail payload.++## Code Example (Frontend - `src/marketplace.js`, modified `renderDetail`)+```javascript+// Inside renderDetail function+const skillPrices = a.skill_prices || {};+const ownedSkills = a.owned_skills || []; // Assumes API now provides this array of skill names++$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];++ let badgeHtml = '';+ if (price) {+ const priceDisplay = `${(price.amount / 1e6).toFixed(2)} USDC`;+ if (ownedSkills.includes(name)) {+ badgeHtml = `<span class="price-badge price-owned">Owned</span> <span class="price-display">${priceDisplay}</span>`;+ } else {+ badgeHtml = `<span class="price-display">${priceDisplay}</span> <button class="purchase-btn" data-skill-name="${name}">Purchase</button>`;+ }+ } else {+ badgeHtml = `<span class="price-badge price-free">Free</span>`;+ }++ return `<span class="skill-entry">${escapeHtml(name)}${badgeHtml}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+```diff --git a/tasks/monetization-feature/10-subscription-based-skills-db-schema.md b/tasks/monetization-feature/10-subscription-based-skills-db-schema.mdnew file mode 100644index 000000000..ecc14b1b0--- /dev/null+++ b/tasks/monetization-feature/10-subscription-based-skills-db-schema.md@@ -0,0 +1,24 @@+---+status: not-started+---++# Prompt 10: Subscription-Based Skills (Part 1 - DB Schema)++**Status:** Not Started++## Objective+Update the database schema to support subscription-based pricing for skills (e.g., monthly access).++## Explanation+In addition to one-time purchases, we want to allow creators to sell skills as a recurring subscription. This requires changes to how we model pricing and access.++## Instructions+- [ ] **Modify the `agent_skill_prices` table.**+ - Add a `pricing_type` column (e.g., `one_time` or `subscription`).+ - Add a `renewal_period_days` column (e.g., 30 for monthly). This can be nullable if `pricing_type` is `one_time`.+- [ ] **Modify the `user_skill_access` table.**+ - Ensure the `expires_at` column exists. When a user buys a subscription, this will be set to `now() + renewal_period_days`.+- [ ] **Update the creator dashboard UI.**+ - When setting a price, allow creators to choose between "One-Time" and "Subscription".+ - If "Subscription" is chosen, show an input for the renewal period.+- [ ] **Update the API for saving prices** to handle these new fields.diff --git a/tasks/monetization-feature/11-frontend-wallet-connection.md b/tasks/monetization-feature/11-frontend-wallet-connection.mdnew file mode 100644index 000000000..0ccb7dd76--- /dev/null+++ b/tasks/monetization-feature/11-frontend-wallet-connection.md@@ -0,0 +1,55 @@+---+status: not-started+---+# Prompt 11: Frontend Wallet Connection++**Status:** Not Started++## Objective+Implement a "Connect Wallet" feature allowing users to connect their Solana wallets (e.g., Phantom) to the application.++## Explanation+To perform on-chain transactions, the application needs permission to interact with the user's wallet. This task involves adding a UI element for connecting a wallet and using a library like `@solana/wallet-adapter` to handle the connection logic.++## Instructions+1. **Add the necessary libraries to your project:**+ ```bash+ npm install @solana/wallet-adapter-base @solana/wallet-adapter-react @solana/wallet-adapter-wallets @solana/web3.js+ ```+ *(Note: If not using React, you can use the base libraries and implement your own UI bindings.)*+2. **Add a "Connect Wallet" button to your site's main header.**+3. **Wrap your application's main component with `ConnectionProvider`, `WalletProvider`, and add a `WalletModalProvider` for the connection dialog.**+4. **Use the `useWallet` hook (or equivalent) to get the connection status and public key.**+ - When connected, change the button text to show the user's public key (truncated).+ - Store the user's public key in a global state or variable for use in purchase flows.++## Code Example (Using `@solana/wallet-adapter-react` and components)+```javascript+// In your main layout/app component+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 { PhantomWalletAdapter } from '@solana/wallet-adapter-wallets';+// ... more adapters++// In your render method+const network = WalletAdapterNetwork.Mainnet;+const endpoint = useMemo(() => clusterApiUrl(network), [network]);+const wallets = useMemo(() => [new PhantomWalletAdapter()], [network]);++return (+ <ConnectionProvider endpoint={endpoint}>+ <WalletProvider wallets={wallets} autoConnect>+ <WalletModalProvider>+ {/* Your app content */}+ <header>+ {/* ... other nav items ... */}+ <WalletMultiButton />+ </header>+ {/* ... rest of your app ... */}+ </WalletModalProvider>+ </WalletProvider>+ </ConnectionProvider>+);+```+*This provides a pre-built button and modal for a quick setup.*diff --git a/tasks/monetization-feature/11-subscription-based-skills-access-logic.md b/tasks/monetization-feature/11-subscription-based-skills-access-logic.mdnew file mode 100644index 000000000..0bf92220d--- /dev/null+++ b/tasks/monetization-feature/11-subscription-based-skills-access-logic.md@@ -0,0 +1,25 @@+---+status: not-started+---++# Prompt 11: Subscription-Based Skills (Part 2 - Access Logic)++**Status:** Not Started++## Objective+Update the skill access control logic to handle subscriptions.++## Explanation+Now that we can store subscription prices, we need to enforce access based on whether a user's subscription is active.++## Instructions+- [ ] **Modify the skill purchase logic.**+ - When a user buys a subscription skill, in the `user_skill_access` table, set `expires_at` to the correct future date.+- [ ] **Modify the skill access control check (`/api/agent/invoke`).**+ - When checking for access in the `user_skill_access` table:+ - If the skill is a subscription, you must also check that `expires_at` is in the future.+ - `WHERE user_id = ? AND skill_name = ? AND expires_at > NOW()`+- [ ] **Update the UI to show subscription status.**+ - On the agent detail page, if a user owns a subscription, show "Subscribed" and the expiry date instead of a "Buy" button.+ - If a subscription is expired, show a "Renew" button.+- [ ] **Implement the renewal logic.** The "Renew" button should trigger the same purchase flow, which will update the `expires_at` date.diff --git a/tasks/monetization-feature/12-frontend-js-initiate-purchase.md b/tasks/monetization-feature/12-frontend-js-initiate-purchase.mdnew file mode 100644index 000000000..a442d62b2--- /dev/null+++ b/tasks/monetization-feature/12-frontend-js-initiate-purchase.md@@ -0,0 +1,64 @@+---+status: not-started+---+# Prompt 12: Frontend Initiates Purchase++**Status:** Not Started++## Objective+Write the frontend JavaScript to call the backend API and fetch the unsigned transaction when a user clicks "Purchase".++## Explanation+This is the first step in the client-side purchase flow. After the user clicks the purchase button, the frontend needs to communicate with the backend to get a transaction that can then be passed to the user's wallet for signing.++## Instructions+1. **In `src/marketplace.js`, add a click event listener to the skills container.**+2. **Delegate the event to handle clicks on `.purchase-btn` buttons.**+3. **Inside the handler:**+ - Check if the user's wallet is connected. If not, prompt them to connect it.+ - Get the skill name from the `data-skill-name` attribute.+ - Get the current agent ID from the page context.+ - Get the user's public key from the wallet adapter state.+ - Show a "Preparing transaction..." loading indicator.+ - Call the `POST /api/skills/:skill_id/purchase` endpoint (from Prompt 5). Note: you might need to pass the skill name and get the ID. The API might be better as `/api/skills/purchase` with the name in the body.+ - Pass the user's public key (`account`) in the request body.+ - The API will respond with a base64-encoded transaction string.++## Code Example (Frontend - `src/marketplace.js`)+```javascript+// Using a hypothetical wallet state object+// const { publicKey, connected } = useWallet();++$('d-skills').addEventListener('click', async (event) => {+ if (!event.target.matches('.purchase-btn')) return;++ if (!connected || !publicKey) {+ alert('Please connect your wallet to purchase a skill.');+ return;+ }++ const skillName = event.target.dataset.skillName;+ const agentId = getCurrentAgentId(); // Function to get agent ID from URL or state++ try {+ const response = await fetch(`/api/skills/purchase`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ skillName: skillName,+ agentId: agentId,+ account: publicKey.toBase58(),+ })+ });++ if (!response.ok) throw new Error('Failed to prepare transaction.');++ const { transaction } = await response.json();+ // Next step: pass this 'transaction' string to the signing function+ await signAndSendTransaction(transaction);++ } catch (error) {+ alert(`Purchase failed: ${error.message}`);+ }+});+```diff --git a/tasks/monetization-feature/12-gated-content-via-nfts.md b/tasks/monetization-feature/12-gated-content-via-nfts.mdnew file mode 100644index 000000000..fae7368c4--- /dev/null+++ b/tasks/monetization-feature/12-gated-content-via-nfts.md@@ -0,0 +1,28 @@+---+status: not-started+---++# Prompt 12: Gated Content/Skills via NFTs++**Status:** Not Started++## Objective+Allow creators to restrict access to skills to only holders of a specific NFT.++## Explanation+To add more utility for NFT projects, we can allow agent creators to gate their skills. Only users who hold a specific NFT (from a certain collection) in their wallet can use the skill.++## Instructions+- [ ] **Modify the `agent_skill_prices` table (or create a new `agent_skill_gates` table).**+ - Add a `gate_type` column (e.g., `price` or `nft`).+ - Add an `nft_collection_mint` column.+- [ ] **Update the creator dashboard UI.**+ - Allow creators to choose "NFT Gate" as a pricing option.+ - If chosen, provide an input for the NFT collection mint address.+- [ ] **Modify the skill access control check.**+ - If a skill is gated by an NFT:+ - Get the user's wallet address.+ - Use a Solana RPC provider (e.g., Helius) to check if the user's wallet holds at least one NFT from the `nft_collection_mint`.+ - If they do, grant access. If not, return a `402` error with a message like "You need to hold an NFT from collection X to use this skill."+- [ ] **Update the UI to show NFT-gated skills.**+ - Clearly indicate that a skill is "Token Gated" and show the required collection.diff --git a/tasks/monetization-feature/13-free-trials-for-skills.md b/tasks/monetization-feature/13-free-trials-for-skills.mdnew file mode 100644index 000000000..f95a27945--- /dev/null+++ b/tasks/monetization-feature/13-free-trials-for-skills.md@@ -0,0 +1,25 @@+---+status: not-started+---++# Prompt 13: Free Trials for Skills++**Status:** Not Started++## Objective+Allow creators to offer a limited-time free trial for their paid skills.++## Explanation+Free trials are a great way for users to experience the value of a premium skill before committing to a purchase. We can implement this by granting temporary access.++## Instructions+- [ ] **Modify the `agent_skill_prices` table.**+ - Add a `trial_period_days` column.+- [ ] **Update the creator dashboard UI.**+ - Add a checkbox and an input field for creators to enable a free trial and set its duration.+- [ ] **On the agent detail page, show a "Start Free Trial" button** for skills that have one.+- [ ] **When a user clicks "Start Free Trial":**+ - Make an API call to a new endpoint (e.g., `POST /api/skills/start-trial`).+ - This endpoint adds an entry to the `user_skill_access` table with an `expires_at` date set to `now() + trial_period_days`. It should also record that this is a trial.+ - Add a `is_trial` boolean column to `user_skill_access`. A user should only be ableto start a trial for a specific skill once.+- [ ] **The access control logic will now automatically handle trial access** due to the `expires_at` check.diff --git a/tasks/monetization-feature/14-skill-bundles.md b/tasks/monetization-feature/14-skill-bundles.mdnew file mode 100644index 000000000..1595b06b1--- /dev/null+++ b/tasks/monetization-feature/14-skill-bundles.md@@ -0,0 +1,26 @@+---+status: not-started+---++# Prompt 14: Skill Bundles++**Status:** Not Started++## Objective+Allow creators to sell multiple skills together as a discounted bundle.++## Explanation+Bundles can increase the average revenue per user. A creator could offer a "Pro Pack" of 3 skills at a lower price than buying them individually.++## Instructions+- [ ] **Create new database tables:**+ - `skill_bundles`: to store bundle details (`id`, `agent_id`, `name`, `price`, `currency_mint`).+ - `bundle_skills`: a join table linking bundles to skills (`bundle_id`, `skill_name`).+- [ ] **Update the creator dashboard.**+ - Add a new section for creating and managing bundles.+ - A creator should be able to create a bundle, give it a name, set a price, and select which of their existing skills to include.+- [ ] **Update the marketplace UI.**+ - Display bundles on the agent detail page.+ - A "Buy Bundle" button should trigger a purchase flow similar to a single skill.+- [ ] **Update the purchase and access logic.**+ - When a bundle is purchased, grant access to *all* skills within that bundle in the `user_skill_access` table.diff --git a/tasks/monetization-feature/15-pay-what-you-want-pricing.md b/tasks/monetization-feature/15-pay-what-you-want-pricing.mdnew file mode 100644index 000000000..9c0c4d2ee--- /dev/null+++ b/tasks/monetization-feature/15-pay-what-you-want-pricing.md@@ -0,0 +1,28 @@+---+status: not-started+---++# Prompt 15: "Pay What You Want" Pricing++**Status:** Not Started++## Objective+Allow creators to set a skill as "Pay What You Want" (PWYW), optionally with a minimum price.++## Explanation+PWYW can be a powerful tool for community engagement and can sometimes lead to higher revenue than a fixed price.++## Instructions+- [ ] **Modify the `agent_skill_prices` table.**+ - Add a `pricing_type` of `pwyw`.+ - Add a `minimum_amount` column (can be 0).+- [ ] **Update the creator dashboard.**+ - Add "Pay What You Want" as a pricing option.+ - If selected, allow setting a minimum price.+- [ ] **Update the UI on the agent detail page.**+ - For PWYW skills, instead of a "Buy" button, show an input field for the amount and a "Pay" button.+ - Client-side validation should ensure the entered amount is not below the minimum.+- [ ] **Update the purchase API (`/api/skills/purchase`).**+ - It should now accept an optional `amount` in the request body for PWYW skills.+ - The backend must validate that this amount is above the `minimum_amount`.+ - The transaction is then constructed with the user-defined amount.diff --git a/tasks/monetization-feature/16-user-purchase-history.md b/tasks/monetization-feature/16-user-purchase-history.mdnew file mode 100644index 000000000..b9d900a85--- /dev/null+++ b/tasks/monetization-feature/16-user-purchase-history.md@@ -0,0 +1,22 @@+---+status: not-started+---++# Prompt 16: User Purchase History++**Status:** Not Started++## Objective+Create a page in the user's dashboard where they can see a history of all their skill purchases.++## Explanation+Users need a way to track their spending and see which skills they've bought. This is important for transparency and user trust.++## Instructions+- [ ] **Create a new API endpoint, e.g., `GET /api/users/me/purchases`**.+ - This should query the `skill_sales` table for all records where the `buyer_id` matches the current user.+ - It should return a list of purchases with details like agent name, skill name, price, and date.+- [ ] **Create a new page in the user dashboard (e.g., `dashboard/history.html`)**.+- [ ] **On this page, fetch the purchase history** from the new API endpoint.+- [ ] **Display the purchases in a clean, readable table.**+- [ ] **For each purchase, include a link to the Solana transaction on an explorer** like Solscan or X-Ray. The transaction signature is stored in the `skill_sales` table.diff --git a/tasks/monetization-feature/17-invoicing-and-receipts.md b/tasks/monetization-feature/17-invoicing-and-receipts.mdnew file mode 100644index 000000000..fb457628b--- /dev/null+++ b/tasks/monetization-feature/17-invoicing-and-receipts.md@@ -0,0 +1,28 @@+---+status: not-started+---++# Prompt 17: Invoicing and Receipts++**Status:** Not Started++## Objective+Generate a simple invoice or receipt for each purchase and make it accessible to the user.++## Explanation+For accounting and record-keeping, users should be able to get a receipt for their purchases.++## Instructions+- [ ] **After a successful purchase, generate a receipt.** This can be done in the backend.+- [ ] **The receipt should contain:**+ - A unique invoice number.+ - Date of purchase.+ - Buyer and seller (creator) details.+ - A description of the item (e.g., "Skill: text-to-speech for Agent X").+ - The price paid.+ - The transaction signature.+- [ ] **Store the receipt.** You can store it as a JSON object in a new `receipts` table or as a PDF in cloud storage.+- [ ] **Modify the User Purchase History page.**+ - Add a "View Receipt" link or button to each entry in the history table.+- [ ] **Create an API endpoint to fetch a single receipt** (e.g., `GET /api/receipts/:id`).+- [ ] **When a user clicks "View Receipt", display the receipt details** in a clean, printable format.diff --git a/tasks/monetization-feature/18-affiliate-referral-program.md b/tasks/monetization-feature/18-affiliate-referral-program.mdnew file mode 100644index 000000000..6cc97daf0--- /dev/null+++ b/tasks/monetization-feature/18-affiliate-referral-program.md@@ -0,0 +1,29 @@+---+status: not-started+---++# Prompt 18: Affiliate/Referral Program++**Status:** Not Started++## Objective+Implement a referral system where users can earn a commission for referring new buyers.++## Explanation+Referral programs are a great way to incentivize word-of-mouth marketing. A user can share a special link to an agent, and if someone makes a purchase through that link, the referrer gets a percentage of the sale.++## Instructions+- [ ] **Database Schema:**+ - Add a `referral_code` column to the `users` table.+ - Create a `referrals` table to track referral relationships (`referrer_id`, `referred_id`).+ - Add a `referred_by_user_id` column to the `skill_sales` table.+- [ ] **Generate Referral Links:** On the agent detail page, add a "Share" button that generates a unique referral link (e.g., `/marketplace/agent/ID?ref=USER_CODE`).+- [ ] **Track Referrals:** When a user lands on a page with a `ref` code, store it in their session or local storage. When they sign up or make a purchase, associate them with the referrer.+- [ ] **Modify the Purchase Transaction:**+ - If a sale was made through a referral, modify the transaction to include a third transfer for the referral commission.+ - Example: 1 USDC sale, 5% platform fee, 10% referral commission.+ - Buyer pays 1 USDC.+ - Creator gets 0.85 USDC.+ - Platform gets 0.05 USDC.+ - Referrer gets 0.10 USDC.+- [ ] **Update the Earnings Dashboards** for both creators and referrers to show referral income.diff --git a/tasks/monetization-feature/19-support-for-multiple-currencies.md b/tasks/monetization-feature/19-support-for-multiple-currencies.mdnew file mode 100644index 000000000..56caf5116--- /dev/null+++ b/tasks/monetization-feature/19-support-for-multiple-currencies.md@@ -0,0 +1,24 @@+---+status: not-started+---++# Prompt 19: Support for Multiple Currencies++**Status:** Not Started++## Objective+Allow creators to set prices in different SPL tokens (e.g., BONK, WIF) and allow buyers to pay in any of them.++## Explanation+To embrace the Solana ecosystem, we should support more than just USDC. This will involve using a DEX like Jupiter to handle currency swaps during the purchase.++## Instructions+- [ ] **Update the Creator Dashboard UI:** The currency dropdown for setting prices should include a list of whitelisted SPL tokens.+- [ ] **Update the Purchase API (`/api/skills/purchase`):**+ - The API should now accept an additional parameter: `payment_mint`, the token the user wants to pay with.+- [ ] **Integrate with Jupiter API:**+ - When a user wants to pay with BONK for a skill priced in USDC:+ - 1. Use the Jupiter API to get a `swap` transaction that converts the right amount of the user's BONK into the required amount of USDC.+ - 2. The destination for the USDC should be a temporary account or directly to the creator/platform wallets.+ - 3. **Combine the transactions:** The full transaction sent to the user will include the Jupiter swap *and* the payment transfers. The user signs one transaction that does everything.+- [ ] **Update the Frontend:** The "Buy" button should present the user with a choice of which token to pay with.diff --git a/tasks/monetization-feature/20-analytics-for-creators.md b/tasks/monetization-feature/20-analytics-for-creators.mdnew file mode 100644index 000000000..bcb08a941--- /dev/null+++ b/tasks/monetization-feature/20-analytics-for-creators.md@@ -0,0 +1,31 @@+---+status: not-started+---++# Prompt 20: Analytics for Creators++**Status:** Not Started++## Objective+Provide creators with analytics on their skill sales, such as page views, conversion rates, and top referrers.++## Explanation+Data helps creators make better decisions. We can provide them with simple analytics to understand how their agent is performing in the marketplace.++## Instructions+- [ ] **Track Events:**+ - Create a new table `analytics_events`.+ - Log key events: `agent_page_view`, `skill_purchase`, `referral_link_click`.+ - Include details like `agent_id`, `user_id`, and other relevant metadata.+- [ ] **Create a new API endpoint, e.g., `GET /api/dashboard/analytics`**.+ - This endpoint will query the `analytics_events` table and aggregate the data.+ - Calculate metrics like:+ - Total views in the last 30 days.+ - Number of sales.+ - Conversion rate (sales / views).+ - Top-performing skills.+- [ ] **Create a new "Analytics" tab in the creator dashboard.**+- [ ] **Display the analytics using simple charts and cards.**+ - A line chart for views over time.+ - A bar chart for sales per skill.+ - A summary card for conversion rate.diff --git a/tasks/monetization-feature/21-user-ratings-and-reviews.md b/tasks/monetization-feature/21-user-ratings-and-reviews.mdnew file mode 100644index 000000000..5fc1d2747--- /dev/null+++ b/tasks/monetization-feature/21-user-ratings-and-reviews.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 21: User Ratings and Reviews for Skills++**Status:** Not Started++## Objective+Allow users who have purchased a skill to leave a rating and a written review.++## Explanation+Social proof is a powerful driver of sales. Ratings and reviews help users make informed decisions and reward high-quality work from creators.++## Instructions+- [ ] **Create a `skill_reviews` table:**+ - `id`, `user_id`, `agent_id`, `skill_name`, `rating` (1-5), `comment` (text), `created_at`.+- [ ] **On the agent detail page, after a user has purchased a skill, allow them to submit a review.**+- [ ] **Create API endpoints for submitting and fetching reviews.**+ - `POST /api/skills/review`: to submit a new review. The backend should verify that the user actually owns the skill.+ - `GET /api/agents/:id/reviews`: to fetch all reviews for an agent's skills.+- [ ] **Display the average rating and the number of reviews** next to each skill in the marketplace.+- [ ] **Create a "Reviews" tab** on the agent detail page where users can read all the reviews for that agent's skills.diff --git a/tasks/monetization-feature/22-gifting-skills.md b/tasks/monetization-feature/22-gifting-skills.mdnew file mode 100644index 000000000..24c5ddd2b--- /dev/null+++ b/tasks/monetization-feature/22-gifting-skills.md@@ -0,0 +1,26 @@+---+status: not-started+---++# Prompt 22: Gifting Skills++**Status:** Not Started++## Objective+Allow a user to purchase a skill and gift it to another user.++## Explanation+Gifting can be a new acquisition channel. A user might buy a skill for a friend to try out.++## Instructions+- [ ] **Update the purchase flow UI.**+ - Add a "Buy as a Gift" checkbox.+ - If checked, an input field appears for the recipient's username or wallet address.+- [ ] **Modify the purchase API and logic.**+ - The purchase transaction is the same (the buyer pays).+ - However, when the purchase is confirmed, the entry in the `user_skill_access` table should be created for the *recipient*, not the buyer.+- [ ] **Send a notification to the recipient.**+ - After the purchase, send an on-site notification or an email to the recipient informing them that "User X has gifted you the skill Y!"+- [ ] **Update the purchase history.**+ - The buyer's history should indicate that the purchase was a gift and show who it was for.+ - The recipient should also see the gifted skill in their list of owned skills.diff --git a/tasks/monetization-feature/23-on-chain-royalties-for-skill-usage.md b/tasks/monetization-feature/23-on-chain-royalties-for-skill-usage.mdnew file mode 100644index 000000000..c60f11961--- /dev/null+++ b/tasks/monetization-feature/23-on-chain-royalties-for-skill-usage.md@@ -0,0 +1,24 @@+---+status: not-started+---++# Prompt 23: On-Chain Royalties for Skill Usage++**Status:** Not Started++## Objective+Explore a more advanced model where creators earn royalties *every time* their skill is used, not just when it's sold.++## Explanation+This moves towards a "pay-per-use" model, which might be more suitable for certain high-value AI skills. It requires every skill execution to be a micro-transaction.++## Instructions+- [ ] **This is a significant architectural change.** Instead of a one-time access check, every call to `/api/agent/invoke` for a paid skill will now be a transaction.+- [ ] **The `invoke` endpoint will now behave like a Solana Pay API:**+ - 1. It receives the skill execution request.+ - 2. It calculates the per-use price.+ - 3. It returns a transaction that both pays the creator and includes the instructions to execute the skill (this may require an on-chain program).+- [ ] **The frontend needs to be updated** to handle this new flow. Every paid skill use will now require a wallet signature.+- [ ] **Consider using Solana Actions** to simplify this. The "invoke" button could be a Blink (Solana Action URL), which wallets can render and execute natively.++**Note:** This is a complex, forward-looking feature. The initial focus should be on the "purchase access" model. This prompt is for planning the next stage of the platform's evolution.diff --git a/tasks/monetization-feature/24-creator-payout-system.md b/tasks/monetization-feature/24-creator-payout-system.mdnew file mode 100644index 000000000..fbb0a7a7b--- /dev/null+++ b/tasks/monetization-feature/24-creator-payout-system.md@@ -0,0 +1,30 @@+---+status: not-started+---++# Prompt 24: Creator Payout System++**Status:** Not Started++## Objective+Develop a system for creators to withdraw their earnings from the platform to their own wallet.++## Explanation+While sales are directly to the creator's wallet in our current model, a future model where the platform holds funds in escrow before paying out would require a withdrawal system. This prompt outlines that future state.++## Instructions+- [ ] **This assumes a model where funds are not sent directly to the creator on purchase.** Instead, they are sent to a platform-controlled wallet, and the creator's earnings are tracked as a balance in our database.+- [ ] **Create a `creator_balances` table.**+ - `creator_id`, `currency_mint`, `balance`.+- [ ] **Update the creator earnings dashboard.**+ - Show the current withdrawable balance.+ - Add a "Withdraw" button.+- [ ] **Create a withdrawal API endpoint.**+ - When a creator requests a withdrawal:+ - 1. Verify they have sufficient balance.+ - 2. Construct a transfer transaction from the platform's hot wallet to the creator's registered wallet.+ - 3. Process the transfer and update the creator's balance in the database.+ - 4. Log the withdrawal in a `payouts` table for history.+- [ ] **Implement security measures:**+ - 2FA for withdrawals.+ - Time-locks or manual approval for large amounts.diff --git a/tasks/monetization-feature/25-legal-and-tax-compliance.md b/tasks/monetization-feature/25-legal-and-tax-compliance.mdnew file mode 100644index 000000000..0eacba2b3--- /dev/null+++ b/tasks/monetization-feature/25-legal-and-tax-compliance.md@@ -0,0 +1,26 @@+---+status: not-started+---++# Prompt 25: Legal and Tax Compliance Features++**Status:** Not Started++## Objective+Integrate basic tools to help creators with tax compliance, such as generating end-of-year earnings reports.++## Explanation+As a platform facilitating payments, we have a responsibility to make it easier for our creators to handle their finances and legal obligations.++## Instructions+- [ ] **In the Creator Earnings Dashboard, add a feature to export transaction history.**+ - Allow exporting as a CSV file.+ - The CSV should include date, skill name, amount, currency, and transaction signature for each sale.+- [ ] **Allow creators to add their legal information.**+ - Create a form in the dashboard for creators to enter their legal name, address, and tax ID (optional, and should be encrypted).+- [ ] **Generate simple annual earnings summaries.**+ - Create an API endpoint that, for a given year, calculates the total income for a creator.+- [ ] **Display clear disclaimers.**+ - Include text on the earnings page reminding creators that they are responsible for their own taxes and should consult a professional.++**Note:** We are not a financial services company, so we should not offer tax advice. The goal is to provide tools that make the data more accessible for creators.diff --git a/tasks/monetization-feature/README.md b/tasks/monetization-feature/README.mdindex 73815c007..4915adfcc 100644--- a/tasks/monetization-feature/README.md+++ b/tasks/monetization-feature/README.md@@ -8,8 +8,8 @@ The status of each task is tracked in its frontmatter (`status: not-started | in| ID | Task | Status ||----|--------------------------------------------|-------------|-| 01 | Display Priced Skills in Marketplace | `not-started` |-| 02 | Create `agent_skill_prices` Table Schema | `not-started` |+| 01 | Display Priced Skills in Marketplace | `completed` |+| 02 | Create `agent_skill_prices` Table Schema | `completed` || 03 | Creator UI for Skill Pricing | `not-started` || 04 | Backend for Saving Skill Prices | `not-started` || 05 | Add "Purchase" Button to Marketplace UI | `not-started` |diff --git a/tasks/platform-ux/16-ux-implement-dark-mode.md b/tasks/platform-ux/16-ux-implement-dark-mode.mdnew file mode 100644index 000000000..0e3d92b3a--- /dev/null+++ b/tasks/platform-ux/16-ux-implement-dark-mode.md@@ -0,0 +1,76 @@+---+status: not-started+---+# Prompt 16: Implement Dark Mode++**Status:** Not Started++## Objective+Implement a site-wide dark mode theme to improve user comfort in low-light environments and provide a modern look and feel.++## Explanation+Dark mode is a popular user preference. We will implement it using CSS variables for easy toggling and use `localStorage` to remember the user's choice.++## Instructions+1. **Define CSS Color Variables:**+ * In your main stylesheet (`style.css`), define two sets of color variables within the `:root` and a `[data-theme='dark']` selector.+ * Use these variables throughout all your CSS files.+2. **Create a Theme Toggler:**+ * Add a button or toggle switch to your site's header or footer.+ * When clicked, this button will toggle the `data-theme` attribute on the `<html>` or `<body>` element.+3. **Use JavaScript to Manage State:**+ * Write a script that:+ * On page load, checks `localStorage` for a saved theme preference.+ * Also checks the user's OS preference via `prefers-color-scheme` media query as a default.+ * Applies the correct `data-theme` attribute.+ * Updates `localStorage` whenever the user clicks the theme toggler.++## Code Example (CSS)+```css+/* style.css */+:root {+ --background-color: #ffffff;+ --text-color: #333333;+ --primary-color: #3d8bfd;+ --card-bg-color: #f9f9f9;+}++[data-theme='dark'] {+ --background-color: #121212;+ --text-color: #f5f5f5;+ --primary-color: #5a9fff;+ --card-bg-color: #1e1e1e;+}++body {+ background-color: var(--background-color);+ color: var(--text-color);+}++.agent-card {+ background-color: var(--card-bg-color);+}+```++## Code Example (JavaScript)+```javascript+// theme-switcher.js+const themeToggle = document.getElementById('theme-toggle');+const currentTheme = localStorage.getItem('theme');++function setTheme(theme) {+ document.documentElement.setAttribute('data-theme', theme);+ localStorage.setItem('theme', theme);+}++if (currentTheme) {+ setTheme(currentTheme);+} else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {+ setTheme('dark');+}++themeToggle.addEventListener('click', () => {+ const newTheme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';+ setTheme(newTheme);+});+```