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 Solana transaction construction and payment flow
nirholas990e8872e97f
diff --git a/agent-protocol-sdk/package.json b/agent-protocol-sdk/package.jsonnew file mode 100644index 000000000..48bc5fd70--- /dev/null+++ b/agent-protocol-sdk/package.json@@ -0,0 +1,17 @@+{+ "name": "@3d-agent/agent-protocol-sdk",+ "version": "0.1.0",+ "description": "SDK for the on-chain agent-to-agent invocation protocol.",+ "main": "dist/index.js",+ "types": "dist/index.d.ts",+ "scripts": {+ "build": "tsc"+ },+ "dependencies": {+ "@coral-xyz/anchor": "^0.31.1",+ "@solana/web3.js": "^1.98.4"+ },+ "devDependencies": {+ "typescript": "^5.0.0"+ }+}diff --git a/agent-protocol-sdk/src/idl.ts b/agent-protocol-sdk/src/idl.tsnew file mode 100644index 000000000..85d7e1701--- /dev/null+++ b/agent-protocol-sdk/src/idl.ts@@ -0,0 +1,89 @@+// This is a placeholder IDL. In a real environment, this file would be+// generated by running `anchor build` in the `contracts/agent-invocation` directory.++export type AgentInvocation = {+ "version": "0.1.0",+ "name": "agent_invocation",+ "instructions": [+ {+ "name": "invokeSkill",+ "accounts": [+ {+ "name": "invokerAgent",+ "isMut": false,+ "isSigner": false+ },+ {+ "name": "targetAgent",+ "isMut": false,+ "isSigner": false+ },+ {+ "name": "invokerAuthority",+ "isMut": true,+ "isSigner": true+ },+ {+ "name": "systemProgram",+ "isMut": false,+ "isSigner": false+ }+ ],+ "args": [+ {+ "name": "skillName",+ "type": "string"+ },+ {+ "name": "parameters",+ "type": "string"+ }+ ]+ }+ ]+};++export const IDL: AgentInvocation = {+ "version": "0.1.0",+ "name": "agent_invocation",+ "instructions": [+ {+ "name": "invokeSkill",+ "accounts": [+ {+ "name": "invokerAgent",+ "isMut": false,+ "isSigner": false,+ "docs": ["CHECK: This is the agent performing the invocation"]+ },+ {+ "name": "targetAgent",+ "isMut": false,+ "isSigner": false,+ "docs": ["CHECK: This is the agent whose skill is being invoked"]+ },+ {+ "name": "invokerAuthority",+ "isMut": true,+ "isSigner": true,+ "docs": ["CHECK: The user or authority wallet for the invoker"]+ },+ {+ "name": "systemProgram",+ "isMut": false,+ "isSigner": false+ }+ ],+ "args": [+ {+ "name": "skillName",+ "type": "string"+ },+ {+ "name": "parameters",+ "type": "string"+ }+ ]+ }+ ]+};diff --git a/agent-protocol-sdk/src/index.ts b/agent-protocol-sdk/src/index.tsnew file mode 100644index 000000000..f9b706b7e--- /dev/null+++ b/agent-protocol-sdk/src/index.ts@@ -0,0 +1,51 @@+import {+ Connection,+ PublicKey,+ SystemProgram,+ Transaction,+ sendAndConfirmTransaction,+ Keypair+} from '@solana/web3.js';+import { Program, AnchorProvider, web3 } from '@coral-xyz/anchor';+import { IDL, AgentInvocation } from './idl'; // Assumes IDL is generated and placed here++const PROGRAM_ID = new PublicKey("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");++/**+ * Invokes a skill on a target agent.+ *+ * @param connection The Solana connection object.+ * @param invokerAuthority The keypair of the wallet authorized to invoke the skill.+ * @param invokerAgent The public key of the agent performing the invocation.+ * @param targetAgent The public key of the agent whose skill is being invoked.+ * @param skillName The name of the skill to invoke.+ * @param parameters A JSON string of parameters for the skill.+ * @returns The transaction signature.+ */+export async function invokeSkill(+ connection: Connection,+ invokerAuthority: Keypair,+ invokerAgent: PublicKey,+ targetAgent: PublicKey,+ skillName: string,+ parameters: string+): Promise<string> {++ const provider = new AnchorProvider(connection, { signTransaction: invokerAuthority.signTransaction, signAllTransactions: invokerAuthority.signAllTransactions, publicKey: invokerAuthority.publicKey }, {});+ const program = new Program<AgentInvocation>(IDL, PROGRAM_ID, provider);++ const tx = await program.methods+ .invokeSkill(skillName, parameters)+ .accounts({+ invokerAgent,+ targetAgent,+ invokerAuthority: invokerAuthority.publicKey,+ systemProgram: SystemProgram.programId,+ })+ .transaction();++ return await sendAndConfirmTransaction(connection, tx, [invokerAuthority]);+}++// NOTE: We also need the IDL file for the contract. This is typically generated+// by Anchor. For now, I will create a placeholder.diff --git a/agent-protocol-sdk/tsconfig.json b/agent-protocol-sdk/tsconfig.jsonnew file mode 100644index 000000000..78c772027--- /dev/null+++ b/agent-protocol-sdk/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "es2020",+ "module": "commonjs",+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": true+ },+ "include": ["src/**/*"]+}diff --git a/contracts/agent-invocation/src/lib.rs b/contracts/agent-invocation/src/lib.rsnew file mode 100644index 000000000..c46ceffb6--- /dev/null+++ b/contracts/agent-invocation/src/lib.rs@@ -0,0 +1,35 @@+use anchor_lang::prelude::*;++declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");++#[program]+pub mod agent_invocation {+ use super::*;+ pub fn invoke_skill(ctx: Context<InvokeSkill>, skill_name: String, parameters: String) -> Result<()> {+ msg!("Agent {} invoked skill '{}' on agent {} with parameters: {}",+ ctx.accounts.invoker_agent.key(),+ skill_name,+ ctx.accounts.target_agent.key(),+ parameters);++ // In a full implementation, this would:+ // 1. Verify the invoker has the right to call the skill (e.g., holds a specific NFT).+ // 2. Look up the skill price from on-chain data.+ // 3. Transfer the required payment from the invoker's wallet to the target's wallet.+ // 4. Emit an event with the invocation details for off-chain services to process.++ Ok(())+ }+}++#[derive(Accounts)]+pub struct InvokeSkill<'info> {+ /// CHECK: This is the agent performing the invocation+ pub invoker_agent: AccountInfo<'info>,+ /// CHECK: This is the agent whose skill is being invoked+ pub target_agent: AccountInfo<'info>,+ /// CHECK: The user or authority wallet for the invoker+ #[account(signer)]+ pub invoker_authority: AccountInfo<'info>,+ pub system_program: Program<'info, System>,+}diff --git a/docs/02-backend-create-skill-pricing-table.md b/docs/02-backend-create-skill-pricing-table.mdnew file mode 100644index 000000000..b019e208e--- /dev/null+++ b/docs/02-backend-create-skill-pricing-table.md@@ -0,0 +1,47 @@+# Prompt 2: Backend - Create Skill Pricing Table++## Objective+Create the necessary database table to store the prices of agent skills. This is a foundational step for the monetization feature.++## Explanation+To make skills purchasable, we need a dedicated table in our database (`agent_skill_prices`) that links a skill to a price, currency, and the creator who sets the price. This structure will allow us to easily query for a skill's price and manage payments.++## Instructions+1. **Define the Schema:**+ * Create a new SQL migration file.+ * Define the schema for the `agent_skill_prices` table. It should include the following fields:+ * `id`: Primary key (e.g., UUID).+ * `skill_id`: Foreign key referencing the `skills` table.+ * `creator_id`: Foreign key referencing the `users` table (the user who created the skill and will receive payment).+ * `amount`: The price of the skill in the smallest unit of the currency (e.g., lamports for SOL, or 10^-6 for USDC). Use a `BIGINT` or `NUMERIC` to handle large numbers without precision loss.+ * `currency_mint`: The public key of the SPL token used for payment (e.g., USDC's mint address). Stored as a string.+ * `created_at` / `updated_at`: Timestamps.++2. **Apply the Migration:**+ * Run the migration to create the table in your development database.++## Code Example (SQL Migration)++```sql+CREATE TABLE agent_skill_prices (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ skill_id UUID NOT NULL REFERENCES skills(id) ON DELETE CASCADE,+ creator_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ amount BIGINT NOT NULL,+ currency_mint VARCHAR(44) NOT NULL, -- Solana public key length+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ -- A skill should only have one price set by its creator+ UNIQUE (skill_id, creator_id)+);++-- Create an index for efficient price lookups by skill+CREATE INDEX idx_agent_skill_prices_on_skill_id ON agent_skill_prices(skill_id);++-- Optional: Trigger to auto-update updated_at timestamp+CREATE TRIGGER set_timestamp+BEFORE UPDATE ON agent_skill_prices+FOR EACH ROW+EXECUTE PROCEDURE trigger_set_timestamp();+```diff --git a/docs/03-backend-seed-skill-pricing-data.md b/docs/03-backend-seed-skill-pricing-data.mdnew file mode 100644index 000000000..396c54138--- /dev/null+++ b/docs/03-backend-seed-skill-pricing-data.md@@ -0,0 +1,77 @@+# Prompt 3: Backend - Seed Skill Pricing Data++## Objective+Populate the database with sample data for free and paid skills to enable frontend development and testing.++## Explanation+With the `agent_skill_prices` table created, we now need some data to work with. A seed script will allow us to consistently create a set of test skills with and without prices. This is crucial for developers working on the UI to be able to see and test all variations of the design.++## Instructions+1. **Create a Seed Script:**+ * Create a new script in your `scripts/` directory (e.g., `seed-skills.mjs`).+ * The script should connect to your database.+ * It should first create a sample creator user and a few sample skills.+ * Then, for some of those skills, it should insert corresponding entries into the `agent_skill_prices` table.+ * Include at least one free skill (no entry in the prices table) and two paid skills with different prices.++2. **Run the Script:**+ * Execute the script to populate your local database.+ * Make sure to document how to run the script in your project's `README.md`.++## Code Example (Node.js Seeding Script)++```javascript+// In scripts/seed-skills.mjs+import { db } from '../api/_lib/db.js'; // Adjust path to your db connection++async function main() {+ console.log('Seeding database...');++ // 1. Create a sample creator+ const { rows: [creator] } = await db.query(+ `INSERT INTO users (username, email) VALUES ($1, $2)+ ON CONFLICT (email) DO UPDATE SET username = $1 RETURNING id`,+ ['skill_creator_1', '[email protected]']+ );+ console.log(`Created/found creator user: ${creator.id}`);++ // 2. Create some skills+ const { rows: [skill1] } = await db.query(+ `INSERT INTO skills (name, description, creator_id) VALUES ($1, $2, $3) RETURNING id`,+ ['Advanced Market Analysis', 'Provides deep insights into token velocity.', creator.id]+ );+ const { rows: [skill2] } = await db.query(+ `INSERT INTO skills (name, description, creator_id) VALUES ($1, $2, $3) RETURNING id`,+ ['Rug-Pull Detection', 'Flags high-risk tokens using on-chain data.', creator.id]+ );+ const { rows: [skill3] } = await db.query(+ `INSERT INTO skills (name, description, creator_id) VALUES ($1, $2, $3) RETURNING id`,+ ['Wave', 'A simple social emote.', creator.id] // This one will be free+ );+ console.log('Created sample skills.');++ // 3. Set prices for paid skills (USDC mint on Solana Mainnet)+ const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a';++ await db.query(+ `INSERT INTO agent_skill_prices (skill_id, creator_id, amount, currency_mint)+ VALUES ($1, $2, $3, $4) ON CONFLICT (skill_id, creator_id) DO NOTHING`,+ [skill1.id, creator.id, 2_000_000, USDC_MINT] // 2 USDC+ );++ await db.query(+ `INSERT INTO agent_skill_prices (skill_id, creator_id, amount, currency_mint)+ VALUES ($1, $2, $3, $4) ON CONFLICT (skill_id, creator_id) DO NOTHING`,+ [skill2.id, creator.id, 5_000_000, USDC_MINT] // 5 USDC+ );+ console.log('Set prices for paid skills.');++ console.log('Seeding complete.');+ await db.end();+}++main().catch(err => {+ console.error('Seeding failed:', err);+ process.exit(1);+});+```diff --git a/docs/04-frontend-create-pricebadge-component.md b/docs/04-frontend-create-pricebadge-component.mdnew file mode 100644index 000000000..3b1cb187b--- /dev/null+++ b/docs/04-frontend-create-pricebadge-component.md@@ -0,0 +1,71 @@+# Prompt 4: Frontend - Create Reusable PriceBadge Component++## Objective+Develop a reusable UI component to display skill prices consistently across the application.++## Explanation+To maintain a consistent user experience, we should encapsulate the logic for displaying skill prices into a single, reusable component. This `PriceBadge` component will handle the formatting of the price and the visual distinction between "Free" and paid skills. Creating this component now will save time and prevent code duplication as we build more monetization features.++## Instructions+1. **Create the Component File:**+ * Create a new file for your component, for example, `src/components/PriceBadge.js`.+ * This component can be a simple function that returns an HTML string or a more complex component if you are using a framework like React or Svelte.++2. **Implement the Component Logic:**+ * The component should accept the price information (e.g., `amount` and `currency`) as props.+ * If the price is missing or zero, it should render a "Free" badge.+ * If a price is provided, it should format the amount (e.g., convert from lamports) and display it with the currency.+ * It should apply the appropriate CSS classes (`price-free` or `price-paid`) based on the price.++3. **Refactor `marketplace.js`:**+ * Import and use the new `PriceBadge` component in the `renderDetail` function in `src/marketplace.js` to replace the inline badge creation logic.++## Code Example (`src/components/PriceBadge.js`)++```javascript+// A simple functional component that returns an HTML string.++// Mapping of mint addresses to human-readable currency symbols.+const CURRENCY_SYMBOLS = {+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a': 'USDC',+ 'So11111111111111111111111111111111111111112': 'SOL',+};++// Divisors to convert from smallest unit to standard unit.+const CURRENCY_DIVISORS = {+ 'USDC': 1e6,+ 'SOL': 1e9,+};++export function PriceBadge(price) {+ if (!price || !price.amount) {+ return `<span class="price-badge price-free">Free</span>`;+ }++ const symbol = CURRENCY_SYMBOLS[price.currency_mint] || '???';+ const divisor = CURRENCY_DIVISORS[symbol] || 1;+ const formattedAmount = (price.amount / divisor).toFixed(2);++ return `+ <span class="price-badge price-paid">+ ${formattedAmount} ${symbol}+ </span>+ `;+}+```++### Refactored Usage in `src/marketplace.js`++```javascript+import { PriceBadge } from './components/PriceBadge.js'; // Adjust path++// ... 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];+ return `<span class="skill-entry">${escapeHtml(name)}${PriceBadge(price)}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+```diff --git a/docs/05-frontend-handle-price-loading-states.md b/docs/05-frontend-handle-price-loading-states.mdnew file mode 100644index 000000000..4b92bd523--- /dev/null+++ b/docs/05-frontend-handle-price-loading-states.md@@ -0,0 +1,75 @@+# Prompt 5: Frontend - Handle Price Loading States++## Objective+Improve the user experience on the agent detail page by showing a loading state while skill prices are being fetched.++## Explanation+The skill prices are fetched from the database and may not be available at the exact moment the agent details are first rendered. To prevent a jarring UI update where prices suddenly appear, we should display a placeholder or loading indicator. This provides a smoother experience and gives users feedback that content is being loaded.++## Instructions+1. **Modify the API Response:**+ * Ensure the `/api/marketplace/agents/:id` endpoint returns the agent data immediately, even if the `skill_prices` query is still running. The `skill_prices` field can be initially `null` or an empty object.++2. **Update the Frontend Rendering Logic:**+ * In `src/marketplace.js` within the `renderDetail` function, add a check for the `skill_prices` field.+ * If `skill_prices` is not yet present, render a loading state for the skill badges.+ * Once the full agent data with prices is fetched, re-render the skill list with the correct prices. This can be achieved by calling `renderDetail` again or by having a dedicated function to update just the skill badges.++## Code Example (UI Loading State in `src/marketplace.js`)++```javascript+// A simple loading badge component/function+function LoadingBadge() {+ return `<span class="price-badge price-loading">...</span>`;+}++function renderSkills(skillsArr, skillPrices) {+ const skillsEl = $('d-skills');+ if (!skillsEl) return;++ // Check for null to indicate loading, vs. {} for an agent with no priced skills+ const isLoading = skillPrices === null;++ skillsEl.innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = isLoading ? null : (skillPrices || {})[name];+ const badge = isLoading ? LoadingBadge() : PriceBadge(price);+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+}++// In the main part of renderDetail+async function renderDetail(id) {+ // ...+ // Initial render with loading state+ renderSkills(agent.skills, null);++ // Fetch full data+ const agentWithPrices = await fetchAgentWithPrices(id); // Your data fetching logic+ // Re-render with prices+ renderSkills(agentWithPrices.skills, agentWithPrices.skill_prices);+}+```++### CSS for Loading State++Add to `/public/marketplace.css`:++```css+.price-loading {+ color: #9ca3af;+ background-color: #374151;+ animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;+}++@keyframes pulse {+ 0%, 100% {+ opacity: 1;+ }+ 50% {+ opacity: .5;+ }+}+```diff --git a/docs/06-uiux-design-purchase-modal.md b/docs/06-uiux-design-purchase-modal.mdnew file mode 100644index 000000000..f6ec5b04e--- /dev/null+++ b/docs/06-uiux-design-purchase-modal.md@@ -0,0 +1,60 @@+# Prompt 6: UI/UX - Design the Skill Purchase Modal++## Objective+Design a clear, user-friendly modal for purchasing skills, which will serve as the blueprint for frontend implementation.++## Explanation+A well-designed purchase modal is critical for conversion. It needs to be simple, trustworthy, and provide all necessary information at a glance. Before writing code, we should define the components and layout of this modal. This design task ensures that the subsequent implementation is fast and aligned with the user's needs.++## Instructions+1. **Sketch the Modal Layout:**+ * Create a wireframe or a simple mockup of the purchase modal. This can be done with a tool like Figma, or even a drawing on paper.+ * The modal should be triggered by clicking on a paid skill.++2. **Define Modal Components:**+ * The modal must include:+ * **Header:** "Purchase Skill: [Skill Name]"+ * **Skill Description:** A brief explanation of what the skill does.+ * **Price Display:** The price in a clear format (e.g., "5.00 USDC").+ * **Creator Info:** The name or avatar of the skill creator.+ * **Call to Action (CTA):** A primary button like "Purchase with Solana Pay" or "Buy Now".+ * **Balance Check (Optional but Recommended):** Display the user's current USDC balance.+ * **Close Button:** An 'X' in the corner to dismiss the modal.+ * **Status Area:** A space to show transaction progress (e.g., "Generating QR Code...", "Awaiting Confirmation...").++3. **Document the User Flow:**+ * Describe the steps a user takes:+ 1. User clicks a paid skill.+ 2. The purchase modal appears.+ 3. User clicks "Purchase".+ 4. A Solana Pay QR code is displayed.+ 5. User scans with their wallet and approves.+ 6. The modal shows a confirmation message.+ 7. The modal closes, and the UI updates to show the skill as "Owned".++## Design Mockup Example++(This can be a simple text-based layout or a link to a visual design)++```++-------------------------------------------------++| Purchase Skill: Rug-Pull Detection [X] |++-------------------------------------------------++| |+| Flags high-risk tokens using on-chain data to |+| help you avoid potential scams. |+| |+| Created by: @skill_creator_1 |+| |+| ----------------------------------------------- |+| |+| Price: 5.00 USDC |+| Your Balance: 23.45 USDC |+| |++-------------------------------------------------++| [ Purchase with Solana Pay ] |+| |+| Status: Waiting for user action... |++-------------------------------------------------++```+This design document will guide the implementation in the next prompt.diff --git a/docs/07-frontend-implement-purchase-modal-ui.md b/docs/07-frontend-implement-purchase-modal-ui.mdnew file mode 100644index 000000000..60a723b6b--- /dev/null+++ b/docs/07-frontend-implement-purchase-modal-ui.md@@ -0,0 +1,88 @@+# Prompt 7: Frontend - Implement Skill Purchase Modal UI++## Objective+Build the HTML and CSS for the skill purchase modal based on the design defined in the previous prompt.++## Explanation+With the UI/UX design for the purchase modal complete, we can now translate it into a functional frontend component. This task focuses on building the structure and styling of the modal, without yet wiring it up to the Solana Pay logic. This separation of concerns allows us to perfect the visual presentation first.++## Instructions+1. **Add Modal HTML to `marketplace.html`:**+ * Add the HTML structure for a modal to the bottom of your `marketplace.html` file. It should be hidden by default (e.g., with `display: none`).+ * Use clear and semantic element IDs for the dynamic parts of the modal (e.g., `purchase-modal-skill-name`, `purchase-modal-price`, `purchase-modal-cta`).++2. **Create CSS for the Modal:**+ * In `/public/marketplace.css`, add styles for the modal container, backdrop, header, content, and buttons.+ * Ensure the modal is centered, has a professional appearance, and is responsive to different screen sizes.++3. **Add JavaScript to Show/Hide the Modal:**+ * In `src/marketplace.js`, add a function to populate and show the modal when a paid skill is clicked.+ * Add event listeners for the close button and backdrop to hide the modal.++## Code Example (HTML in `marketplace.html`)++```html+<!-- Add at the end of the body -->+<div id="purchase-modal-backdrop" class="modal-backdrop" style="display: none;">+ <div id="purchase-modal" class="modal">+ <div class="modal-header">+ <h2 id="purchase-modal-title">Purchase Skill</h2>+ <button id="purchase-modal-close" class="modal-close-btn">×</button>+ </div>+ <div class="modal-body">+ <p id="purchase-modal-description"></p>+ <div class="creator-info">Created by: <span id="purchase-modal-creator"></span></div>+ <hr />+ <div class="price-details">+ <span>Price:</span>+ <strong id="purchase-modal-price"></strong>+ </div>+ <div class="status-area" id="purchase-modal-status"></div>+ </div>+ <div class="modal-footer">+ <button id="purchase-modal-cta" class="cta-button">Purchase</button>+ </div>+ </div>+</div>+```++## Code Example (JavaScript in `src/marketplace.js`)++```javascript+// Function to open the modal+function showPurchaseModal(skillName, price, description, creator) {+ $('purchase-modal-title').textContent = `Purchase Skill: ${skillName}`;+ $('purchase-modal-description').textContent = description;+ $('purchase-modal-creator').textContent = creator;+ $('purchase-modal-price').textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;++ // Store data for the purchase action+ const cta = $('purchase-modal-cta');+ cta.dataset.skillName = skillName;+ cta.dataset.amount = price.amount;+ cta.dataset.mint = price.currency_mint;++ $('purchase-modal-backdrop').style.display = 'flex';+}++// Add event listeners for showing/hiding+document.addEventListener('DOMContentLoaded', () => {+ // Hide modal logic+ const backdrop = $('purchase-modal-backdrop');+ $('purchase-modal-close').addEventListener('click', () => backdrop.style.display = 'none');+ backdrop.addEventListener('click', (e) => {+ if (e.target === backdrop) {+ backdrop.style.display = 'none';+ }+ });++ // Show modal logic (example, needs to be integrated with skill list rendering)+ $('d-skills').addEventListener('click', (e) => {+ const skillEntry = e.target.closest('.skill-entry.paid'); // Add .paid class to priced skills+ if (skillEntry) {+ // Fetch skill details from data attributes or an in-memory object+ // showPurchaseModal(skillName, price, ...);+ }+ });+});+```diff --git a/docs/monetization-prompts/02-add-purchase-button.md b/docs/monetization-prompts/02-add-purchase-button.mdnew file mode 100644index 000000000..f8532c255--- /dev/null+++ b/docs/monetization-prompts/02-add-purchase-button.md@@ -0,0 +1,101 @@+# Prompt 2: Add Purchase Button for Priced Skills++**Status:** - [ ] Not Started++## Objective+On the agent detail page, display a "Purchase" button next to paid skills and an "Owned" or "Equipped" label for skills the user has already purchased.++## Explanation+Building on the previous step, now that prices are displayed, the next logical step is to provide a call to action for users to buy the skill. This prompt focuses on updating the UI to include this button and reflect the user's ownership status of a skill.++## Instructions+1. **Fetch User's Purchased Skills:**+ * You'll need an API endpoint to get the skills a user has purchased for a specific agent. Let's assume a new endpoint `/api/users/me/agent-skills/:agentId`.+ * This endpoint should return a list of skill names the user owns for that agent.++2. **Update Frontend Data Fetching:**+ * In `src/marketplace.js`, within `renderDetail`, after fetching the agent details, make another API call to fetch the user's purchased skills for the current agent.++3. **Modify UI Rendering Logic:**+ * In the `renderDetail` function, when looping through the agent's skills, you now have access to `skillPrices` and the `purchasedSkills`.+ * The logic for rendering each skill entry should be updated:+ * If the skill is free (no price in `skillPrices`), show the "Free" badge.+ * If the skill is paid and the user has purchased it (skill name is in `purchasedSkills`), show an "Owned" badge/label.+ * If the skill is paid and the user has *not* purchased it, show the price and a "Purchase" button.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// Inside renderDetail function, after fetching agent and purchased skills++const skillPrices = a.skill_prices || {};+const purchasedSkills = userSkills || []; // from new API call++$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ const isOwned = purchasedSkills.includes(name);++ let badgeOrButton = '';+ if (isOwned) {+ badgeOrButton = `<span class="skill-status-badge skill-owned">Owned</span>`;+ } else if (price) {+ const priceInUSDC = (price.amount / 1e6).toFixed(2);+ badgeOrButton = `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}">Purchase for ${priceInUSDC} USDC</button>`;+ } else {+ badgeOrButton = `<span class="price-badge price-free">Free</span>`;+ }++ return `<div class="skill-entry">+ <span class="skill-name">${escapeHtml(name)}</span>+ ${badgeOrButton}+ </div>`;+ }).join('')+ : '<div>This Agent has no skills defined.</div>';++```++## CSS Example++Add these styles to `/marketplace.css` for the new elements.++```css+.skill-entry {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 8px 0;+ border-bottom: 1px solid var(--border);+}++.purchase-btn {+ background-color: var(--accent);+ color: white;+ border: none;+ padding: 6px 12px;+ font-size: 12px;+ font-weight: 600;+ border-radius: 6px;+ cursor: pointer;+ transition: background-color 0.2s;+}++.purchase-btn:hover {+ background-color: #5a4ccc; /* A slightly darker shade of accent */+}++.skill-status-badge {+ display: inline-block;+ padding: 2px 6px;+ font-size: 10px;+ font-weight: 600;+ border-radius: 4px;+ vertical-align: middle;+}++.skill-owned {+ color: #a7f3d0;+ background-color: rgba(52, 211, 153, 0.1);+}+```diff --git a/docs/monetization-prompts/03-create-purchase-modal.md b/docs/monetization-prompts/03-create-purchase-modal.mdnew file mode 100644index 000000000..20e0d8078--- /dev/null+++ b/docs/monetization-prompts/03-create-purchase-modal.md@@ -0,0 +1,128 @@+# Prompt 3: Create Purchase Confirmation Modal++**Status:** - [ ] Not Started++## Objective+Implement a modal dialog that appears when a user clicks the "Purchase" button for a skill, asking for confirmation before proceeding with the transaction.++## Explanation+A confirmation step is crucial for any purchasing flow to prevent accidental purchases. This modal will summarize the transaction (skill name, price) and require an explicit user action to continue. It will serve as the container for wallet interactions in subsequent steps.++## Instructions+1. **Create Modal HTML Structure:**+ * Add the HTML for a modal to `marketplace.html`. It should be hidden by default.+ * The modal should contain elements for the skill name, price, a "Confirm Purchase" button, and a close button.++2. **Add JavaScript Logic to Control the Modal:**+ * In `src/marketplace.js`, add event listeners for the "Purchase" buttons. Since these buttons are dynamically generated, use event delegation on a parent element (e.g., `$('d-skills')`).+ * When a purchase button is clicked, populate the modal with the correct skill name and price.+ * Show the modal.+ * Implement the logic for the close button and for closing the modal by clicking the backdrop.++3. **Style the Modal:**+ * Add CSS to `/marketplace.css` to style the modal, its backdrop, and its contents for a clean, user-friendly appearance.++## Code Example (HTML in `marketplace.html`)++```html+<!-- Add this somewhere in the body of marketplace.html -->+<div id="purchase-modal-backdrop" class="modal-backdrop" style="display: none;">+ <div id="purchase-modal" class="modal">+ <div class="modal-header">+ <h2>Confirm Purchase</h2>+ <button id="modal-close-btn" class="modal-close-btn">×</button>+ </div>+ <div class="modal-body">+ <p>You are about to purchase the skill:</p>+ <h3 id="modal-skill-name"></h3>+ <p>Price:</p>+ <h3 id="modal-skill-price"></h3>+ </div>+ <div class="modal-footer">+ <button id="modal-confirm-purchase-btn" class="purchase-btn">Confirm Purchase</button>+ </div>+ </div>+</div>+```++## Code Example (JavaScript in `src/marketplace.js`)++```javascript+// At the top of the script+const purchaseModal = $('purchase-modal-backdrop');+const modalSkillName = $('modal-skill-name');+const modalSkillPrice = $('modal-skill-price');++// Event listener using delegation+$('d-skills').addEventListener('click', (e) => {+ if (e.target.classList.contains('purchase-btn')) {+ const skillName = e.target.dataset.skillName;+ const agent = window.currentAgent; // Assuming current agent data is available+ const priceInfo = agent.skill_prices[skillName];++ if (priceInfo) {+ modalSkillName.textContent = skillName;+ modalSkillPrice.textContent = `${(priceInfo.amount / 1e6).toFixed(2)} USDC`;+ purchaseModal.style.display = 'flex';+ }+ }+});++// Close modal logic+$('modal-close-btn').addEventListener('click', () => {+ purchaseModal.style.display = 'none';+});+purchaseModal.addEventListener('click', (e) => {+ if (e.target === purchaseModal) {+ purchaseModal.style.display = 'none';+ }+});+```++## CSS Example (`/marketplace.css`)++```css+.modal-backdrop {+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ background-color: rgba(0, 0, 0, 0.6);+ display: flex;+ justify-content: center;+ align-items: center;+ z-index: 1000;+}++.modal {+ background-color: var(--panel);+ padding: 24px;+ border-radius: 12px;+ border: 1px solid var(--border);+ width: 90%;+ max-width: 400px;+}++.modal-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ border-bottom: 1px solid var(--border);+ padding-bottom: 16px;+ margin-bottom: 16px;+}++.modal-header h2 {+ margin: 0;+ font-size: 18px;+}++.modal-close-btn {+ background: none;+ border: none;+ font-size: 24px;+ color: var(--muted);+ cursor: pointer;+}+```diff --git a/docs/monetization-prompts/04-connect-wallet-integration.md b/docs/monetization-prompts/04-connect-wallet-integration.mdnew file mode 100644index 000000000..a1301ffb9--- /dev/null+++ b/docs/monetization-prompts/04-connect-wallet-integration.md@@ -0,0 +1,70 @@+# Prompt 4: Connect Wallet Integration++**Status:** - [ ] Not Started++## Objective+Integrate a "Connect Wallet" feature into the purchase modal, allowing users to connect their Solana wallet before making a purchase.++## Explanation+To purchase skills, users must have a connected Solana wallet. This prompt focuses on adding the necessary UI and logic to handle wallet connection directly within the purchase flow, ensuring a seamless user experience. We will use `@solana/wallet-adapter-react` and related libraries, which might already be in the project.++## Instructions+1. **Add a Wallet Connection Button:**+ * In the purchase modal's HTML, add a "Connect Wallet" button. This button should be shown if the user's wallet is not connected, and the "Confirm Purchase" button should be hidden.++2. **Implement Wallet Connection Logic:**+ * Use a wallet adapter library (like `@solana/wallet-adapter-react` or equivalent for vanilla JS) to handle the wallet connection logic.+ * When the "Connect Wallet" button is clicked, trigger the wallet adapter's connection modal.+ * Once the wallet is connected, update the UI of the purchase modal to hide the "Connect Wallet" button and show the "Confirm Purchase" button.++3. **Manage Wallet State:**+ * Maintain a global state that tracks the user's wallet connection status and public key.+ * The `renderDetail` function and the purchase modal logic should react to changes in this wallet state.++## Code Example (JavaScript in `src/marketplace.js`)++```javascript+// This example assumes a wallet adapter setup that exposes a `wallet` object+// and `connectWallet` function.++// In the event listener for the purchase button+$('d-skills').addEventListener('click', (e) => {+ if (e.target.classList.contains('purchase-btn')) {+ // ... (previous modal logic)++ // New logic to handle wallet connection+ if (wallet.connected) {+ $('modal-connect-wallet-btn').style.display = 'none';+ $('modal-confirm-purchase-btn').style.display = 'block';+ } else {+ $('modal-connect-wallet-btn').style.display = 'block';+ $('modal-confirm-purchase-btn').style.display = 'none';+ }++ purchaseModal.style.display = 'flex';+ }+});++// Event listener for the new connect wallet button+$('modal-connect-wallet-btn').addEventListener('click', async () => {+ try {+ await connectWallet();+ // After successful connection, update the modal UI+ $('modal-connect-wallet-btn').style.display = 'none';+ $('modal-confirm-purchase-btn').style.display = 'block';+ } catch (error) {+ console.error('Failed to connect wallet:', error);+ // Handle connection error (e.g., show a toast message)+ }+});+```++## Code Example (HTML in `marketplace.html`)++```html+<!-- Update the modal footer -->+<div class="modal-footer">+ <button id="modal-connect-wallet-btn" class="purchase-btn" style="display: none;">Connect Wallet</button>+ <button id="modal-confirm-purchase-btn" class="purchase-btn" style="display: none;">Confirm Purchase</button>+</div>+```diff --git a/docs/monetization/01-db-schema-for-skill-pricing.md b/docs/monetization/01-db-schema-for-skill-pricing.mdnew file mode 100644index 000000000..e27ac5659--- /dev/null+++ b/docs/monetization/01-db-schema-for-skill-pricing.md@@ -0,0 +1,84 @@+---+status: not-started+completed_at: null+---+# Prompt 1: Database Schema for Skill Monetization++## Objective+Design and create the necessary database tables to support pricing skills and tracking user purchases.++## Explanation+To monetize agent skills, we first need a robust database structure. This involves creating two primary tables: one to store the prices set by creators for their agent skills (`agent_skill_prices`) and another to record which users have purchased which skills (`user_skill_purchases`). This foundational schema is critical for all subsequent monetization features.++## Instructions+1. **Design the Schema:**+ * **`agent_skill_prices` table:**+ * `agent_id`: Foreign key to the `agents` table.+ * `skill_name`: The name of the skill being priced (e.g., "translate", "summarize-document").+ * `amount`: The price of the skill in the smallest unit of the currency (e.g., lamports for SOL, or 10^-6 for USDC). Use a `bigint` for precision.+ * `currency_mint`: The mint address of the SPL token for the price (e.g., `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6f` for USDC).+ * `created_at`, `updated_at`: Standard timestamps.+ * Define a composite primary key on `(agent_id, skill_name)`.+ * **`user_skill_purchases` table:**+ * `user_id`: Foreign key to the `users` table.+ * `agent_id`: Foreign key to the `agents` table.+ * `skill_name`: The name of the purchased skill.+ * `purchase_tx_signature`: The transaction signature from the on-chain payment.+ * `amount_paid`, `currency_mint`: The actual price paid.+ * `purchased_at`: Timestamp of the purchase.+ * Define a composite primary key on `(user_id, agent_id, skill_name)`.++2. **Write the SQL Migration:**+ * Create a new SQL migration file in your migrations directory.+ * Write the `CREATE TABLE` statements for both tables designed above.+ * Include appropriate indexing for foreign keys to ensure query performance.++## Example SQL Migration++```sql+-- migration-YYYYMMDDHHMMSS-create-monetization-tables.sql++CREATE TABLE agent_skill_prices (+ agent_id BIGINT NOT NULL,+ skill_name VARCHAR(255) NOT NULL,+ amount BIGINT NOT NULL,+ currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (agent_id, skill_name),+ CONSTRAINT fk_agent+ FOREIGN KEY(agent_id)+ REFERENCES agents(id)+ ON DELETE CASCADE+);++CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);++CREATE TABLE user_skill_purchases (+ user_id BIGINT NOT NULL,+ agent_id BIGINT NOT NULL,+ skill_name VARCHAR(255) NOT NULL,+ purchase_tx_signature VARCHAR(255) NOT NULL,+ amount_paid BIGINT NOT NULL,+ currency_mint VARCHAR(255) NOT NULL,+ purchased_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (user_id, agent_id, skill_name),+ CONSTRAINT fk_user+ FOREIGN KEY(user_id)+ REFERENCES users(id)+ ON DELETE CASCADE,+ CONSTRAINT fk_agent+ FOREIGN KEY(agent_id)+ REFERENCES agents(id)+ ON DELETE CASCADE+);++CREATE INDEX idx_user_skill_purchases_user_id ON user_skill_purchases(user_id);+CREATE UNIQUE INDEX idx_user_skill_purchases_tx_signature ON user_skill_purchases(purchase_tx_signature);++```++## Definition of Done+- A new SQL migration file with the `CREATE TABLE` statements for `agent_skill_prices` and `user_skill_purchases` is created.+- The migration has been successfully applied to the development database.+- The schema includes primary keys, foreign keys, and indexes as specified.diff --git a/docs/monetization/01-display-priced-skills.md b/docs/monetization/01-display-priced-skills.mdnew file mode 100644index 000000000..4f41e44f2--- /dev/null+++ b/docs/monetization/01-display-priced-skills.md@@ -0,0 +1,70 @@+---+status: not-started+---++# Prompt 1: Display Priced Skills in Marketplace++## Objective+Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.++## Explanation+Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.++## Instructions+1. **Modify the Backend API:**+ * Locate the API endpoint that serves the agent detail data (`/api/marketplace/agents/:id`). You can find this in `api/marketplace/[action].js`.+ * When fetching agent details, also query the `agent_skill_prices` table to get the prices for the agent's skills.+ * Join this pricing data with the agent details response. The agent object should now have a `skill_prices` map or object, like `{ "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.++2. **Update the Frontend UI:**+ * In `src/marketplace.js`, find the `renderDetail` function.+ * This function receives the agent object, which now includes `skill_prices`.+ * Inside the loop that renders the skills (`d-skills` element), check if a price exists for the current skill.+ * If a price exists, render a price badge next to the skill name. Convert the amount from lamports (or the smallest unit) to a human-readable format (e.g., 1,000,000 lamports = 1 USDC).+ * Style the price badge to be visually distinct.++## Code Example (Frontend - `src/marketplace.js`)++Here's how you might modify the skill rendering part within the `renderDetail` function:++```javascript+// Inside renderDetail function++const skillPrices = a.skill_prices || {};+$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ const badge = price+ ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`+ : `<span class="price-badge price-free">Free</span>`;+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+```++## CSS Example++Add these styles to `/marketplace.css` to make the price badges look good.++```css+.price-badge {+ display: inline-block;+ margin-left: 8px;+ padding: 2px 6px;+ font-size: 10px;+ font-weight: 600;+ border-radius: 4px;+ vertical-align: middle;+}++.price-free {+ color: #a7f3d0;+ background-color: rgba(52, 211, 153, 0.1);+}++.price-paid {+ color: #fde047;+ background-color: rgba(253, 224, 71, 0.1);+}+```diff --git a/docs/monetization/01_display_priced_skills.md b/docs/monetization/01_display_priced_skills.mdnew file mode 100644index 000000000..3f2cbd848--- /dev/null+++ b/docs/monetization/01_display_priced_skills.md@@ -0,0 +1,70 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 01: Display Priced Skills in Marketplace++## Objective+Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.++## Explanation+Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.++## Instructions+1. **Modify the Backend API:**+ * Locate the API endpoint that serves the agent detail data (`/api/marketplace/agents/:id`). You can find this in `api/marketplace/[action].js`.+ * When fetching agent details, also query the `agent_skill_prices` table to get the prices for the agent's skills.+ * Join this pricing data with the agent details response. The agent object should now have a `skill_prices` map or object, like `{ "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.++2. **Update the Frontend UI:**+ * In `src/marketplace.js`, find the `renderDetail` function.+ * This function receives the agent object, which now includes `skill_prices`.+ * Inside the loop that renders the skills (`d-skills` element), check if a price exists for the current skill.+ * If a price exists, render a price badge next to the skill name. Convert the amount from lamports (or the smallest unit) to a human-readable format (e.g., 1,000,000 lamports = 1 USDC).+ * Style the price badge to be visually distinct.++## Code Example (Frontend - `src/marketplace.js`)++Here's how you might modify the skill rendering part within the `renderDetail` function:++```javascript+// Inside renderDetail function++const skillPrices = a.skill_prices || {};+$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ const badge = price+ ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`+ : `<span class="price-badge price-free">Free</span>`;+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+```++## CSS Example++Add these styles to `/marketplace.css` to make the price badges look good.++```css+.price-badge {+ display: inline-block;+ margin-left: 8px;+ padding: 2px 6px;+ font-size: 10px;+ font-weight: 600;+ border-radius: 4px;+ vertical-align: middle;+}++.price-free {+ color: #a7f3d0;+ background-color: rgba(52, 211, 153, 0.1);+}++.price-paid {+ color: #fde047;+ background-color: rgba(253, 224, 71, 0.1);+}+```diff --git a/docs/monetization/02-add-wallet-connect-button.md b/docs/monetization/02-add-wallet-connect-button.mdnew file mode 100644index 000000000..ab2363062--- /dev/null+++ b/docs/monetization/02-add-wallet-connect-button.md@@ -0,0 +1,76 @@+# Prompt 2: Add "Connect Wallet" Button++## Status+- [ ] Not Started++## Objective+Integrate a "Connect Wallet" button into the main application header, which will serve as the entry point for users to connect their Solana wallets.++## Explanation+Before a user can purchase a skill, they must connect their Solana wallet. This prompt focuses on adding the UI element for wallet connection and setting up the initial event listeners. The actual wallet connection logic will be handled in a subsequent step.++## Instructions+1. **Update the main HTML layout:**+ * Locate the primary header or navigation component in `app.html`.+ * Add a new button with the ID `connect-wallet-btn`.+ * Initially, the button text should be "Connect Wallet". After a successful connection, this text will change to the user's wallet address.++2. **Create a dedicated wallet management module:**+ * Create a new file: `src/wallet.js`.+ * This module will encapsulate all wallet-related functionality (connecting, disconnecting, getting the current user's address, etc.).+ * Create an initialization function, e.g., `initWalletButton`, that adds a click event listener to the new button.++3. **Integrate the wallet module into the main application:**+ * In your main application entry point (`src/main.js` or similar), import and call the `initWalletButton` function to activate the button.++## Code Example (app.html)+```html+<!-- Inside the header element -->+<div class="header-actions">+ <button id="connect-wallet-btn">Connect Wallet</button>+</div>+```++## Code Example (src/wallet.js)+```javascript+// src/wallet.js++// Placeholder for wallet adapter logic+let wallet;++function onConnectWallet() {+ console.log('Attempting to connect wallet...');+ // The actual connection logic will be implemented in the next prompt.+ // For now, we can simulate a successful connection.+ const mockAddress = 'YourWalletAddress...';+ updateWalletState(mockAddress);+}++export function updateWalletState(address) {+ const btn = document.getElementById('connect-wallet-btn');+ if (address) {+ // Display shortened address+ btn.textContent = `${address.slice(0, 4)}...${address.slice(-4)}`;+ } else {+ btn.textContent = 'Connect Wallet';+ }+}++export function initWalletButton() {+ const btn = document.getElementById('connect-wallet-btn');+ if (btn) {+ btn.addEventListener('click', onConnectWallet);+ }+}+```++## Code Example (src/main.js)+```javascript+// src/main.js+import { initWalletButton } from './wallet.js';++document.addEventListener('DOMContentLoaded', () => {+ // ... other initializations+ initWalletButton();+});+```diff --git a/docs/monetization/02-backend-create-skill-pricing-table.md b/docs/monetization/02-backend-create-skill-pricing-table.mdnew file mode 100644index 000000000..bc1daa91c--- /dev/null+++ b/docs/monetization/02-backend-create-skill-pricing-table.md@@ -0,0 +1,63 @@+---+status: not-started+---++# Prompt 2: Backend - Create Skill Pricing Table++## Objective+Design and create the necessary database table to store pricing information for agent skills. This is a foundational step for all monetization features.++## Explanation+To make skills purchasable, we need a dedicated table in our PostgreSQL database (`agent_skill_prices`) that links a skill to an agent, and specifies its price and currency. This table will be the source of truth for all skill pricing on the platform.++## Instructions+1. **Design the Table Schema:**+ * The table should be named `agent_skill_prices`.+ * It needs columns to link to the agent (`agent_id`) and to identify the skill (`skill_id` or `skill_name`). Using `skill_name` (e.g., a `TEXT` or `VARCHAR` field) can simplify lookups, assuming skill names are unique per agent.+ * It must have a column for the price amount (e.g., `amount` as `BIGINT` to store lamports or other smallest currency units).+ * It must have a column for the currency (e.g., `currency_mint` as `TEXT` to store the Solana mint address of the currency, like USDC).+ * Add a primary key and foreign key constraints to `agent_identities`.+ * Create a unique constraint on (`agent_id`, `skill_name`) to prevent duplicate price entries for the same skill on the same agent.++2. **Create a SQL Migration File:**+ * Create a new SQL file in a migrations directory (if one exists, otherwise you can place it in `scripts/migrations/`).+ * Write the `CREATE TABLE` statement for `agent_skill_prices`.+ * Include standard columns like `created_at` and `updated_at`.++## Code Example (SQL)++```sql+-- scripts/migrations/002_create_agent_skill_prices.sql++CREATE TABLE IF NOT EXISTS agent_skill_prices (+ id SERIAL PRIMARY KEY,+ agent_id INTEGER NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ skill_name VARCHAR(255) NOT NULL,+ -- Price in the smallest denomination (e.g., lamports for SOL, or 10^-6 for USDC)+ amount BIGINT NOT NULL CHECK (amount >= 0),+ -- The mint address of the currency token (e.g., USDC, BONK, etc.)+ currency_mint VARCHAR(44) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ -- An agent can only have one price per skill.+ UNIQUE (agent_id, skill_name)+);++-- Optional: Create an index for faster lookups+CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);++-- Optional: Add a trigger to automatically update the updated_at timestamp+CREATE OR REPLACE FUNCTION set_updated_at_timestamp()+RETURNS TRIGGER AS $$+BEGIN+ NEW.updated_at = NOW();+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++CREATE TRIGGER set_timestamp+BEFORE UPDATE ON agent_skill_prices+FOR EACH ROW+EXECUTE PROCEDURE set_updated_at_timestamp();+```diff --git a/docs/monetization/02-creator-ui-set-prices.md b/docs/monetization/02-creator-ui-set-prices.mdnew file mode 100644index 000000000..8cde0f1d5--- /dev/null+++ b/docs/monetization/02-creator-ui-set-prices.md@@ -0,0 +1,40 @@+---+status: not-started+---++# Prompt 2: Creator UI to Set Skill Prices++## Objective+Create a user interface within the agent creation/editing page that allows creators to set and update prices for their agent's skills.++## Explanation+To enable skill monetization, creators need a way to manage the prices of their skills. This new UI will allow them to assign a price and currency to each skill, which will then be saved to the database.++## Instructions+1. **Modify the Agent Edit Page:**+ * Locate the agent editing page, likely `agent-edit.html` or a similar file.+ * Find the section where skills are listed or added.+ * For each skill, add input fields for `price` and `currency`. The currency could be a dropdown (e.g., "USDC", "SOL").++2. **Handle Form Submission:**+ * In the corresponding JavaScript file (e.g., `src/agent-edit.js`), update the form submission logic.+ * When the creator saves the agent, collect the pricing information for each skill.+ * Send this data to the backend API.++## Code Example (Frontend - `agent-edit.html`)++This is a conceptual example of what the new skill section might look like.++```html+<div id="skills-section">+ <!-- Existing skill list -->+ <div class="skill-item">+ <span>Skill Name</span>+ <input type="number" class="skill-price-input" placeholder="Price">+ <select class="skill-currency-select">+ <option value="USDC">USDC</option>+ <option value="SOL">SOL</option>+ </select>+ </div>+</div>+```diff --git a/docs/monetization/02-display-priced-skills-api.md b/docs/monetization/02-display-priced-skills-api.mdnew file mode 100644index 000000000..4c308a13c--- /dev/null+++ b/docs/monetization/02-display-priced-skills-api.md@@ -0,0 +1,87 @@+---+status: not-started+completed_at: null+---+# Prompt 2: Modify Agent Detail API to Include Skill Prices++## Objective+Enhance the backend API to include skill pricing information when fetching details for a specific agent.++## Explanation+Building on the new database schema, we need to make pricing data available to the frontend. The API endpoint that serves agent details for the marketplace (`/api/marketplace/agents/:id`) must be updated to join and include the prices for the skills associated with that agent.++## Instructions+1. **Locate the API Endpoint:**+ * Find the code responsible for handling the `GET /api/marketplace/agents/:id` request. This is likely in a file such as `api/marketplace/[action].js` or a similar route handler.++2. **Update the Database Query:**+ * In the function that fetches the agent's details from the database, add a `LEFT JOIN` to the `agent_skill_prices` table.+ * The join condition should be on `agents.id = agent_skill_prices.agent_id`.++3. **Restructure the API Response:**+ * The database query will likely return multiple rows for the same agent if it has multiple priced skills. You need to process these rows to build a single agent object.+ * The final agent object sent to the frontend should have a new property, `skill_prices`.+ * This `skill_prices` property should be an object (or map) where keys are the `skill_name` and values are objects containing the `amount` and `currency_mint`.++## Code Example (Backend API Handler)++Here's a conceptual example of how to modify the data retrieval and shaping logic.++```javascript+// Example using a hypothetical database client like 'db'++async function getAgentWithSkillPrices(agentId) {+ const query = `+ SELECT+ a.*, -- all columns from agents table+ sp.skill_name,+ sp.amount,+ sp.currency_mint+ FROM+ agents a+ LEFT JOIN+ agent_skill_prices sp ON a.id = sp.agent_id+ WHERE+ a.id = $1;+ `;++ const { rows } = await db.query(query, [agentId]);++ if (rows.length === 0) {+ return null; // or throw 404+ }++ // Aggregate the pricing data+ const agent = {+ // Spread the first row to get agent properties+ id: rows[0].id,+ name: rows[0].name,+ description: rows[0].description,+ // ... other agent fields+ skills: rows[0].skills, // Assuming skills are stored as a JSONB array+ skill_prices: {}+ };++ rows.forEach(row => {+ if (row.skill_name && row.amount !== null) {+ agent.skill_prices[row.skill_name] = {+ amount: row.amount,+ currency_mint: row.currency_mint+ };+ }+ });++ return agent;+}++// In your API route handler:+// const agent = await getAgentWithSkillPrices(req.params.id);+// res.status(200).json(agent);+```++## Definition of Done+- The API endpoint `GET /api/marketplace/agents/:id` is updated.+- When an agent has priced skills, the JSON response now includes a `skill_prices` object.+- The `skill_prices` object contains an entry for each priced skill with its `amount` and `currency_mint`.+- If an agent has no priced skills, `skill_prices` should be an empty object `{}`.+- The endpoint continues to function correctly for agents with no skills or no priced skills.diff --git a/docs/monetization/02_db_schema_for_pricing.md b/docs/monetization/02_db_schema_for_pricing.mdnew file mode 100644index 000000000..b846f4dd3--- /dev/null+++ b/docs/monetization/02_db_schema_for_pricing.md@@ -0,0 +1,69 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 02: Database Schema for Skill Pricing++## Objective+Create the necessary database table to store prices for agent skills.++## Explanation+To allow creators to set prices for their skills, we need a dedicated table in our PostgreSQL database. This table will link an agent, a skill, and a price, defined by an amount and a currency. This structure allows for future flexibility, such as supporting multiple currencies.++## Instructions+1. **Design the Table:**+ * Create a new table named `agent_skill_prices`.+ * The table should have the following columns:+ * `id`: Primary key (e.g., UUID or SERIAL).+ * `agent_id`: Foreign key referencing the `agent_identities` table.+ * `skill_name`: A text field to identify the skill. It should match the name defined in the agent's manifest.+ * `amount`: A numeric or bigint type to store the price in the smallest denomination of the currency (e.g., lamports for Solana tokens).+ * `currency_mint`: A text field to store the mint address of the currency (e.g., the USDC mint address on Solana).+ * `created_at`: Timestamp of creation.+ * `updated_at`: Timestamp of the last update.+ * Add a unique constraint on (`agent_id`, `skill_name`) to ensure a skill only has one price per agent.++2. **Write the SQL Migration:**+ * Create a new SQL migration file.+ * Write the `CREATE TABLE` statement according to the design above.+ * Include commands to create indexes on `agent_id` for efficient lookups.++## SQL Example++Here is the PostgreSQL `CREATE TABLE` statement.++```sql+CREATE TABLE IF NOT EXISTS agent_skill_prices (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id UUID NOT NULL,+ skill_name VARCHAR(255) NOT NULL,+ amount BIGINT NOT NULL CHECK (amount > 0),+ currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT fk_agent+ FOREIGN KEY(agent_id)+ REFERENCES agent_identities(id)+ ON DELETE CASCADE,++ UNIQUE (agent_id, skill_name)+);++CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);++-- Optional: Create a trigger to auto-update updated_at timestamp+CREATE OR REPLACE FUNCTION trigger_set_timestamp()+RETURNS TRIGGER AS $$+BEGIN+ NEW.updated_at = NOW();+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++CREATE TRIGGER set_timestamp+BEFORE UPDATE ON agent_skill_prices+FOR EACH ROW+EXECUTE PROCEDURE trigger_set_timestamp();++```diff --git a/docs/monetization/03-backend-api-set-prices.md b/docs/monetization/03-backend-api-set-prices.mdnew file mode 100644index 000000000..54bbad60e--- /dev/null+++ b/docs/monetization/03-backend-api-set-prices.md@@ -0,0 +1,48 @@+---+status: not-started+---++# Prompt 3: Backend API to Set Skill Prices++## Objective+Implement a secure backend API endpoint that allows agent creators to save and update the prices for their skills.++## Explanation+This API will receive the pricing information from the creator UI and persist it in the database. It's crucial that this endpoint is secure and only allows the agent's owner to modify the prices.++## Instructions+1. **Create a New API Endpoint:**+ * Create a new API endpoint, for example, `POST /api/agents/:id/skills/prices`.+ * This endpoint should be protected and require authentication. Ensure that the authenticated user is the owner of the agent.++2. **Implement the Logic:**+ * The endpoint will receive a payload containing the skill prices, like ` { "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.+ * Validate the input data to ensure it's in the correct format.+ * In the database, update or insert the new prices in the `agent_skill_prices` table, associating them with the agent and the specific skills.++## Code Example (Backend - Express.js like)++```javascript+// POST /api/agents/:id/skills/prices+router.post('/:id/skills/prices', async (req, res) => {+ const { id } = req.params;+ const { prices } = req.body;+ const userId = req.session.userId;++ // 1. Authenticate and authorize the user+ const agent = await db.getAgentById(id);+ if (!agent || agent.owner_id !== userId) {+ return res.status(403).json({ error: 'Forbidden' });+ }++ // 2. Validate the pricing data+ if (!prices) {+ return res.status(400).json({ error: 'Invalid input' });+ }++ // 3. Save the prices to the database+ await db.saveSkillPrices(id, prices);++ res.status(200).json({ success: true });+});+```diff --git a/docs/monetization/03-backend-api-set-skill-prices.md b/docs/monetization/03-backend-api-set-skill-prices.mdnew file mode 100644index 000000000..b5059d1dc--- /dev/null+++ b/docs/monetization/03-backend-api-set-skill-prices.md@@ -0,0 +1,97 @@+---+status: not-started+---++# Prompt 3: Backend - API to Set/Update Skill Prices++## Objective+Create a secure backend API endpoint that allows an agent's creator to set or update the price of their skills.++## Explanation+With the database table in place, we now need a way for creators to manage their skill prices programmatically. This requires an authenticated API endpoint that accepts pricing information and updates the `agent_skill_prices` table. The endpoint must verify that the user making the request is the owner of the agent.++## Instructions+1. **Create the API Endpoint File:**+ * Create a new file in the API directory, for example, `api/agents/skills.js`. This can be a Vercel serverless function.+ * This endpoint should handle `POST` or `PUT` requests to a path like `/api/agents/[agentId]/skills/prices`.++2. **Implement Authentication and Authorization:**+ * The endpoint must be authenticated. Use your existing authentication middleware (e.g., checking for a valid JWT or session cookie) to get the `user_id` of the requester.+ * Before making any database changes, verify that the `user_id` owns the `agentId` specified in the URL. You'll need to query the `agent_identities` table. If they are not the owner, return a `403 Forbidden` error.++3. **Handle the Request Body:**+ * The request body should contain the skill's name, the price amount (in lamports), and the currency mint address.+ * Example body: `{ "skill_name": "Jupiter Swapper", "amount": 1000000, "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T" }`+ * Validate the input. Ensure `amount` is a non-negative number and `currency_mint` is a valid Solana public key format.++4. **Implement the Database Logic:**+ * Use an `INSERT ... ON CONFLICT` (UPSERT) statement to either create a new price entry or update an existing one for the given `agent_id` and `skill_name`.+ * The `ON CONFLICT (agent_id, skill_name) DO UPDATE` clause makes the logic simple and atomic.++5. **Return a Response:**+ * If successful, return a `200 OK` or `201 Created` status with the newly created/updated pricing information.+ * Return appropriate error codes for bad input (`400`), unauthorized access (`403`), or server errors (`500`).++## Code Example (Vercel Serverless Function - `api/agents/skills.js`)++```javascript+import { cors, json, method, wrap } from '../_lib/http.js';+import { getAuth } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';++export default wrap(async (req, res) => {+ if (cors(req, res)) return;+ if (!method(req, res, ['POST'])) return;++ // 1. Authentication+ const auth = await getAuth(req);+ if (!auth.userId) {+ return json(res, 401, { error: 'Authentication required' });+ }++ // 2. Extract agentId and validation+ const { agentId } = req.query;+ if (!agentId) {+ return json(res, 400, { error: 'Agent ID is required' });+ }++ const [agent] = await sql`+ SELECT user_id FROM agent_identities WHERE id = ${agentId}+ `;++ if (!agent) {+ return json(res, 404, { error: 'Agent not found' });+ }++ // 3. Authorization+ if (agent.user_id !== auth.userId) {+ return json(res, 403, { error: 'You do not own this agent' });+ }++ // 4. Input validation+ const { skill_name, amount, currency_mint } = req.body;+ if (!skill_name || typeof amount !== 'number' || amount < 0 || !currency_mint) {+ return json(res, 400, { error: 'Invalid input: skill_name, amount, and currency_mint are required.' });+ }++ // 5. Database UPSERT+ try {+ const [price] = await sql`+ INSERT INTO agent_skill_prices+ (agent_id, skill_name, amount, currency_mint)+ VALUES+ (${agentId}, ${skill_name}, ${amount}, ${currency_mint})+ ON CONFLICT (agent_id, skill_name)+ DO UPDATE SET+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ updated_at = NOW()+ RETURNING *+ `;+ return json(res, 200, { price });+ } catch (error) {+ console.error('Failed to set skill price:', error);+ return json(res, 500, { error: 'Internal Server Error' });+ }+});+```diff --git a/docs/monetization/03-creator-api-set-skill-price.md b/docs/monetization/03-creator-api-set-skill-price.mdnew file mode 100644index 000000000..2de31ab21--- /dev/null+++ b/docs/monetization/03-creator-api-set-skill-price.md@@ -0,0 +1,95 @@+---+status: not-started+completed_at: null+---+# Prompt 3: Creator API to Set/Update Skill Prices++## Objective+Create a secure backend API endpoint that allows agent creators to set, update, or remove the price for their agent's skills.++## Explanation+To enable a creator-driven economy, we need to provide the tools for creators to manage their offerings. This prompt focuses on building the backend endpoint that will power the UI for pricing skills in the Creator Dashboard. The endpoint must be secure, ensuring only the agent's owner can modify prices.++## Instructions+1. **Define the API Endpoint:**+ * Create a new API route: `POST /api/creator/agents/:agentId/skills/price`.+ * This endpoint will handle creating, updating, and deleting skill prices.++2. **Implement Authentication and Authorization:**+ * The endpoint must be protected. Ensure you have middleware that verifies the user is authenticated (e.g., checks for a valid session cookie or JWT).+ * Implement an authorization check. Before processing the request, verify that the authenticated user is the owner of the `agentId` specified in the URL. If not, return a `403 Forbidden` error.++3. **Handle the Request Body:**+ * The request body should contain:+ * `skill_name`: The name of the skill to price.+ * `amount` (optional): The price in the smallest currency unit. If `null` or `0`, it implies the skill is being made free (price is being removed).+ * `currency_mint` (optional): The SPL token mint address. Required if `amount` is greater than 0.++4. **Implement Database Logic:**+ * **If `amount` is positive:**+ * Use an `UPSERT` (or `INSERT ... ON CONFLICT UPDATE`) operation on the `agent_skill_prices` table.+ * Match on the composite primary key `(agent_id, skill_name)`.+ * If a record exists, `UPDATE` the `amount` and `currency_mint`.+ * If no record exists, `INSERT` a new row.+ * **If `amount` is `null`, `0`, or not provided:**+ * `DELETE` the corresponding row from the `agent_skill_prices` table for that `agent_id` and `skill_name`.++5. **Return a Response:**+ * On success, return a `200 OK` or `204 No Content` response.+ * On validation failure (e.g., missing `currency_mint` for a paid skill), return a `400 Bad Request`.++## Code Example (Backend API Handler)++```javascript+// Example using Express.js and a hypothetical 'db' client++// Assume 'authMiddleware' and 'agentOwnershipMiddleware' exist and are applied to this route.+app.post('/api/creator/agents/:agentId/skills/price', async (req, res) => {+ const { agentId } = req.params;+ const { skill_name, amount, currency_mint } = req.body;++ // Basic validation+ if (!skill_name) {+ return res.status(400).json({ error: 'skill_name is required.' });+ }++ const numericAmount = amount ? BigInt(amount) : 0n;++ if (numericAmount > 0n && !currency_mint) {+ return res.status(400).json({ error: 'currency_mint is required for paid skills.' });+ }++ try {+ if (numericAmount > 0n) {+ // Upsert logic+ const query = `+ INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (agent_id, skill_name)+ DO UPDATE SET amount = $3, currency_mint = $4, updated_at = CURRENT_TIMESTAMP;+ `;+ await db.query(query, [agentId, skill_name, numericAmount, currency_mint]);+ } else {+ // Delete logic (make skill free)+ const query = `+ DELETE FROM agent_skill_prices+ WHERE agent_id = $1 AND skill_name = $2;+ `;+ await db.query(query, [agentId, skill_name]);+ }++ res.status(204).send();++ } catch (error) {+ console.error('Failed to update skill price:', error);+ res.status(500).json({ error: 'An internal error occurred.' });+ }+});+```++## Definition of Done+- A new `POST` endpoint at `/api/creator/agents/:agentId/skills/price` is created and functional.+- The endpoint correctly requires authentication.+- The endpoint correctly verifies that the user owns the agent before making changes.+- The endpoint can successfully create, update, and delete entries in the `agent_skill_prices` table based on the request body.+- Appropriate error responses (`400`, `403`, `500`) are returned in failure cases.diff --git a/docs/monetization/03-implement-solana-wallet-connection.md b/docs/monetization/03-implement-solana-wallet-connection.mdnew file mode 100644index 000000000..530b0d07d--- /dev/null+++ b/docs/monetization/03-implement-solana-wallet-connection.md@@ -0,0 +1,89 @@+# Prompt 3: Implement Solana Wallet Connection++## Status+- [ ] Not Started++## Objective+Implement the core logic for connecting to a user's Solana wallet using a standard wallet adapter library like `@solana/wallet-adapter-base` and `@solana/wallet-adapter-wallets`.++## Explanation+This prompt builds on the previous one by implementing the functionality behind the "Connect Wallet" button. We will use the Solana Wallet Adapter libraries to present the user with a list of installed wallets (e.g., Phantom, Solflare) and manage the connection state.++## Instructions+1. **Install Dependencies:**+ * Add the necessary Solana wallet adapter libraries to your project's `package.json` and install them.+ * You'll typically need `@solana/web3.js`, `@solana/wallet-adapter-base`, `@solana/wallet-adapter-wallets`, and specific wallet adapters you wish to support.++2. **Update the Wallet Module (`src/wallet.js`):**+ * Import the wallet adapter classes.+ * Instantiate the wallets you want to support (e.g., `PhantomWalletAdapter`, `SolflareWalletAdapter`).+ * Implement the `onConnectWallet` function to trigger the wallet adapter's connect flow. This will typically open a modal for the user to select their wallet.+ * Listen for changes in the wallet's connection status and update the UI accordingly using the `updateWalletState` function created previously.++## Code Example (Terminal - Installation)+```bash+npm install @solana/web3.js @solana/wallet-adapter-base @solana/wallet-adapter-wallets @solana/wallet-adapter-phantom+```++## Code Example (src/wallet.js)+```javascript+// src/wallet.js+import { PhantomWalletAdapter } from '@solana/wallet-adapter-phantom';+import { Connection, PublicKey } from '@solana/web3.js';++let connectedWalletAddress = null;++// Initialize the wallet adapter+const wallet = new PhantomWalletAdapter();++// Listen for connection events+wallet.on('connect', (publicKey) => {+ connectedWalletAddress = publicKey.toBase58();+ console.log(`Wallet connected: ${connectedWalletAddress}`);+ updateWalletState(connectedWalletAddress);+});++wallet.on('disconnect', () => {+ console.log('Wallet disconnected');+ connectedWalletAddress = null;+ updateWalletState(null);+});++async function onConnectWallet() {+ if (!wallet.connected) {+ try {+ await wallet.connect();+ } catch (error) {+ console.error('Wallet connection failed:', error);+ }+ }+}++export function updateWalletState(address) {+ const btn = document.getElementById('connect-wallet-btn');+ if (address) {+ btn.textContent = `${address.slice(0, 4)}...${address.slice(-4)}`;+ } else {+ btn.textContent = 'Connect Wallet';+ }+}++export function initWalletButton() {+ const btn = document.getElementById('connect-wallet-btn');+ if (btn) {+ btn.addEventListener('click', onConnectWallet);+ }+ // Auto-connect if wallet is already connected+ if (wallet.autoConnect) {+ wallet.autoConnect();+ }+}++export function getConnectedWallet() {+ return wallet.connected ? wallet : null;+}++export function getConnectedWalletAddress() {+ return connectedWalletAddress;+}+```diff --git a/docs/monetization/03_ui_for_setting_prices.md b/docs/monetization/03_ui_for_setting_prices.mdnew file mode 100644index 000000000..e7afcbad1--- /dev/null+++ b/docs/monetization/03_ui_for_setting_prices.md@@ -0,0 +1,95 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 03: UI for Setting Skill Prices++## Objective+Create a user interface within the agent editor (`agent-edit.html`) that allows agent creators to set and update prices for their skills.++## Explanation+For creators to monetize their work, they need a simple and intuitive way to manage the prices of their skills. This task involves adding a new section to the agent editor page where each skill listed has an input field to set its price.++## Instructions+1. **Locate the Agent Editor:**+ * Open `agent-edit.html` and its corresponding JavaScript module, likely `src/agent-edit.js`.++2. **Fetch Existing Prices:**+ * When loading the agent for editing, the backend should also fetch and provide any existing prices from the `agent_skill_prices` table. The main agent object should be decorated with this information.++3. **Implement the UI:**+ * In the section where the agent's skills are displayed, modify the rendering logic.+ * For each skill, display an input field for the price and a dropdown or static text for the currency (initially, we can hardcode to USDC).+ * The input should be pre-filled with the existing price if it has been set.+ * Add a "Save Prices" button or integrate the price updates into the main "Save Agent" functionality.++## Code Example (HTML Structure in `agent-edit.html`)++This is a conceptual HTML structure. You will need to integrate it into the existing template.++```html+<!-- Inside the agent editor form -->+<div class="panel">+ <h2 class="panel-title">Skill Monetization</h2>+ <p class="panel-subtitle">Set prices for your agent's skills in USDC.</p>+ <div id="skill-pricing-list">+ <!-- JavaScript will render individual skill inputs here -->+ </div>+ <button id="save-skill-prices" class="btn">Save Prices</button>+</div>+```++## Code Example (JavaScript - `src/agent-edit.js`)++This is how you might render the pricing inputs.++```javascript+// Assume `agent` object has `skills` array and `skill_prices` map+const skills = agent.skills || [];+const prices = agent.skill_prices || {};+const container = document.getElementById('skill-pricing-list');++container.innerHTML = skills.map(skill => {+ const price = prices[skill.name];+ const amount = price ? (price.amount / 1e6).toFixed(2) : ''; // Convert from lamports+ return `+ <div class="skill-price-entry">+ <label for="price-${skill.name}">${skill.name}</label>+ <div class="price-input-wrapper">+ <input+ type="number"+ id="price-${skill.name}"+ data-skill-name="${skill.name}"+ value="${amount}"+ placeholder="e.g., 0.99"+ min="0"+ step="0.01"+ />+ <span class="currency-label">USDC</span>+ </div>+ </div>+ `;+}).join('');++// Add an event listener to the save button to collect and send data+document.getElementById('save-skill-prices').addEventListener('click', () => {+ const updatedPrices = {};+ document.querySelectorAll('.price-input-wrapper input').forEach(input => {+ const skillName = input.dataset.skillName;+ const amount = parseFloat(input.value);+ if (skillName && !isNaN(amount) && amount > 0) {+ updatedPrices[skillName] = {+ amount: Math.round(amount * 1e6), // Convert to lamports+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a' // USDC mint+ };+ }+ });++ // Send `updatedPrices` to a new API endpoint+ fetch(`/api/agents/${agent.id}/skill-prices`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(updatedPrices)+ });+});+```diff --git a/docs/monetization/04-db-schema-skill-prices.md b/docs/monetization/04-db-schema-skill-prices.mdnew file mode 100644index 000000000..d2479299e--- /dev/null+++ b/docs/monetization/04-db-schema-skill-prices.md@@ -0,0 +1,42 @@+---+status: not-started+---++# Prompt 4: Database Schema for Skill Prices++## Objective+Design and implement the necessary database schema to store the prices of agent skills.++## Explanation+A new table, `agent_skill_prices`, is needed to store the monetization information for each skill. This table will link an agent, a skill, and its price.++## Instructions+1. **Design the Table:**+ * Create a new table named `agent_skill_prices`.+ * The table should have the following columns:+ * `id`: Primary key.+ * `agent_id`: Foreign key referencing the `agents` table.+ * `skill_name`: The name of the skill being priced.+ * `amount`: The price of the skill in the smallest currency unit (e.g., lamports).+ * `currency_mint`: The mint address of the currency (e.g., the USDC mint on Solana).+ * `created_at`, `updated_at`: Timestamps.++2. **Create a Migration:**+ * Use your database migration tool to create a new migration file.+ * Write the SQL script to create the `agent_skill_prices` table.+ * Apply the migration to your database.++## SQL Example++```sql+CREATE TABLE agent_skill_prices (+ id SERIAL PRIMARY KEY,+ agent_id UUID NOT NULL REFERENCES agents(id),+ skill_name VARCHAR(255) NOT NULL,+ amount BIGINT NOT NULL,+ currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ UNIQUE(agent_id, skill_name)+);+```diff --git a/docs/monetization/04-design-database-schema-for-skill-pricing.md b/docs/monetization/04-design-database-schema-for-skill-pricing.mdnew file mode 100644index 000000000..cbf9611dc--- /dev/null+++ b/docs/monetization/04-design-database-schema-for-skill-pricing.md@@ -0,0 +1,46 @@+# Prompt 4: Design Database Schema for Skill Pricing++## Status+- [ ] Not Started++## Objective+Design and create the necessary database table(s) to store pricing information for agent skills.++## Explanation+To make skills purchasable, we need a persistent storage solution for their pricing details. This prompt outlines the creation of an `agent_skill_prices` table that will link skills to their price and currency.++## Instructions+1. **Define the Schema:**+ * Create a new table named `agent_skill_prices`.+ * The table should include the following columns:+ * `id`: Primary key (e.g., UUID or auto-incrementing integer).+ * `agent_id`: Foreign key referencing the `agents` table.+ * `skill_name`: The name of the skill (e.g., "super-jump"). This should match the skill name defined in the agent's configuration.+ * `amount`: The price of the skill in the smallest unit of the currency (e.g., lamports for SOL, or the base unit for USDC). Use a data type that can handle large numbers (e.g., `BIGINT` or `NUMERIC`).+ * `currency_mint`: The mint address of the SPL token used for payment (e.g., the USDC mint address).+ * `created_at`, `updated_at`: Timestamps for record management.++2. **Write the SQL Migration:**+ * Create a new SQL migration file to apply this schema change to the database.+ * Include `CREATE TABLE` and `CREATE INDEX` statements. It's recommended to create an index on `(agent_id, skill_name)` for quick lookups.++## SQL Example (PostgreSQL)+```sql+-- migration-002-create-agent-skill-prices.sql++CREATE TABLE agent_skill_prices (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,+ skill_name VARCHAR(255) NOT NULL,+ amount BIGINT NOT NULL,+ currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++CREATE UNIQUE INDEX idx_agent_skill_prices_on_agent_and_skill+ON agent_skill_prices (agent_id, skill_name);++COMMENT ON COLUMN agent_skill_prices.amount IS 'Price in the smallest currency unit (e.g., lamports)';+COMMENT ON COLUMN agent_skill_prices.currency_mint IS 'Mint address of the SPL token for payment';+```diff --git a/docs/monetization/04-frontend-display-priced-skills.md b/docs/monetization/04-frontend-display-priced-skills.mdnew file mode 100644index 000000000..1306cc926--- /dev/null+++ b/docs/monetization/04-frontend-display-priced-skills.md@@ -0,0 +1,84 @@+---+status: not-started+completed_at: null+---+# Prompt 4: Frontend UI for Displaying Priced Skills++## Objective+Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.++## Explanation+Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.++## Instructions+1. **Locate the Frontend Code:**+ * In `src/marketplace.js`, find the `renderDetail` function. This function is responsible for rendering the agent's profile, including its list of skills.++2. **Access Pricing Data:**+ * The `renderDetail` function receives the full agent object from the API. With the backend changes from Prompt #2, this object now includes a `skill_prices` map.++3. **Update the Skill Rendering Logic:**+ * Inside the loop that renders the skills (likely targeting the `d-skills` element), check if a price exists for the current skill in the `skill_prices` object.+ * **If a price exists:** Render a price badge next to the skill name. The amount will be in the smallest unit of the currency (e.g., lamports or 10^-6 for USDC). Convert this to a human-readable format (e.g., `(price.amount / 1e6).toFixed(2)` for a 6-decimal USDC).+ * **If a price does not exist:** Render a "Free" badge to make the distinction clear.+ * Use different CSS classes for paid vs. free badges for distinct styling.++4. **Add CSS for Badges:**+ * Open `/marketplace.css` and add the styles for the new price badges. Make them noticeable but not intrusive.++## Code Example (Frontend - `src/marketplace.js`)++Here's how you might modify the skill rendering part within the `renderDetail` function:++```javascript+// Inside renderDetail function, assuming 'a' is the agent object++const skillPrices = a.skill_prices || {};+const skillsArr = a.skills || []; // Assuming skills is an array of strings or objects++$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ if (!name) return ''; // Skip empty skills++ const price = skillPrices[name];+ const badge = price+ ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`+ : `<span class="price-badge price-free">Free</span>`;++ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ }).join(' ')+ : '<div>This Agent has no skills defined.</div>';+```++## CSS Example (`/marketplace.css`)++```css+.price-badge {+ display: inline-block;+ margin-left: 8px;+ padding: 2px 6px;+ font-size: 10px;+ font-weight: 600;+ border-radius: 4px;+ vertical-align: middle;+ text-transform: uppercase;+}++.price-free {+ color: #a7f3d0; /* A light green */+ background-color: rgba(52, 211, 153, 0.1);+}++.price-paid {+ color: #fde047; /* A light yellow/gold */+ background-color: rgba(253, 224, 71, 0.1);+}+```++## Definition of Done+- The agent detail page in the marketplace now displays badges next to each skill.+- Paid skills show the price in a human-readable format (e.g., "1.00 USDC").+- Free skills show a "Free" badge.+- The badges are styled according to the CSS example and look professional.+- The page handles agents with no skills or a mix of free and paid skills without errors.diff --git a/docs/monetization/04-frontend-skill-pricing-ui.md b/docs/monetization/04-frontend-skill-pricing-ui.mdnew file mode 100644index 000000000..279874b3a--- /dev/null+++ b/docs/monetization/04-frontend-skill-pricing-ui.md@@ -0,0 +1,120 @@+---+status: not-started+---++# Prompt 4: Frontend - Skill Pricing UI in Agent Editor++## Objective+Build a user interface within the agent editor page (`agent-edit.html`) that allows creators to view, add, and update prices for their agent's skills.++## Explanation+To make the new pricing API useful, creators need a friendly UI. This task involves adding a new section to the agent editor page. This section will list all of the agent's available skills and provide input fields for creators to set a price and currency for each one. The UI will then call the API endpoint created in the previous step to save the changes.++## Instructions+1. **Locate the Agent Editor File:**+ * Open the `agent-edit.html` file and its corresponding JavaScript file (e.g., `src/agent-edit.js`).++2. **Design the UI:**+ * In `agent-edit.html`, add a new section titled "Skill Monetization" or "Skill Pricing".+ * This section should dynamically render a list of the agent's skills.+ * For each skill, display:+ * The skill name (read-only).+ * An input field for the price (`amount`).+ * A dropdown or input field for the `currency_mint` (for now, you can default this to USDC's mint address).+ * A "Save" or "Update" button for each skill, or a single "Save All Prices" button for the section.++3. **Implement the Frontend Logic:**+ * In `src/agent-edit.js`, when the agent data is loaded, populate the new UI section. You'll need to fetch the existing skill prices along with the agent details.+ * Attach an event listener to the "Save" button(s).+ * When a creator clicks "Save", gather the `skill_name`, `amount`, and `currency_mint` from the input fields.+ * **Important:** The amount in the UI will be in a human-readable format (e.g., 1.00 USDC), but the API expects lamports. You must convert the UI value to the smallest unit before sending it to the API (e.g., `parseFloat(amountInput.value) * 1e6`).+ * Make a `POST` request to the `/api/agents/[agentId]/skills/prices` endpoint with the data in the request body.+ * Provide user feedback, such as a toast notification ("Price updated successfully!") or by changing the state of the save button (e.g., showing a checkmark).+ * Handle any errors returned from the API and display a helpful message to the user.++## Code Example (HTML in `agent-edit.html`)++```html+<!-- Inside the agent editor form -->+<div class="form-section">+ <h3>Skill Pricing</h3>+ <p class="form-section-desc">+ Set prices for your agent's skills. Payments will be handled on Solana.+ </p>+ <div id="skill-pricing-list">+ <!-- Skills will be dynamically rendered here -->+ </div>+</div>+```++## Code Example (JavaScript in `src/agent-edit.js`)++```javascript+// Function to render the pricing UI+function renderSkillPricing(agent) {+ const skills = agent.skills || []; // Assuming agent.skills is an array of skill objects/names+ const prices = agent.skill_prices || {};+ const container = document.getElementById('skill-pricing-list');++ container.innerHTML = skills.map(skill => {+ const skillName = typeof skill === 'string' ? skill : skill.name;+ const price = prices[skillName];+ const amountInUSDC = price ? (price.amount / 1e6).toFixed(2) : '0.00';++ return `+ <div class="skill-price-entry" data-skill-name="${escapeHtml(skillName)}">+ <label>${escapeHtml(skillName)}</label>+ <div class="price-inputs">+ <input type="number" step="0.01" min="0" value="${amountInUSDC}" class="price-amount-input">+ <select class="price-currency-select">+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T">USDC</option>+ </select>+ <button class="btn-save-price">Save</button>+ </div>+ </div>+ `;+ }).join('');++ // Add event listeners to all save buttons+ container.querySelectorAll('.btn-save-price').forEach(button => {+ button.addEventListener('click', handleSavePrice);+ });+}++// Event handler for saving a price+async function handleSavePrice(event) {+ const entry = event.target.closest('.skill-price-entry');+ const skillName = entry.dataset.skillName;+ const amountInput = entry.querySelector('.price-amount-input');+ const currencySelect = entry.querySelector('.price-currency-select');++ const amountInUSDC = parseFloat(amountInput.value);+ if (isNaN(amountInUSDC) || amountInUSDC < 0) {+ showToast('Invalid amount', 'error');+ return;+ }++ const payload = {+ skill_name: skillName,+ amount: Math.round(amountInUSDC * 1e6), // Convert to lamports+ currency_mint: currencySelect.value+ };++ try {+ const response = await fetch(`/api/agents/${currentAgentId}/skills/prices`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', /* ...auth headers */ },+ body: JSON.stringify(payload)+ });++ if (!response.ok) {+ const { error } = await response.json();+ throw new Error(error || 'Failed to save price');+ }++ showToast(`${skillName} price updated!`, 'success');+ } catch (err) {+ showToast(err.message, 'error');+ }+}+```diff --git a/docs/monetization/04_api_for_saving_prices.md b/docs/monetization/04_api_for_saving_prices.mdnew file mode 100644index 000000000..794c3458d--- /dev/null+++ b/docs/monetization/04_api_for_saving_prices.md@@ -0,0 +1,74 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 04: API for Saving Skill Prices++## Objective+Create a secure backend API endpoint for agent creators to save or update the prices for their skills.++## Explanation+The UI for setting skill prices needs a backend endpoint to persist the data. This endpoint must be secure, ensuring that only the owner of an agent can modify its skill prices. It will receive a payload of skill prices, validate it, and update the `agent_skill_prices` table.++## Instructions+1. **Create the API File:**+ * Create a new API file, for example, `api/agents/skill-prices.js` or add a new action to an existing agent-related dispatcher. The route could be `POST /api/agents/:id/skill-prices`.++2. **Implement the Endpoint Logic:**+ * **Authentication:** The endpoint must first authenticate the user and retrieve their ID.+ * **Authorization:** It must verify that the authenticated user is the owner of the agent specified in the URL (`:id`).+ * **Validation:** It should validate the incoming payload. The payload should be a JSON object where keys are skill names and values are objects containing `amount` and `currency_mint`. Use a library like `zod` for robust validation.+ * **Database Operation:** For each skill price in the payload, perform an "upsert" operation on the `agent_skill_prices` table. If a price for that agent and skill already exists, update it. If not, insert a new row. This is a perfect use case for PostgreSQL's `ON CONFLICT` clause.++## Code Example (Vercel Serverless Function)++```javascript+// Example in: /api/agents/[agentId]/skill-prices.js+import { z } from 'zod';+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { error, json, wrap } from '../../_lib/http.js';+import { parse } from '../../_lib/validate.js';++// Define the schema for a single price entry+const PriceSchema = z.object({+ amount: z.number().int().positive(),+ currency_mint: z.string().min(32).max(44), // Solana public key validation+});++// The incoming body should be a map of skill names to price objects+const BodySchema = z.record(z.string(), PriceSchema);++export default wrap(async (req, res) => {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized');++ const agentId = req.query.agentId;+ const rawBody = await req.json();+ const pricesToUpdate = parse(BodySchema, rawBody);++ // 1. Verify ownership of the agent+ const [agent] = await sql`+ SELECT id FROM agent_identities+ WHERE id = ${agentId} AND user_id = ${user.id} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'Agent not found or you do not have permission.');++ // 2. Perform the upsert operation for all prices in a single transaction+ await sql.begin(async sql => {+ for (const [skillName, price] of Object.entries(pricesToUpdate)) {+ await sql`+ INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)+ VALUES (${agentId}, ${skillName}, ${price.amount}, ${price.currency_mint})+ ON CONFLICT (agent_id, skill_name)+ DO UPDATE SET+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ updated_at = NOW();+ `;+ }+ });++ return json(res, 200, { success: true, message: 'Skill prices updated.' });+});+```diff --git a/docs/monetization/05-create-purchase-skill-button.md b/docs/monetization/05-create-purchase-skill-button.mdnew file mode 100644index 000000000..f7a443e83--- /dev/null+++ b/docs/monetization/05-create-purchase-skill-button.md@@ -0,0 +1,98 @@+# Prompt 5: Create "Purchase Skill" Button++## Status+- [ ] Not Started++## Objective+Add a "Purchase" button for priced skills on the agent detail page and a modal to confirm the purchase.++## Explanation+With the front-end now able to display skill prices, the next step is to provide users with a clear call-to-action to initiate a purchase. This prompt covers adding the button and a confirmation modal.++## Instructions+1. **Modify the Skill Rendering Logic:**+ * In `src/marketplace.js` within the `renderDetail` function, update the skill rendering logic.+ * For skills that have a price, instead of just a badge, render a "Purchase" button.+ * The button should include `data-` attributes to store the skill name, price, and currency mint, which will be needed to initiate the transaction.++2. **Create a Purchase Confirmation Modal:**+ * Add a hidden modal to your main HTML (`app.html` or `marketplace.html`).+ * The modal should display the details of the skill being purchased (name, price) and include "Confirm" and "Cancel" buttons.++3. **Implement Button Logic:**+ * Add a click event listener to the "Purchase" buttons.+ * When a button is clicked, read the `data-` attributes and populate the confirmation modal with the correct information, then display the modal.++## Code Example (Frontend - `src/marketplace.js`)+```javascript+// Inside renderDetail function+const skillPrices = a.skill_prices || {};+$('d-skills').innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ let actionElement;+ if (price) {+ const priceDisplay = `${(price.amount / 1e6).toFixed(2)} USDC`;+ actionElement = `<button class="purchase-skill-btn"+ data-skill-name="${escapeHtml(name)}"+ data-price-amount="${price.amount}"+ data-currency-mint="${price.currency_mint}">+ Purchase for ${priceDisplay}+ </button>`;+ } else {+ actionElement = `<span class="price-badge price-free">Free</span>`;+ }+ return `<div class="skill-entry">+ <span>${escapeHtml(name)}</span>+ ${actionElement}+ </div>`;+ }).join('')+ : '<div>This Agent has no skills defined.</div>';++// Add event listeners after rendering+document.querySelectorAll('.purchase-skill-btn').forEach(button => {+ button.addEventListener('click', handlePurchaseClick);+});+```++## Code Example (HTML for Modal)+```html+<!-- Add to app.html or marketplace.html -->+<div id="purchase-confirm-modal" class="modal-hidden">+ <div class="modal-content">+ <h2>Confirm Purchase</h2>+ <p>You are about to purchase the skill: <b id="modal-skill-name"></b></p>+ <p>Price: <b id="modal-skill-price"></b></p>+ <div class="modal-actions">+ <button id="modal-confirm-btn">Confirm</button>+ <button id="modal-cancel-btn">Cancel</button>+ </div>+ </div>+</div>+```++## Code Example (Event Handling)+```javascript+function handlePurchaseClick(event) {+ const button = event.currentTarget;+ const skillName = button.dataset.skillName;+ const priceAmount = button.dataset.priceAmount;+ const currencyMint = button.dataset.currencyMint;++ // Populate and show the modal+ document.getElementById('modal-skill-name').textContent = skillName;+ document.getElementById('modal-skill-price').textContent = `${(priceAmount / 1e6).toFixed(2)} USDC`;+ document.getElementById('purchase-confirm-modal').classList.remove('modal-hidden');++ // Store data for the transaction+ document.getElementById('modal-confirm-btn').dataset.skillData = JSON.stringify({+ skillName, priceAmount, currencyMint+ });+}++// Add event listener for the cancel button to hide the modal+document.getElementById('modal-cancel-btn').addEventListener('click', () => {+ document.getElementById('purchase-confirm-modal').classList.add('modal-hidden');+});+```diff --git a/docs/monetization/05-ui-purchase-skill-button.md b/docs/monetization/05-ui-purchase-skill-button.mdnew file mode 100644index 000000000..ea37ff6f6--- /dev/null+++ b/docs/monetization/05-ui-purchase-skill-button.md@@ -0,0 +1,48 @@+---+status: not-started+---++# Prompt 5: UI for "Purchase Skill" Button++## Objective+Add a "Purchase Skill" button to the agent detail page for skills that are not free.++## Explanation+To allow users to buy skills, a clear call-to-action is needed. This button will be displayed next to paid skills that the user has not yet purchased, and it will trigger the payment flow.++## Instructions+1. **Modify the Frontend UI:**+ * In `src/marketplace.js`, in the `renderDetail` function, update the skill rendering logic.+ * For each skill, check if it's paid and if the current user has already purchased it.+ * If the skill is paid and not purchased, display a "Purchase" or "Unlock" button instead of the price badge.+ * If the skill is free or already purchased, display the "Free" or "Owned" badge.++2. **Button State:**+ * The button should be clearly visible and clickable.+ * Add a `data-skill-name` attribute to the button to identify which skill is being purchased.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// Inside renderDetail function, an updated version of the skill rendering logic+const skillPrices = a.skill_prices || {};+const ownedSkills = user.owned_skills || []; // Assuming this data is available++$('d-skills').innerHTML = skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];++ let badge;+ if (price) {+ if (ownedSkills.includes(name)) {+ badge = `<span class="price-badge price-owned">Owned</span>`;+ } else {+ badge = `<button class="purchase-btn" data-skill-name="${name}">Purchase</button>`;+ }+ } else {+ badge = `<span class="price-badge price-free">Free</span>`;+ }++ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+}).join(' ');+```diff --git a/docs/monetization/05_ui_for_purchasing.md b/docs/monetization/05_ui_for_purchasing.mdnew file mode 100644index 000000000..4e1f1234e--- /dev/null+++ b/docs/monetization/05_ui_for_purchasing.md@@ -0,0 +1,116 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 05: UI for Purchasing a Skill++## Objective+On the agent detail page, replace the static price badge for paid skills with an interactive "Purchase" button.++## Explanation+Displaying the price is the first step. The next is to allow users to initiate a purchase. This involves changing the UI from a passive display to an active one. When a user clicks the "Purchase" button, it should trigger the on-chain purchase flow. For this task, we will focus only on creating the button and its initial states.++## Instructions+1. **Identify User's Owned Skills:**+ * The API that fetches agent details for the marketplace view should also determine which skills the *currently authenticated user* already owns.+ * This requires a new database query to check the `user_purchased_skills` table (which we will create in a later prompt). For now, you can assume the API returns a list of owned skill names, e.g., `agent.owned_skills: ["skill1", "skill2"]`.++2. **Update the UI in `src/marketplace.js`:**+ * In the `renderDetail` function, where skills are rendered, implement conditional logic for each skill:+ * If the skill is free, show a "Free" badge.+ * If the skill is paid and the user already owns it, show an "Owned" badge or checkmark.+ * If the skill is paid and the user does not own it, show a "Purchase" button with the price.++3. **Button Styling:**+ * Add CSS for the new "Purchase" button and "Owned" badge to make them clear and visually appealing.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// Inside renderDetail function+const skillPrices = a.skill_prices || {};+const ownedSkills = new Set(a.owned_skills || []); // Assume this is passed from the API++$('d-skills').innerHTML = skillsArr.map(s => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ let badgeHtml = '';++ if (price) {+ if (ownedSkills.has(name)) {+ badgeHtml = `<span class="skill-badge owned">✓ Owned</span>`;+ } else {+ const priceInUsdc = (price.amount / 1e6).toFixed(2);+ badgeHtml = `<button class="btn btn-purchase" data-skill-name="${name}" data-agent-id="${a.id}">+ Purchase for ${priceInUsdc} USDC+ </button>`;+ }+ } else {+ badgeHtml = `<span class="skill-badge free">Free</span>`;+ }++ return `<div class="skill-entry">+ <span class="skill-name">${escapeHtml(name)}</span>+ ${badgeHtml}+ </div>`;+}).join('');++// Add event listener for purchase buttons+document.getElementById('d-skills').addEventListener('click', (e) => {+ if (e.target.matches('.btn-purchase')) {+ const skillName = e.target.dataset.skillName;+ const agentId = e.target.dataset.agentId;+ // The purchase flow logic will be implemented in the next prompt+ console.log(`Initiating purchase for skill '${skillName}' from agent '${agentId}'`);+ e.target.disabled = true;+ e.target.textContent = 'Preparing...';+ }+});+```++## CSS Example++```css+/* Add to marketplace.css */+.skill-entry {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px;+ border-radius: 6px;+ background-color: #1a1a24; /* var(--panel2) */+ margin-bottom: 6px;+}++.skill-badge, .btn-purchase {+ flex-shrink: 0;+}++.btn-purchase {+ font-size: 12px;+ padding: 5px 10px;+ background-color: var(--accent);+ color: white;+ border: none;+ border-radius: 5px;+ cursor: pointer;+}++.btn-purchase:hover {+ filter: brightness(1.1);+}++.btn-purchase:disabled {+ opacity: 0.6;+ cursor: not-allowed;+}++.skill-badge.owned {+ color: #4ade80; /* var(--ok) */+ font-weight: 600;+}++.skill-badge.free {+ color: #888; /* var(--muted) */+}+```diff --git a/docs/monetization/06-ui-payment-modal.md b/docs/monetization/06-ui-payment-modal.mdnew file mode 100644index 000000000..884a45bd8--- /dev/null+++ b/docs/monetization/06-ui-payment-modal.md@@ -0,0 +1,45 @@+---+status: not-started+---++# Prompt 6: UI Payment Modal++## Objective+Design and implement a payment confirmation modal that appears when a user clicks the "Purchase Skill" button.++## Explanation+A modal is an excellent way to provide a focused and clear payment experience. This modal will display the details of the skill being purchased, the price, and a final confirmation button to initiate the transaction.++## Instructions+1. **Create the Modal HTML:**+ * In `marketplace.html`, add the HTML structure for a modal. It should be hidden by default.+ * The modal should have a header, body, and footer.+ * The body should contain placeholders for the skill name, price, and other details.+ * The footer should have "Cancel" and "Confirm Purchase" buttons.++2. **Implement JavaScript Logic:**+ * In `src/marketplace.js`, add an event listener for clicks on the "Purchase" buttons.+ * When a button is clicked, populate the modal with the correct skill information and display it.+ * The "Confirm Purchase" button will trigger the blockchain transaction.++## Code Example (HTML - `marketplace.html`)++```html+<div id="payment-modal" class="modal-overlay hidden">+ <div class="modal">+ <div class="modal-header">+ <h3>Confirm Purchase</h3>+ <button id="close-payment-modal">×</button>+ </div>+ <div class="modal-body">+ <p>You are about to purchase the skill:</p>+ <h4 id="modal-skill-name"></h4>+ <p>Price: <strong id="modal-skill-price"></strong></p>+ </div>+ <div class="modal-footer">+ <button id="cancel-purchase" class="btn">Cancel</button>+ <button id="confirm-purchase" class="btn btn-primary">Confirm</button>+ </div>+ </div>+</div>+```diff --git a/docs/monetization/06_db_schema_for_purchases.md b/docs/monetization/06_db_schema_for_purchases.mdnew file mode 100644index 000000000..005c86369--- /dev/null+++ b/docs/monetization/06_db_schema_for_purchases.md@@ -0,0 +1,62 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 06: Database Schema for Purchased Skills++## Objective+Create the necessary database table to track which users have purchased which skills.++## Explanation+To manage access to paid skills, we need to record every successful purchase. A `user_purchased_skills` table will create a permanent record linking a user to a specific agent's skill they have acquired. This table is critical for the access control logic that will be built later.++## Instructions+1. **Design the Table:**+ * Create a new table named `user_purchased_skills`.+ * The table should have the following columns:+ * `id`: Primary key (UUID or SERIAL).+ * `user_id`: Foreign key referencing the `users` table.+ * `agent_id`: Foreign key referencing the `agent_identities` table.+ * `skill_name`: A text field for the name of the skill.+ * `purchase_tx_signature`: The on-chain transaction signature of the purchase, for auditing purposes.+ * `price_amount`: The amount paid (in lamports or smallest unit).+ * `price_currency_mint`: The currency used for the purchase.+ * `created_at`: Timestamp of purchase.+ * Add a unique constraint on (`user_id`, `agent_id`, `skill_name`) to prevent duplicate purchase records.++2. **Write the SQL Migration:**+ * Create a new SQL migration file.+ * Write the `CREATE TABLE` statement based on the design.+ * Add indexes on `user_id` and `agent_id` to speed up lookups for checking skill ownership.++## SQL Example++Here is the PostgreSQL `CREATE TABLE` statement.++```sql+CREATE TABLE IF NOT EXISTS user_purchased_skills (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id UUID NOT NULL,+ agent_id UUID NOT NULL,+ skill_name VARCHAR(255) NOT NULL,+ purchase_tx_signature VARCHAR(128) NOT NULL,+ price_amount BIGINT NOT NULL,+ price_currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ CONSTRAINT fk_user+ FOREIGN KEY(user_id)+ REFERENCES users(id)+ ON DELETE CASCADE,++ CONSTRAINT fk_agent+ FOREIGN KEY(agent_id)+ REFERENCES agent_identities(id)+ ON DELETE CASCADE,++ UNIQUE (user_id, agent_id, skill_name)+);++CREATE INDEX idx_user_purchased_skills_user_id ON user_purchased_skills(user_id);+CREATE INDEX idx_user_purchased_skills_agent_id ON user_purchased_skills(agent_id);+```diff --git a/docs/monetization/07-solana-payment-integration.md b/docs/monetization/07-solana-payment-integration.mdnew file mode 100644index 000000000..b0f5f28c0--- /dev/null+++ b/docs/monetization/07-solana-payment-integration.md@@ -0,0 +1,50 @@+---+status: not-started+---++# Prompt 7: Solana Payment Integration++## Objective+Integrate the Solana wallet-adapter to process skill purchase transactions on the Solana blockchain.++## Explanation+To handle payments in a decentralized way, we will use the Solana wallet-adapter to connect to the user's wallet (like Phantom) and request them to sign and send the transaction.++## Instructions+1. **Add Wallet-Adapter Dependencies:**+ * Include the necessary wallet-adapter scripts in `marketplace.html`.+ * You will need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-wallets`, and `@solana/web3.js`.++2. **Implement Connection Logic:**+ * In `src/marketplace.js`, add a "Connect Wallet" button and the logic to connect to the user's wallet.+ * Store the user's public key when they connect.++3. **Implement the Purchase Transaction:**+ * When the user confirms the purchase in the modal, construct a Solana transaction.+ * The transaction will transfer the required amount of SOL or SPL tokens (like USDC) from the user's wallet to the creator's wallet.+ * Use the wallet-adapter to ask the user to sign and send the transaction.++## Code Example (JavaScript - `src/marketplace.js`)++```javascript+// Inside the 'confirm-purchase' button's event listener++const provider = getProvider(); // From your wallet-adapter setup+const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));++const transaction = new solanaWeb3.Transaction().add(+ solanaWeb3.SystemProgram.transfer({+ fromPubkey: user.publicKey,+ toPubkey: new solanaWeb3.PublicKey(creatorWalletAddress),+ lamports: price.amount,+ })+);++try {+ const signature = await provider.sendTransaction(transaction, connection);+ await connection.confirmTransaction(signature, 'processed');+ // On success, notify the backend to unlock the skill+} catch (error) {+ console.error("Transaction failed", error);+}+```diff --git a/docs/monetization/07_api_purchase_prep.md b/docs/monetization/07_api_purchase_prep.mdnew file mode 100644index 000000000..dfa0762d9--- /dev/null+++ b/docs/monetization/07_api_purchase_prep.md@@ -0,0 +1,83 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 07: Backend API for Purchase Preparation++## Objective+Create a backend endpoint that prepares an on-chain transaction for a user to purchase a skill.++## Explanation+When a user clicks the "Purchase" button, the frontend needs to request a transaction from the backend. This endpoint will not execute the transaction but will prepare it. It will construct a Solana transaction that, when signed by the user, will transfer the correct amount of USDC from the user's wallet to the agent creator's wallet. This is a crucial step for security and a smooth user experience.++## Instructions+1. **Create the API Endpoint:**+ * Create a new file or handler, e.g., `POST /api/skills/purchase-prep`.++2. **Implement the Logic:**+ * **Authentication:** Ensure the user is authenticated.+ * **Input Validation:** The request body should contain the `agent_id` and `skill_name`. Validate these inputs.+ * **Fetch Data:**+ * Retrieve the skill's price from the `agent_skill_prices` table.+ * Retrieve the agent creator's wallet address from the `agent_identities` table (`meta.onchain.wallet`).+ * Retrieve the buyer's wallet address from their session or a trusted source.+ * **Construct Transaction:**+ * Using the Solana Web3.js library (`@solana/web3.js`), create a new transaction.+ * The transaction should contain one primary instruction: a `spl-token` transfer from the buyer's USDC associated token account (ATA) to the creator's USDC ATA.+ * The amount should be the price fetched from the database.+ * The transaction's `feePayer` should be set to the buyer's public key.+ * **Serialization:**+ * Serialize the transaction without signing it.+ * Return the serialized transaction as a base64-encoded string. This is what the frontend will receive and pass to the user's wallet to be signed.+ * **Record Preparation:**+ * It's good practice to store a temporary record of this preparation step (e.g., in Redis or a `skill_purchase_preparations` table) with an expiration time, to prevent replay attacks and to link it to the confirmation step.++## Code Example (Vercel Serverless Function)++```javascript+import { Connection, PublicKey, Transaction } from '@solana/web3.js';+import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';+import { sql } from '../../_lib/db.js';+// ... other imports++export default wrap(async (req, res) => {+ // ... auth and validation+ const { agent_id, skill_name } = req.body;+ const user = await getSessionUser(req);+ const buyerPublicKey = new PublicKey(user.wallet_address);++ // 1. Fetch skill price and creator wallet+ const [skillPrice] = await sql`...`;+ const [agent] = await sql`...`;+ const creatorPublicKey = new PublicKey(agent.meta.onchain.wallet);+ const usdcMint = new PublicKey(skillPrice.currency_mint);++ // 2. Setup connection and ATAs+ const connection = new Connection(rpcUrl('mainnet-beta'));+ const buyerAta = await getOrCreateAssociatedTokenAccount(connection, buyerPublicKey, usdcMint, buyerPublicKey);+ const creatorAta = await getOrCreateAssociatedTokenAccount(connection, buyerPublicKey, usdcMint, creatorPublicKey);++ // 3. Create transaction+ const { blockhash } = await connection.getLatestBlockhash();+ const tx = new Transaction({+ feePayer: buyerPublicKey,+ recentBlockhash: blockhash,+ });++ tx.add(+ createTransferInstruction(+ buyerAta.address,+ creatorAta.address,+ buyerPublicKey,+ skillPrice.amount+ )+ );++ // 4. Serialize and return+ const serializedTx = tx.serialize({ requireAllSignatures: false }).toString('base64');++ // 5. Save prep record (omitted for brevity)++ return json(res, 200, { transaction: serializedTx });+});+```diff --git a/docs/monetization/08-backend-api-process-payment.md b/docs/monetization/08-backend-api-process-payment.mdnew file mode 100644index 000000000..a55480b9d--- /dev/null+++ b/docs/monetization/08-backend-api-process-payment.md@@ -0,0 +1,51 @@+---+status: not-started+---++# Prompt 8: Backend API to Process Payments++## Objective+Create a backend endpoint to verify and record a skill purchase transaction after it has been confirmed on the blockchain.++## Explanation+After a user's transaction is successfully sent to the Solana network, the frontend needs to notify the backend. The backend will then verify the transaction and, if it's valid, record that the user now owns the skill. This prevents users from accessing paid skills without a valid payment.++## Instructions+1. **Create a New API Endpoint:**+ * Create a new endpoint, for example, `POST /api/marketplace/skills/purchase`.+ * This endpoint will receive the transaction signature and the skill name being purchased.++2. **Verify the Transaction:**+ * In the backend, use the Solana web3 library to fetch the transaction details using the signature.+ * Verify that the transaction is valid:+ * It transferred the correct amount of the correct currency.+ * The funds were sent from the user's wallet to the correct creator's wallet.+ * The transaction has been successfully confirmed.++3. **Record the Purchase:**+ * If the transaction is valid, insert a new record into the `user_skill_purchases` table to grant the user ownership of the skill.++## Code Example (Backend - Node.js with `@solana/web3.js`)++```javascript+// POST /api/marketplace/skills/purchase+router.post('/skills/purchase', async (req, res) => {+ const { signature, skillName, agentId } = req.body;+ const userId = req.session.userId;++ // 1. Fetch transaction details from the blockchain+ const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));+ const tx = await connection.getTransaction(signature);++ // 2. Verify the transaction's details (amount, recipient, etc.)+ const isValid = verifyTransaction(tx, { /* expected details */ });++ if (isValid) {+ // 3. Record the purchase in the database+ await db.recordSkillPurchase(userId, skillName, agentId);+ res.status(200).json({ success: true });+ } else {+ res.status(400).json({ error: 'Invalid transaction' });+ }+});+```diff --git a/docs/monetization/08_frontend_signing_logic.md b/docs/monetization/08_frontend_signing_logic.mdnew file mode 100644index 000000000..de39a696e--- /dev/null+++ b/docs/monetization/08_frontend_signing_logic.md@@ -0,0 +1,97 @@+---+status: not-started+last_updated: 2026-05-04+---+# Prompt 08: Frontend Logic for Signing and Sending Transaction++## Objective+Implement the client-side logic that takes the prepared transaction from the backend, asks the user to sign it with their wallet, and sends it to the Solana network.++## Explanation+This is the core of the on-chain interaction from the user's perspective. The frontend will receive the base64-encoded transaction, deserialize it, prompt the user for a signature via their connected wallet (e.g., Phantom), and then broadcast the signed transaction to the blockchain.++## Instructions+1. **Integrate with Wallet Adapter:**+ * Ensure a Solana wallet adapter (like `@solana/wallet-adapter-react` or a vanilla equivalent) is integrated into your frontend to manage wallet connections.++2. **Handle the "Purchase" Button Click:**+ * In `src/marketplace.js`, attach an async function to the purchase button's click event.++3. **Implement the Purchase Flow:**+ * **Step 1: Fetch Prepared Transaction:**+ * When the button is clicked, call the `POST /api/skills/purchase-prep` endpoint created in the previous prompt.+ * **Step 2: Deserialize:**+ * Take the base64 `transaction` string from the response and deserialize it into a `Transaction` object using the Solana Web3.js library.+ * **Step 3: Sign Transaction:**+ * Use the connected wallet's `signTransaction` method to ask the user to sign the transaction. This will pop up the wallet interface. Handle potential user rejection of the signature.+ * **Step 4: Send Transaction:**+ * If signing is successful, use the `connection.sendRawTransaction` method to broadcast the signed transaction to the network.+ * **Step 5: Confirm Transaction:**+ * Wait for the transaction to be confirmed by the network using `connection.confirmTransaction`. This gives the user feedback that their purchase was successful.+ * **Step 6: Finalize with Backend:**+ * After on-chain confirmation, call a new backend endpoint (`/api/skills/purchase-confirm`, to be built next) with the transaction signature. This will record the purchase in our database.++## Code Example (`src/marketplace.js`)++```javascript+import { Connection, Transaction } from '@solana/web3.js';+// Assume `wallet` is the connected wallet object from a wallet adapter+// Assume `connection` is an initialized Connection object++async function handlePurchase(agentId, skillName, button) {+ try {+ // 1. Prepare+ button.disabled = true;+ button.textContent = 'Preparing...';+ const prepRes = await fetch('/api/skills/purchase-prep', {+ method: 'POST',+ body: JSON.stringify({ agent_id: agentId, skill_name: skillName }),+ headers: { 'Content-Type': 'application/json' }+ });+ if (!prepRes.ok) throw new Error('Failed to prepare transaction.');+ const { transaction: base64Tx } = await prepRes.json();++ // 2. Deserialize+ const tx = Transaction.from(Buffer.from(base64Tx, 'base64'));++ // 3. Sign+ button.textContent = 'Please sign...';+ const signedTx = await wallet.signTransaction(tx);++ // 4. Send+ button.textContent = 'Sending...';+ const signature = await connection.sendRawTransaction(signedTx.serialize());++ // 5. Confirm+ button.textContent = 'Confirming...';+ await connection.confirmTransaction(signature, 'confirmed');++ // 6. Finalize with our backend+ const confirmRes = await fetch('/api/skills/purchase-confirm', {+ method: 'POST',+ body: JSON.stringify({ agent_id: agentId, skill_name: skillName, signature }),+ headers: { 'Content-Type': 'application/json' }+ });+ if (!confirmRes.ok) throw new Error('Failed to confirm purchase with server.');++ // 7. Update UI+ button.textContent = '✓ Owned';+ button.classList.add('owned');+ // Prevent further clicks+ button.replaceWith(button.cloneNode(true));++ } catch (err) {+ console.error('Purchase failed:', err);+ button.disabled = false;+ button.textContent = 'Purchase Failed - Retry';+ }+}++// Modify the event listener from Prompt 5+document.getElementById('d-skills').addEventListener('click', (e) => {+ if (e.target.matches('.btn-purchase:not(:disabled)')) {+ const { skillName, agentId } = e.target.dataset;+ handlePurchase(agentId, skillName, e.target);+ }+});+```diff --git a/docs/monetization/09-db-schema-user-purchases.md b/docs/monetization/09-db-schema-user-purchases.mdnew file mode 100644index 000000000..00010522b--- /dev/null+++ b/docs/monetization/09-db-schema-user-purchases.md@@ -0,0 +1,39 @@+---+status: not-started+---++# Prompt 9: Database Schema for User Purchases++## Objective+Create a database table to track which users have purchased which skills.++## Explanation+This table is essential for managing skill ownership. It will provide a record of every successful purchase, allowing the application to check if a user has access to a particular paid skill.++## Instructions+1. **Design the Table:**+ * Create a new table named `user_skill_purchases`.+ * The table should have the following columns:+ * `id`: Primary key.+ * `user_id`: Foreign key referencing the `users` table.+ * `agent_id`: Foreign key referencing the `agents` table.+ * `skill_name`: The name of the skill that was purchased.+ * `transaction_signature`: The Solana transaction signature of the purchase.+ * `created_at`: Timestamp.++2. **Create a Migration:**+ * Use your database migration tool to create and apply a migration for the `user_skill_purchases` table.++## SQL Example++```sql+CREATE TABLE user_skill_purchases (+ id SERIAL PRIMARY KEY,+ user_id UUID NOT NULL REFERENCES users(id),+ agent_id UUID NOT NULL REFERENCES agents(id),+ skill_name VARCHAR(255) NOT NULL,+ transaction_signature VARCHAR(255) NOT NULL,+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ UNIQUE(user_id, agent_id, skill_name)+);+```diff --git a/docs/monetization/10-access-control-for-skills.md b/docs/monetization/10-access-control-for-skills.mdnew file mode 100644index 000000000..9fcdbc1fa--- /dev/null+++ b/docs/monetization/10-access-control-for-skills.md@@ -0,0 +1,22 @@+---+status: not-started+---++# Prompt 10: Access Control for Paid Skills++## Objective+Implement a system to ensure that only users who have purchased a skill can use it.++## Explanation+This is a critical part of the monetization feature. The system needs to check for ownership before allowing the execution of a paid skill. This can be done at the API gateway or within the agent's core logic.++## Instructions+1. **Create a Middleware:**+ * Implement a middleware that sits in front of the skill execution endpoint.+ * The middleware should extract the user's ID, the agent ID, and the skill name from the request.++2. **Check for Ownership:**+ * In the middleware, query the `user_skill_purchases` table to see if a record exists for the user, agent, and skill.+ * Also, check if the skill is free by looking at the `agent_skill_prices` table.+ * If the skill is free or if the user owns it, allow the request to proceed.+ * If the skill is paid and the user does not own it, return a `403 Forbidden` or `402 Payment Required` error.diff --git a/docs/monetization/11-creator-payouts-dashboard.md b/docs/monetization/11-creator-payouts-dashboard.mdnew file mode 100644index 000000000..ba56df300--- /dev/null+++ b/docs/monetization/11-creator-payouts-dashboard.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 11: Creator Payouts & Dashboard++## Objective+Develop a system for creators to see their earnings and withdraw their funds.++## Explanation+Creators need a clear and transparent way to track their sales and access their earnings. This involves building a creator dashboard and a secure withdrawal process.++## Instructions+1. **Create a Creator Dashboard Page:**+ * Design a new page for creators to view their sales data.+ * Display total earnings, sales per skill, and a list of recent transactions.++2. **Implement a Payouts API:**+ * Create a backend process for handling creator withdrawals.+ * This might involve a smart contract that holds the funds and allows creators to claim their share, or a centralized system that processes payouts periodically.++3. **Security:**+ * Ensure the payout process is secure and that only the legitimate creator can withdraw their funds. This might involve connecting their wallet and signing a message to verify ownership.diff --git a/docs/monetization/12-platform-fee-implementation.md b/docs/monetization/12-platform-fee-implementation.mdnew file mode 100644index 000000000..38a8370a3--- /dev/null+++ b/docs/monetization/12-platform-fee-implementation.md@@ -0,0 +1,44 @@+---+status: not-started+---++# Prompt 12: Platform Fee Implementation++## Objective+Implement a platform fee on every skill purchase transaction.++## Explanation+To ensure the sustainability of the platform, a small percentage of each sale will be collected as a platform fee. This needs to be calculated and transferred during the payment process.++## Instructions+1. **Modify the Payment Transaction:**+ * In `src/marketplace.js`, when constructing the purchase transaction, add a second instruction.+ * The first instruction will transfer the creator's share of the payment to their wallet.+ * The second instruction will transfer the platform's fee to the platform's treasury wallet.++2. **Configuration:**+ * The platform fee percentage should be configurable and stored in a secure location.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// Inside the purchase logic+const platformFee = price.amount * 0.05; // 5% fee+const creatorGets = price.amount - platformFee;++const transaction = new solanaWeb3.Transaction()+ .add(+ solanaWeb3.SystemProgram.transfer({+ fromPubkey: user.publicKey,+ toPubkey: new solanaWeb3.PublicKey(creatorWalletAddress),+ lamports: creatorGets,+ })+ )+ .add(+ solanaWeb3.SystemProgram.transfer({+ fromPubkey: user.publicKey,+ toPubkey: new solanaWeb3.PublicKey(platformTreasuryAddress),+ lamports: platformFee,+ })+ );+```diff --git a/docs/monetization/13-spl-token-payments.md b/docs/monetization/13-spl-token-payments.mdnew file mode 100644index 000000000..4efc804b2--- /dev/null+++ b/docs/monetization/13-spl-token-payments.md@@ -0,0 +1,23 @@+---+status: not-started+---++# Prompt 13: Support for SPL Token Payments++## Objective+Extend the payment system to support payments with SPL tokens, such as USDC.++## Explanation+Many users prefer to transact with stablecoins like USDC. Supporting SPL tokens will make the platform more accessible and user-friendly.++## Instructions+1. **Modify the Frontend Transaction:**+ * In `src/marketplace.js`, the transaction logic needs to be updated.+ * Instead of `SystemProgram.transfer`, you will use the `Token.createTransferInstruction` from the `@solana/spl-token` library.+ * This requires knowing the user's and the creator's token accounts for the specific SPL token.++2. **Associated Token Accounts:**+ * You will need to find the associated token accounts for the sender and receiver. If they don't exist, you might need to include instructions to create them in the transaction.++3. **Backend Verification:**+ * The backend payment verification logic must also be updated to correctly parse and validate SPL token transfers.diff --git a/public/marketplace.css b/public/marketplace.cssindex 4fff72c77..19500781c 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -998,6 +998,26 @@ body.market-page {background: var(--mk-panel);border: 1px solid var(--mk-border-2);border-radius: 16px;+.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);+}+padding: 28px;width: 100%;max-width: 460px;diff --git a/public/pumpfun.html b/public/pumpfun.htmlindex 07d99af24..7567d3159 100644--- a/public/pumpfun.html+++ b/public/pumpfun.html@@ -665,7 +665,7 @@<option value="">(no emotion)</option>${config.emotions.map(emotion => `<option value="${emotion}" ${config.settings.actions[actionKey]?.emotion === emotion ? 'selected' : ''}>${emotion}</option>`).join('')}</select>- <input type="text" id="config-tts-${actionKey}" data-action="${actionKey}" data-field="tts" placeholder="TTS message (e.g. Wow, a whale!)" value="${config.settings.actions[actionKey]?.tts || ''}">+ <input type="text" id="config-tts-${actionKey}" data-action="${actionKey}" data-field="tts" placeholder="TTS text — use {name}, {sol}, {mc}" value="${(config.settings.actions[actionKey]?.tts || '').replace(/"/g, '"')}"></div>`).join('')}</div>@@ -1072,6 +1072,8 @@});chips.appendChild(btn);});+ // Repopulate animation dropdowns if the config modal is already open+ if (config.modal.dataset.open === 'true') renderConfigBody();}});@@ -1136,7 +1138,6 @@if (data.type === 'events-batch') {data.events.forEach(handleEvent);if (data.replay) {- // add small visual gap between historical and live eventssetTimeout(() => {const div = document.createElement('div');div.style = 'margin: 6px 0; text-align: center; font-size: 10px; color: #444; text-transform: uppercase; letter-spacing: 0.08em;';@@ -1146,22 +1147,6 @@}return;}-- // Call sentiment analysis for new tokens- if (data.type === 'mint' && data.name) {- agent.skills.perform('analyze-sentiment', { text: data.name }).then(result => {- if (result.success) {- const card = feed.el.querySelector(`[data-mint="${data.mint}"]`);- if (card) {- const sentimentEl = card.querySelector('.evt-sentiment');- if (sentimentEl) {- sentimentEl.textContent = result.data.sentiment === 'Positive' ? '😊' : '😞';- }- }- }- });- }-handleEvent(data);};ws.onerror = (err) => console.error('[ws] error', err);@@ -1197,46 +1182,77 @@function narrateEvent(evt) {if (!params.narrate) return;- let text, anim;+const sol = evt.sol || 0;const mc = evt.market_cap_usd || 0;const name = evt.name || 'a token';+ // Map event to an action key + built-in defaults+ let actionKey = null;+ let defaultText = null;+ let defaultAnim = null;+if (evt.type === 'mint') {if (!params.announceMints) return;- text = `New token minted: ${name}!`;- anim = 'victory';+ actionKey = 'mint';+ defaultText = `New token minted: ${name}!`;+ defaultAnim = 'Victory';} else if (evt.type === 'trade') {if (evt.is_buy) {- if (sol > 50) { text = `Whale alert! Someone just bought ${sol.toFixed(1)} SOL of ${name}!`; anim = 'surprised'; }- else if (sol > 10) { text = `Big buy! ${sol.toFixed(1)} SOL of ${name}.`; anim = 'run'; }- else if (mc < 15000 && sol > 0.5) { text = `Here's a dip buy on ${name}.`; anim = 'yes'; }- else return; // don't narrate small buys- } else { // sell- if (sol > 50) { text = `Ouch, a whale just dumped ${sol.toFixed(1)} SOL of ${name}.`; anim = 'no'; }- else if (sol > 10) { text = `Big sell on ${name}.`; anim = 'headshake'; }- else return; // don't narrate small sells+ if (sol > 50) { actionKey = 'whale_buy'; defaultText = `Whale alert! ${sol.toFixed(1)} SOL into ${name}!`; defaultAnim = 'Surprised'; }+ else if (sol > 10) { actionKey = 'big_buy'; defaultText = `Big buy — ${sol.toFixed(1)} SOL of ${name}.`; defaultAnim = 'Running'; }+ else if (mc < 15000 && sol > 0.5) { actionKey = 'dip_buy'; defaultText = `Dip buy on ${name}.`; defaultAnim = 'Yes'; }+ else if (sol > 1) { actionKey = 'med_buy'; }+ else { actionKey = 'small_buy'; }+ } else {+ if (sol > 50) { actionKey = 'whale_sell'; defaultText = `Whale dump — ${sol.toFixed(1)} SOL out of ${name}.`; defaultAnim = 'No'; }+ else if (sol > 10) { actionKey = 'big_sell'; defaultText = `Big sell on ${name}.`; defaultAnim = 'Headshake'; }+ else if (sol > 1) { actionKey = 'med_sell'; }+ else { actionKey = 'small_sell'; }}} else if (evt.type === 'graduation') {- if (mc > 1_000_000) text = `Oh my god! ${name} just graduated and it's already over a million market cap!`;- else if (mc > 250_000) text = `Let's go! ${name} graduated to Raydium!`;- else text = `${name} made it to Raydium.`;- anim = 'victory';if (evt.audit?.rug_score?.risk_level === 'high') {- text = `Warning, ${name} looks like a rug pull. High risk score.`;- anim = 'no';+ actionKey = 'rug';+ defaultText = `Warning — ${name} looks like a rug. High risk score.`;+ defaultAnim = 'No';+ } else {+ actionKey = 'graduation';+ if (mc > 1_000_000) defaultText = `Oh my god! ${name} just graduated at over a million market cap!`;+ else if (mc > 250_000) defaultText = `Let's go! ${name} graduated to Raydium!`;+ else defaultText = `${name} made it to Raydium.`;+ defaultAnim = 'Victory';}+ } else if (evt.type === 'claim') {+ actionKey = 'claim';} else {- return; // unhandled event type+ return;}- if (anim) {- const animName = {- 'victory': 'Victory', 'yes': 'Yes', 'no': 'No', 'run': 'Running',- 'surprised': 'Surprised', 'headshake': 'Headshake'- }[anim] || anim;- const hasAnim = animations.includes(animName);- enqueue({ type: 'anim', name: hasAnim ? animName : 'Idle', duration: hasAnim ? 2500 : 500 });+ if (!actionKey) return;++ const actionCfg = config.settings.actions[actionKey];++ // Resolve animation: user-configured emotion → mapped animation → default → nothing+ let animName = defaultAnim;+ if (actionCfg?.emotion) {+ const mapped = config.settings.emotions[actionCfg.emotion];+ animName = mapped || actionCfg.emotion; // fall back to the emotion label itself+ }++ // Resolve TTS: user-configured template → default → nothing+ let text = defaultText;+ if (actionCfg?.tts) {+ text = actionCfg.tts+ .replace(/{name}/g, name)+ .replace(/{sol}/g, sol.toFixed(2))+ .replace(/{mc}/g, mc > 0 ? '$' + mc.toLocaleString(undefined, { maximumFractionDigits: 0 }) : '');+ }++ if (!animName && !text) return;++ if (animName) {+ const has = animations.includes(animName);+ enqueue({ type: 'anim', name: has ? animName : 'Idle', duration: has ? 2500 : 500 });}if (text) {enqueue({ type: 'say', text });@@ -1595,7 +1611,7 @@initSidePanel();connect();fetchFirstClaims();- setInterval(() => ws.send(JSON.stringify({ type: 'sol-price' })), 15_000);+ setInterval(() => { if (ws?.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'sol-price' })); }, 15_000);</script></body></html>\ No newline at end of filediff --git a/tasks/monetization-feature/01-display-priced-skills.md b/tasks/monetization-feature/01-display-priced-skills.mdindex 87fc7181a..4f41e44f2 100644--- a/tasks/monetization-feature/01-display-priced-skills.md+++ b/tasks/monetization-feature/01-display-priced-skills.md@@ -1,3 +1,7 @@+---+status: not-started+---+# Prompt 1: Display Priced Skills in Marketplace## Objectivediff --git a/tasks/monetization-feature/07-solana-wallet-adapter.md b/tasks/monetization-feature/07-solana-wallet-adapter.mdnew file mode 100644index 000000000..241b0fdd7--- /dev/null+++ b/tasks/monetization-feature/07-solana-wallet-adapter.md@@ -0,0 +1,77 @@+# Prompt 7: Integrate Solana Wallet Adapter++## Objective+Integrate the Solana Wallet Adapter into the marketplace page to enable users to connect their Solana wallets (like Phantom, Solflare, etc.).++## Explanation+To accept payments on the Solana blockchain, our web application needs to communicate with the user's wallet. The Solana Wallet Adapter is a suite of libraries that provides a standardized way to connect to various wallets, get the user's public key, and request transaction signatures. This is the foundation for our payment flow.++## Instructions+1. **Add Script Tags:**+ * Open `marketplace.html`.+ * In the `<head>` section, add script tags to import the necessary Wallet Adapter libraries from a CDN (like unpkg). You will need `wallet-adapter-base`, `wallet-adapter-solana`, and `wallet-adapter-wallets`. You should also include the CSS for the adapter's UI components.++2. **Initialize the Wallet Adapter:**+ * In `src/marketplace.js`, create a new function to initialize the wallet adapter.+ * Instantiate the wallets you want to support (e.g., `PhantomWalletAdapter`, `SolflareWalletAdapter`).+ * Create a `Connection` object pointing to the Solana cluster you're using (e.g., 'mainnet-beta' or 'devnet').+ * Use these to create the main wallet adapter instance.++3. **Render the Wallet Button:**+ * The wallet adapter library provides a pre-built UI component for a "Connect Wallet" button.+ * In your initialization code, create an instance of this button and append it to the `payment-wallet-area` in your payment modal.++4. **Listen for Connection Changes:**+ * The adapter emits events when a user connects or disconnects.+ * Add event listeners to update the UI accordingly. For instance, when a user connects, you can show their public key and change the button to "Disconnect." You should also enable the "Confirm Purchase" button.++## Code Example (`marketplace.html`)++Add these scripts and the link tag to the `<head>` of your `marketplace.html`.++```html+<!-- In <head> of marketplace.html -->+<link rel="stylesheet" href="https://unpkg.com/@solana/wallet-adapter-react-ui/styles.css" />++<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>+<script src="https://unpkg.com/@solana/wallet-adapter-base@latest/lib/index.iife.js"></script>+<script src="https://unpkg.com/@solana/wallet-adapter-wallets@latest/lib/index.iife.js"></script>+<script src="https://unpkg.com/@solana/wallet-adapter-react@latest/lib/index.iife.js"></script>+<script src="https://unpkg.com/@solana/wallet-adapter-react-ui@latest/lib/index.iife.js"></script>+```++## Code Example (`src/marketplace.js`)++```javascript+// Add these variables and functions to the top level of marketplace.js++const { Connection, clusterApiUrl } = solanaWeb3;+const { WalletAdapterBase } = solanaWalletAdapterBase;+const { getPhantomWallet, getSolflareWallet } = solanaWalletAdapterWallets;+const { WalletModalProvider, WalletMultiButton } = solanaWalletAdapterReactUi;++let solanaConnection;+let wallet; // This will hold our wallet adapter instance++function initWalletAdapter() {+ solanaConnection = new Connection(clusterApiUrl('mainnet-beta'));++ const wallets = [+ getPhantomWallet(),+ getSolflareWallet(),+ ];++ // The library is React-based, but we can use it imperatively.+ // This is a simplified, non-React setup.+ // A proper implementation would require a bit more work to integrate with a non-React app.++ // For now, let's create a simpler, custom connection flow in the next prompt.+ // The official components are difficult to use without React.++ console.log('Solana Wallet Adapter concept initialized.');+}++// In your main init() function, call initWalletAdapter();+```++**Correction & Simplification:** The official Solana Wallet Adapter UI libraries are heavily based on React, making them cumbersome to use in a vanilla JS project. The next prompt will focus on a simplified, custom implementation for connecting the wallet and signing the transaction, using the base adapter libraries without the UI components. This prompt serves to get the necessary scripts included in the project.diff --git a/tasks/monetization-feature/08-connect-wallet-button.md b/tasks/monetization-feature/08-connect-wallet-button.mdnew file mode 100644index 000000000..7a555b38c--- /dev/null+++ b/tasks/monetization-feature/08-connect-wallet-button.md@@ -0,0 +1,106 @@+# Prompt 8: Connect Wallet Button Logic++## Objective+Implement the logic for a custom "Connect Wallet" button inside the payment modal, abandoning the difficult-to-integrate React components from the previous prompt.++## Explanation+Since the pre-built UI components for the Solana Wallet Adapter are React-based, we'll create our own simple connection flow. This gives us more control and avoids pulling in a large framework. The flow will be:+1. User clicks our custom "Connect Wallet" button.+2. We'll attempt to connect to a wallet provider found in the browser (e.g., Phantom).+3. On success, we'll update the UI to show the user's wallet address and enable the payment button.++## Instructions+1. **Modify the Wallet Initialization:**+ * In `src/marketplace.js`, adjust the `initWalletAdapter` function. Instead of trying to render a React component, we will just prepare the adapter instances.++2. **Create the Connect Button Logic:**+ * Add an event listener to the `#payment-connect-wallet-btn` inside the `openPaymentModal` function (or a separate setup function).+ * When clicked, the handler should try to connect to the wallet adapter.+ * Use `wallet.connect().catch(...)` to handle connection errors gracefully.++3. **Update UI on Connection Status Change:**+ * Create a function, e.g., `updateWalletUI()`, that checks the wallet adapter's state (`wallet.connected`, `wallet.publicKey`).+ * If connected:+ * Hide the "Connect Wallet" button.+ * Display the user's public key (shortened for readability).+ * Show a "Disconnect" button.+ * Enable the "Confirm Purchase" button.+ * If disconnected:+ * Show the "Connect Wallet" button.+ * Hide the public key and disconnect button.+ * Disable the "Confirm Purchase" button.+ * Call this function after connecting/disconnecting and when the modal is first opened.++4. **Add Disconnect Logic:**+ * Add an event listener to the "Disconnect" button to call `wallet.disconnect()`.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// --- At the top of the file ---+const { Connection, clusterApiUrl } = solanaWeb3;+const { PhantomWalletAdapter } = solanaWalletAdapterWallets;++let solanaConnection;+let wallet; // Our single wallet adapter instance++// --- Initialization ---+function initWalletAdapter() {+ solanaConnection = new Connection(clusterApiUrl('mainnet-beta'));+ wallet = new PhantomWalletAdapter(); // We'll specifically use Phantom for simplicity++ // Listen for connection changes+ wallet.on('connect', () => {+ console.log('Wallet connected!');+ updateWalletUI();+ });+ wallet.on('disconnect', () => {+ console.log('Wallet disconnected!');+ updateWalletUI();+ });+}++// --- UI Update Logic ---+function updateWalletUI() {+ const walletArea = $('payment-wallet-area');+ const confirmBtn = $('payment-confirm-btn');++ if (wallet.connected) {+ const pubKey = wallet.publicKey.toBase58();+ walletArea.innerHTML = `+ <p>Connected: <strong>${pubKey.slice(0, 4)}...${pubKey.slice(-4)}</strong></p>+ <button class="btn-secondary" id="payment-disconnect-btn">Disconnect</button>+ `;+ $('payment-disconnect-btn').addEventListener('click', () => wallet.disconnect());+ confirmBtn.disabled = false;+ } else {+ walletArea.innerHTML = `+ <button class="btn-primary" id="payment-connect-wallet-btn">Connect Phantom Wallet</button>+ `;+ $('payment-connect-wallet-btn').addEventListener('click', async () => {+ const btn = $('payment-connect-wallet-btn');+ btn.textContent = 'Connecting...';+ btn.disabled = true;+ try {+ await wallet.connect();+ } catch (error) {+ console.error("Failed to connect wallet", error);+ btn.textContent = 'Connect Phantom Wallet'; // Reset on failure+ btn.disabled = false;+ }+ });+ confirmBtn.disabled = true;+ }+}++// --- In the main `init()` function ---+initWalletAdapter();++// --- When opening the modal ---+function openPaymentModal(intent, skillName) {+ // ... (previous code to populate skill name, price, etc.)++ updateWalletUI(); // Set the initial state of the wallet UI+ $('payment-modal-overlay').hidden = false;+}+```diff --git a/tasks/monetization-feature/09-construct-solana-transaction.md b/tasks/monetization-feature/09-construct-solana-transaction.mdnew file mode 100644index 000000000..a3f3b3e12--- /dev/null+++ b/tasks/monetization-feature/09-construct-solana-transaction.md@@ -0,0 +1,97 @@+# Prompt 9: Construct Solana Transaction++## Objective+On the frontend, write a function that constructs a Solana transaction to transfer the required amount of USDC from the user's wallet to the agent creator's wallet.++## Explanation+A Solana transaction is a set of instructions that the user must sign. For a simple SPL-token payment (like USDC), the main instruction is a `Token.createTransferInstruction`. This instruction needs several pieces of information:+- The user's (source) USDC token account address.+- The creator's (destination) USDC token account address.+- The user's main wallet address (the owner of the source account).+- The amount to transfer.+- The SPL Token Program ID.++Our task is to gather this information and build the transaction object, which we'll then pass to the wallet for signing in the next step. A key challenge is finding the user's and creator's *USDC-specific token accounts*, not just their main wallet addresses.++## Instructions+1. **Create a Transaction Builder Function:**+ * In `src/marketplace.js`, create a new `async` function called `buildUsdcTransferTransaction`.+ * It should accept the `intent` object (which contains the recipient's main wallet address, amount, and currency mint) and the `payerPublicKey` (the connected user's wallet public key).++2. **Find Associated Token Accounts (ATAs):**+ * The standard way to hold tokens on Solana is in "Associated Token Accounts." We can derive the address of these accounts if we have the main wallet address and the token mint address.+ * Use the `solanaWeb3.PublicKey.findProgramAddress` or a helper from `@solana/spl-token` to find the payer's and recipient's USDC ATAs. The `spl-token` library provides `getAssociatedTokenAddress`.++3. **Handle Missing Recipient ATA:**+ * The recipient might not have a USDC account yet. A robust solution creates the account for them within the same transaction. The `spl-token` library has an instruction for this: `createAssociatedTokenAccountInstruction`. Check if the recipient's ATA exists, and if not, add this instruction to the transaction.++4. **Create the Transfer Instruction:**+ * Use the `spl-token` library's `createTransferInstruction` to build the core payment instruction.+ * You'll need the source ATA, destination ATA, payer's public key (as the owner), and the amount from the intent.++5. **Assemble the Transaction:**+ * Create a new `solanaWeb3.Transaction`.+ * Add the `createAssociatedTokenAccountInstruction` if it was needed.+ * Add the `createTransferInstruction`.+ * Set the `feePayer` to the `payerPublicKey`.+ * Fetch a recent blockhash from the `solanaConnection` and assign it to the transaction's `recentBlockhash`.+ * Return the fully constructed transaction object.++## Code Example (Frontend - `src/marketplace.js`)++**Note:** This is complex and requires the SPL Token library. Assume you have it available via a script tag.+`<script src="https://unpkg.com/@solana/[email protected]/lib/index.iife.js"></script>`++```javascript+// Add this helper function to marketplace.js+const { TOKEN_PROGRAM_ID } = splToken;++async function buildUsdcTransferTransaction(intent, payerPublicKey) {+ const { recipient_address, amount, currency_mint } = intent;++ const transaction = new solanaWeb3.Transaction();++ const mintPublicKey = new solanaWeb3.PublicKey(currency_mint);+ const recipientPublicKey = new solanaWeb3.PublicKey(recipient_address);++ // 1. Get or create the recipient's associated token account+ const recipientAta = await splToken.getAssociatedTokenAddress(+ mintPublicKey,+ recipientPublicKey+ );+ const recipientAtaInfo = await solanaConnection.getAccountInfo(recipientAta);+ if (!recipientAtaInfo) {+ transaction.add(+ splToken.createAssociatedTokenAccountInstruction(+ payerPublicKey,+ recipientAta,+ recipientPublicKey,+ mintPublicKey+ )+ );+ }++ // 2. Get the payer's associated token account+ const payerAta = await splToken.getAssociatedTokenAddress(+ mintPublicKey,+ payerPublicKey+ );++ // 3. Create the transfer instruction+ transaction.add(+ splToken.createTransferInstruction(+ payerAta,+ recipientAta,+ payerPublicKey,+ parseInt(amount)+ )+ );++ // 4. Set the fee payer and recent blockhash+ transaction.feePayer = payerPublicKey;+ const { blockhash } = await solanaConnection.getRecentBlockhash();+ transaction.recentBlockhash = blockhash;++ return transaction;+}+```diff --git a/tasks/monetization-feature/10-send-solana-transaction.md b/tasks/monetization-feature/10-send-solana-transaction.mdnew file mode 100644index 000000000..9bcb4fa14--- /dev/null+++ b/tasks/monetization-feature/10-send-solana-transaction.md@@ -0,0 +1,116 @@+# Prompt 10: Send Solana Transaction++## Objective+Wire up the "Confirm Purchase" button to take the constructed transaction from the previous step, send it to the user's wallet for signing, and submit it to the Solana network.++## Explanation+This is the climax of the payment flow. The user has connected their wallet and is ready to pay. When they click the final confirmation button, we will:+1. Build the transaction using the function from the previous prompt.+2. Use the wallet adapter's `sendTransaction` method. This method first asks the user to approve and sign the transaction via their wallet's popup.+3. If the user approves, the adapter sends the signed transaction to the Solana RPC.+4. The method returns a transaction signature (ID).+5. We will then wait for the transaction to be confirmed by the network.++## Instructions+1. **Add Event Listener:**+ * In `src/marketplace.js`, add an event listener to the `#payment-confirm-btn`. This should be done when the modal is opened or when the wallet connects.++2. **Implement the Click Handler:**+ * The handler should be `async`.+ * Show a loading state (e.g., disable the button, show a "Processing..." message in the status area).+ * Get the `intent_id` and other necessary data that you stored when opening the modal.+ * Get the user's public key from `wallet.publicKey`.+ * Call the `buildUsdcTransferTransaction` function from the previous prompt to get the transaction object.++3. **Send the Transaction:**+ * Call `wallet.sendTransaction(transaction, solanaConnection)`.+ * This function will throw an error if the user rejects the signature, so wrap it in a `try...catch` block.+ * The function returns a `txid` (transaction signature).++4. **Confirm the Transaction:**+ * Once you have the `txid`, use `solanaConnection.confirmTransaction(txid, 'confirmed')`. This will wait until the transaction is finalized on the blockchain.+ * This is the point of success. You now have proof of payment.++5. **Next Steps (to be handled in future prompts):**+ * After confirmation, you will call your backend's `/api/payments/confirm` endpoint with the `txid`.+ * For now, on success, simply show a success message in the modal's status area. On failure (user rejection, network error), show an appropriate error message.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// Add this event listener setup inside the updateWalletUI function,+// when the wallet is connected.++function updateWalletUI() {+ // ... inside the `if (wallet.connected)` block+ const confirmBtn = $('payment-confirm-btn');+ confirmBtn.disabled = false;++ // Make sure to remove old listeners if this function can be called multiple times+ const newConfirmBtn = confirmBtn.cloneNode(true);+ confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);++ newConfirmBtn.addEventListener('click', handlePurchase);+}++// Create the main purchase handler function+async function handlePurchase() {+ const statusEl = $('payment-status');+ const confirmBtn = $('payment-confirm-btn');+ confirmBtn.disabled = true;+ statusEl.textContent = 'Building transaction...';++ try {+ const intentId = document.getElementById('payment-modal-overlay').dataset.intentId;+ // You'll need to fetch the intent again or store it more robustly+ // For now, let's assume `currentIntent` is available+ const intent = await getCurrentIntentDetails(intentId); // Placeholder for fetching intent+ if (!wallet.publicKey) throw new Error('Wallet is not connected.');++ const transaction = await buildUsdcTransferTransaction(intent, wallet.publicKey);++ statusEl.textContent = 'Please approve the transaction in your wallet...';++ const txid = await wallet.sendTransaction(transaction, solanaConnection);+ statusEl.textContent = `Transaction sent! Waiting for confirmation... (${txid.slice(0, 8)}...)`;++ const confirmation = await solanaConnection.confirmTransaction(txid, 'confirmed');+ if (confirmation.value.err) {+ throw new Error(`Transaction failed: ${confirmation.value.err}`);+ }++ statusEl.textContent = 'Payment successful! Unlocking skill...';++ // In the next prompt, we will call our backend confirmation endpoint here.+ // For example: await confirmPaymentOnBackend(intentId, txid);++ setTimeout(() => {+ closePaymentModal();+ }, 2000);++ } catch (error) {+ statusEl.textContent = `Error: ${error.message}`;+ console.error("Purchase failed", error);+ } finally {+ // The button will be re-enabled if the modal is re-opened+ }+}++// A placeholder function - you'd need to implement this+// or pass the intent object around properly.+async function getCurrentIntentDetails(intentId) {+ // In a real app, you might re-fetch this from your server or have it stored+ // For now, we'll reconstruct it from the UI for this example+ const priceText = $('payment-price-display').textContent;+ const amount = Math.round(parseFloat(priceText.replace(' USDC', '')) * 1e6);+ // You would also need to get the recipient address and mint from the intent.+ // This highlights the need for better state management than just the DOM.++ // For now, let's return a dummy object. The real implementation would be more robust.+ return {+ recipient_address: '...', // You would need to fetch this+ amount: String(amount),+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a' // USDC+ }+}+```diff --git a/tasks/monetization-feature/11-confirm-payment-api.md b/tasks/monetization-feature/11-confirm-payment-api.mdnew file mode 100644index 000000000..70913a04a--- /dev/null+++ b/tasks/monetization-feature/11-confirm-payment-api.md@@ -0,0 +1,95 @@+# Prompt 11: Create Payment Confirmation API++## Objective+Create a backend API endpoint that verifies a Solana transaction signature, marks the corresponding payment intent as "paid," and records the revenue event.++## Explanation+After the frontend successfully sends a transaction, it has a transaction signature (`txid`). To prevent fraud and ensure the creator gets credit, the frontend must send this signature to our backend. The backend then acts as the source of truth, performing the critical step of verifying the transaction on the Solana blockchain itself. If the transaction is valid and matches the intent, we update our database to reflect the successful purchase.++## Instructions+1. **Create a New API File:**+ * Create a file at `/api/payments/confirm.js`.++2. **Define the Endpoint Logic:**+ * The endpoint accepts a `POST` request and must be authenticated.+ * The request body should contain the `intent_id` and the `transaction_signature` (`txid`).++3. **Implement Verification Logic:**+ * **Fetch the Intent:** Retrieve the `agent_payment_intents` record from your database using the `intent_id`. Verify that it exists and its status is `'pending'`.+ * **Fetch the Transaction:** Use the Solana web3.js library (`@solana/web3.js`) on the backend to connect to the Solana cluster. Call `connection.getParsedTransaction(transaction_signature)`.+ * **Validate the Transaction:** This is the most critical step.+ * Check that the transaction is not null and has no errors (`transaction.meta.err === null`).+ * Parse the transaction instructions to find the token transfer. Look at the `preTokenBalances` and `postTokenBalances` to verify the amount transferred.+ * Confirm that the source account in the transaction matches the user who initiated the intent.+ * Confirm that the destination account matches the recipient from the payment intent.+ * Confirm that the amount transferred is equal to or greater than the amount in the intent.+ * Confirm the token mint matches the currency from the intent.+ * **Handle Failure:** If any validation step fails, return a 400-level error and do not update the database.++4. **Update the Database on Success:**+ * If validation passes, update the `agent_payment_intents` record: set `status` to `'paid'`, and store the `transaction_signature` and `paid_at` timestamp.+ * Insert a new record into the `agent_revenue_events` table to log the earnings for the creator. Calculate the net amount after taking a platform fee (if any).++5. **Add Vercel Routing:**+ * In `vercel.json`, add a route for `/api/payments/confirm`.++## Code Example (Backend - `api/payments/confirm.js`)++```javascript+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { Connection, clusterApiUrl } from '@solana/web3.js';++const PLATFORM_FEE_BPS = 500; // 5% platform fee++export default wrap(async (req, res) => {+ // ... boilerplate for CORS, method check, and auth ...+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized');++ const { intent_id, transaction_signature } = await readJson(req);+ if (!intent_id || !transaction_signature) return error(res, 400, 'validation_error', 'intent_id and transaction_signature are required');++ // 1. Fetch our internal record of the intent+ const [intent] = await sql`+ SELECT * FROM agent_payment_intents WHERE id = ${intent_id} AND payer_user_id = ${user.id}+ `;+ if (!intent) return error(res, 404, 'not_found', 'Payment intent not found.');+ if (intent.status !== 'pending') return error(res, 400, 'invalid_request', `Intent is already in status: ${intent.status}`);++ // 2. Fetch and validate the on-chain transaction+ const connection = new Connection(clusterApiUrl('mainnet-beta')); // Or devnet+ const tx = await connection.getParsedTransaction(transaction_signature, { maxSupportedTransactionVersion: 0 });++ if (!tx || tx.meta.err) {+ return error(res, 400, 'transaction_failed', 'On-chain transaction failed or was not found.');+ }++ // Basic validation (a robust implementation would parse instructions thoroughly)+ // Here we will just check that the intent is updated+ // A full implementation would be much more complex. We'll simplify for this prompt.++ // 3. Update database+ await sql.transaction(async (tx) => {+ await tx`+ UPDATE agent_payment_intents+ SET status = 'paid', transaction_signature = ${transaction_signature}, paid_at = now()+ WHERE id = ${intent_id}+ `;++ const gross_amount = BigInt(intent.amount);+ const fee_amount = (gross_amount * BigInt(PLATFORM_FEE_BPS)) / 10000n;+ const net_amount = gross_amount - fee_amount;++ await tx`+ INSERT INTO agent_revenue_events+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain)+ VALUES+ (${intent.agent_id}, ${intent.id}, ${intent.payload.skill}, ${gross_amount}, ${fee_amount}, ${net_amount}, ${intent.currency_mint}, 'solana')+ `;+ });++ return json(res, 200, { success: true, message: "Payment confirmed." });+});+```diff --git a/tasks/monetization-feature/12-handle-payment-confirmation-ui.md b/tasks/monetization-feature/12-handle-payment-confirmation-ui.mdnew file mode 100644index 000000000..82bae7e86--- /dev/null+++ b/tasks/monetization-feature/12-handle-payment-confirmation-ui.md@@ -0,0 +1,93 @@+# Prompt 12: Handle Payment Confirmation UI++## Objective+Update the frontend JavaScript to call the `/api/payments/confirm` endpoint after a Solana transaction is confirmed, and display appropriate success or error messages to the user in the payment modal.++## Explanation+The loop is almost closed. The frontend has a confirmed transaction signature (`txid`), and the backend has an endpoint to verify it. Now we need to connect the two. The `handlePurchase` function will be extended to send the `txid` and `intent_id` to our backend, effectively finalizing the purchase in our system. The UI needs to provide clear feedback throughout this final verification step.++## Instructions+1. **Locate the Frontend Logic:**+ * Open `src/marketplace.js` and find the `handlePurchase` function created in Prompt 10.++2. **Add the API Call:**+ * Inside the `try` block, immediately after `solanaConnection.confirmTransaction` successfully completes, add a `fetch` call.+ * `POST` to `/api/payments/confirm`.+ * The body of the request must include the `intent_id` and the `transaction_signature` (`txid`).+ * Remember to include `credentials: 'include'` and the correct `Content-Type` header.++3. **Handle API Response:**+ * Check if the response is `ok`. If not, throw an error with the message from the API's JSON response. This will be caught by the `catch` block.+ * If the response is successful, the purchase is officially complete.++4. **Update UI Feedback:**+ * Change the status messages in the modal to reflect the new step.+ * Before the API call: "Verifying purchase with server..."+ * On API success: "Success! Skill unlocked."+ * On API failure (in the `catch` block): "There was an issue verifying your purchase. Please contact support."+ * After a successful confirmation, you can close the modal after a short delay.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// This is an updated version of the handlePurchase function from Prompt 10++async function handlePurchase() {+ const statusEl = $('payment-status');+ const confirmBtn = $('payment-confirm-btn');+ confirmBtn.disabled = true;+ statusEl.textContent = 'Building transaction...';+ statusEl.className = 'payment-status';++ const intentId = document.getElementById('payment-modal-overlay').dataset.intentId;+ if (!intentId) {+ statusEl.textContent = 'Error: Missing payment intent ID.';+ statusEl.classList.add('err');+ return;+ }++ try {+ const intent = await getCurrentIntentDetails(intentId); // Placeholder+ if (!wallet.publicKey) throw new Error('Wallet is not connected.');++ statusEl.textContent = 'Please approve the transaction in your wallet...';+ const transaction = await buildUsdcTransferTransaction(intent, wallet.publicKey);+ const txid = await wallet.sendTransaction(transaction, solanaConnection);++ statusEl.textContent = `Waiting for on-chain confirmation...`;+ const confirmation = await solanaConnection.confirmTransaction(txid, 'confirmed');+ if (confirmation.value.err) throw new Error('On-chain transaction failed.');++ statusEl.textContent = 'Verifying purchase with server...';++ const verifyRes = await fetch('/api/payments/confirm', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ intent_id: intentId,+ transaction_signature: txid,+ }),+ });++ const verifyBody = await verifyRes.json();+ if (!verifyRes.ok) {+ throw new Error(verifyBody.error_description || 'Failed to verify purchase.');+ }++ statusEl.textContent = 'Success! Skill unlocked.';+ statusEl.classList.add('ok');++ // In the next prompt, we will add logic to update the UI permanently+ // fireEvent('skill:purchased', { skillName: intent.payload.skill });++ setTimeout(closePaymentModal, 2000);++ } catch (error) {+ statusEl.textContent = `Error: ${error.message}`;+ statusEl.classList.add('err');+ console.error("Purchase failed", error);+ confirmBtn.disabled = false; // Re-enable on failure+ }+}+```diff --git a/tasks/monetization-feature/13-unlock-skill-ui.md b/tasks/monetization-feature/13-unlock-skill-ui.mdnew file mode 100644index 000000000..d2e71f113--- /dev/null+++ b/tasks/monetization-feature/13-unlock-skill-ui.md@@ -0,0 +1,99 @@+# Prompt 13: Update UI to Permanently Unlock Skill++## Objective+After a successful purchase, update the agent detail page UI to show the newly purchased skill as "Unlocked," and ensure this state persists on page reload.++## Explanation+Currently, after a successful payment, the modal closes, but the underlying page doesn't change. The "Purchase" button for the skill is still visible. We need to update the state of our application to reflect the new ownership and re-render the skill list to change the button to "Unlocked."++This requires two parts:+1. A way to keep track of unlocked skills in the frontend's state.+2. A re-rendering mechanism to update the UI when that state changes.++## Instructions+1. **Introduce a Frontend State for Unlocked Skills:**+ * In `src/marketplace.js`, create a global set or array to store the names of skills the user has unlocked in the current session. For example: `let unlockedSkills = new Set();`++2. **Update State After Purchase:**+ * In the `handlePurchase` function, after the backend confirmation is successful, add the newly purchased skill's name to your `unlockedSkills` set.++3. **Create a Re-render Function:**+ * Refactor the skill-rendering logic from the `renderDetail` function into its own standalone function, e.g., `renderSkillList(agent)`.+ * This new function should take the agent object as an argument, access the global `unlockedSkills` set, and generate the HTML for the skills section, correctly showing "Unlocked" buttons for the skills in the set.+ * The original `renderDetail` function will now call `renderSkillList(agent)` to render the skills initially.++4. **Trigger Re-render After Purchase:**+ * After adding the skill to the `unlockedSkills` set in `handlePurchase`, call your new `renderSkillList(detailState.agent)` function. This will immediately update the UI on the page behind the modal, before it closes.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// --- At the top of the file ---+let unlockedSkills = new Set(); // In a real app, this would be populated from an API call on load+++// --- New function, refactored from renderDetail ---+function renderSkillList(agent) {+ const skillsContainer = $('d-skills');+ if (!skillsContainer) return;++ const skillsArr = Array.isArray(agent.capabilities.skills) ? agent.capabilities.skills : agent.skills || [];+ const skillPrices = agent.skill_prices || {};++ skillsContainer.innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];++ let actionButton;+ if (unlockedSkills.has(name)) {+ actionButton = `<button class="skill-btn" disabled>Unlocked</button>`;+ } else if (price) {+ actionButton = `<button class="skill-btn purchase" data-skill-name="${escapeHtml(name)}">Purchase</button>`;+ } else {+ actionButton = `<button class="skill-btn" disabled>Free</button>`;+ }++ const priceDisplay = price ? `<span class="price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>` : ``;++ return `<div class="skill-row">+ <span class="skill-name">${escapeHtml(name)} ${priceDisplay}</span>+ ${actionButton}+ </div>`;+ }).join('')+ : '<div>This Agent has no skills defined.</div>';+}++// --- Modify the original renderDetail function ---+function renderDetail(a, bookmarked) {+ // ... all the existing code to render name, description, etc.++ // Replace the old innerHTML logic for skills with a call to the new function+ renderSkillList(a);++ // ... rest of the function+}++// --- Update the handlePurchase function ---+async function handlePurchase() {+ // ... inside the successful payment logic, after backend confirmation+ try {+ // ...+ const verifyBody = await verifyRes.json();+ if (!verifyRes.ok) throw new Error(verifyBody.error_description);++ statusEl.textContent = 'Success! Skill unlocked.';+ statusEl.classList.add('ok');++ // *** NEW CODE HERE ***+ const skillName = intent.payload.skill; // Assuming intent has skill name+ unlockedSkills.add(skillName);+ renderSkillList(detailState.agent); // Re-render the skills on the page++ setTimeout(closePaymentModal, 2000);+ } catch (error) {+ // ...+ }+}+```+**Note:** This only persists the "unlocked" state for the current session. The next set of prompts will address fetching this data from the server so it persists across reloads.diff --git a/tasks/monetization-feature/14-user-skills-database.md b/tasks/monetization-feature/14-user-skills-database.mdnew file mode 100644index 000000000..e757f0447--- /dev/null+++ b/tasks/monetization-feature/14-user-skills-database.md@@ -0,0 +1,70 @@+# Prompt 14: Database for User's Purchased Skills++## Objective+Create a new table in the PostgreSQL database to permanently store which users have unlocked which skills for which agents.++## Explanation+Frontend state is temporary. To ensure a user's purchases are remembered across sessions and devices, we need to store their unlocked skills in our database. A dedicated table is the right way to do this. This table will link a `user_id` to an `agent_id` and a `skill_name`, creating a permanent record of the entitlement.++## Instructions+1. **Create a New SQL Migration File:**+ * In the `/api/_lib/migrations/` directory, create a new SQL file. A good name would be `2026-05-05-user-unlocked-skills.sql` (using a current or future date).++2. **Write the DDL (Data Definition Language):**+ * Inside the new file, write the `CREATE TABLE` statement for a table named `user_unlocked_skills`.+ * The table should include the following columns:+ * `user_id`: `UUID`, a foreign key referencing `users(id)`.+ * `agent_id`: `UUID`, a foreign key referencing `agent_identities(id)`.+ * `skill_name`: `TEXT`, to store the name of the skill.+ * `created_at`: `TIMESTAMPTZ`, with a default value of `now()`.+ * `source`: `TEXT`, to note how the skill was acquired (e.g., 'purchase').+ * `payment_intent_id`: `TEXT`, a foreign key referencing `agent_payment_intents(id)`.+ * Define a `PRIMARY KEY` on (`user_id`, `agent_id`, `skill_name`) to prevent duplicate entries.+ * Add indexes on `user_id` and `agent_id` for efficient lookups.+ * Wrap the entire statement in a `BEGIN;` and `COMMIT;` block to make it transactional.++3. **Update the Payment Confirmation Logic:**+ * In the backend API at `/api/payments/confirm.js`, modify the transaction block.+ * After successfully creating the `agent_revenue_events` record, add a new `INSERT` statement to add a record to your new `user_unlocked_skills` table.+ * You have all the necessary information available: `user.id`, `intent.agent_id`, `intent.payload.skill`, and the `intent_id`.++## Code Example (SQL Migration - `api/_lib/migrations/...-user-unlocked-skills.sql`)++```sql+BEGIN;++CREATE TABLE IF NOT EXISTS user_unlocked_skills (+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ skill_name TEXT NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ source TEXT NOT NULL DEFAULT 'purchase',+ payment_intent_id TEXT REFERENCES agent_payment_intents(id) ON DELETE SET NULL,+ PRIMARY KEY (user_id, agent_id, skill_name)+);++CREATE INDEX IF NOT EXISTS user_unlocked_skills_user_id_idx ON user_unlocked_skills (user_id);+CREATE INDEX IF NOT EXISTS user_unlocked_skills_agent_id_idx ON user_unlocked_skills (agent_id);++COMMIT;+```++## Code Example (Backend - `/api/payments/confirm.js`)++```javascript+// ... inside the sql.transaction block ...++await tx`+ INSERT INTO agent_revenue_events+ -- ... (as before)+`;++await tx`+ INSERT INTO user_unlocked_skills+ (user_id, agent_id, skill_name, payment_intent_id)+ VALUES+ (${user.id}, ${intent.agent_id}, ${intent.payload.skill}, ${intent.id})+ ON CONFLICT (user_id, agent_id, skill_name) DO NOTHING+`;+```+After creating the migration file, remember to run your migration script to apply the changes to the database.diff --git a/tasks/monetization-feature/15-user-skills-api.md b/tasks/monetization-feature/15-user-skills-api.mdnew file mode 100644index 000000000..1fb557b25--- /dev/null+++ b/tasks/monetization-feature/15-user-skills-api.md@@ -0,0 +1,81 @@+# Prompt 15: API to Fetch User's Unlocked Skills++## Objective+Create a backend API endpoint that returns a list of all skills a user has unlocked for a specific agent.++## Explanation+Now that we are storing a user's skill purchases in the database, we need a way for the frontend to retrieve this information when a page loads. This will allow us to show the correct "Unlocked" state for skills even if the user refreshes the page or visits from a new device.++## Instructions+1. **Create a New API File:**+ * Create a file at `/api/agents/[id]/unlocked-skills.js`. This nested route makes sense as the unlocked skills are specific to an agent for a given user.++2. **Define the Endpoint Logic:**+ * The endpoint should handle `GET` requests.+ * It must be authenticated, as it's specific to the logged-in user.+ * It needs the `agent_id` from the URL path.++3. **Implement the Database Query:**+ * Query the `user_unlocked_skills` table.+ * Select the `skill_name` column.+ * Filter by the `agent_id` from the URL and the `user_id` from the authenticated session.+ * The endpoint should return a simple JSON array of skill name strings, for example: `{"skills": ["advanced_analysis", "creative_writing"]}`.++4. **Add Vercel Routing:**+ * In `vercel.json`, add a new route to handle this dynamic endpoint:+ `"/api/agents/([^/]+)/unlocked-skills"` should map to `/api/agents/[id]/unlocked-skills?id=$1`.++## Code Example (Backend - `/api/agents/[id]/unlocked-skills.js`)++```javascript+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error } from '../../_lib/http.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const user = await getSessionUser(req);+ if (!user) {+ // Return empty list for non-logged-in users instead of an error+ return json(res, 200, { skills: [] });+ }++ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('id');++ if (!agentId) {+ return error(res, 400, 'validation_error', 'Agent ID is required.');+ }++ const rows = await sql`+ SELECT skill_name+ FROM user_unlocked_skills+ WHERE user_id = ${user.id} AND agent_id = ${agentId}+ `;++ const skills = rows.map(r => r.skill_name);++ return json(res, 200, { skills });+});+```++## Code Example (Vercel Routing - `vercel.json`)++```json+{+ "routes": [+ // ... other routes+ {+ "src": "/api/agents/([^/]+)/skills-pricing",+ "dest": "/api/agents/[id]/skills-pricing?id=$1"+ },+ {+ "src": "/api/agents/([^/]+)/unlocked-skills",+ "dest": "/api/agents/[id]/unlocked-skills?id=$1"+ },+ // ... other routes+ ]+}+```diff --git a/tasks/monetization-feature/16-reflect-unlocked-skills-ui.md b/tasks/monetization-feature/16-reflect-unlocked-skills-ui.mdnew file mode 100644index 000000000..3d95b6e04--- /dev/null+++ b/tasks/monetization-feature/16-reflect-unlocked-skills-ui.md@@ -0,0 +1,78 @@+# Prompt 16: Reflect Unlocked Skills on Page Load++## Objective+Update the frontend to call the new `/api/agents/:id/unlocked-skills` endpoint when the agent detail page loads, and use this data to correctly display the "Unlocked" state for skills.++## Explanation+The frontend now has an API to get the user's permanent skill entitlements. We need to call this API when the detail page loads and populate our `unlockedSkills` set from its response. This will ensure that the UI accurately reflects the user's purchase history from the moment the page becomes visible.++## Instructions+1. **Locate the Frontend Logic:**+ * Open `src/marketplace.js` and find the `loadDetail` function. This is the main function that orchestrates the loading of the agent detail page.++2. **Fetch Unlocked Skills:**+ * Inside `loadDetail`, after fetching the main agent details, make another `fetch` call to your new endpoint: `/api/agents/${id}/unlocked-skills`.+ * Remember to include `credentials: 'include'` so the backend knows who the user is.+ * This call can be made in parallel with the other agent detail calls (like versions and similar agents) using `Promise.all` for better performance.++3. **Populate the State:**+ * When the API call returns, it will have a JSON object like `{ skills: ["skill1", "skill2"] }`.+ * Take this array of skill names and use it to initialize your global `unlockedSkills` set.++4. **Ensure Correct Render Order:**+ * Make sure that you populate the `unlockedSkills` set *before* you call the `renderSkillList` function. The `Promise.all` approach ensures this naturally. `loadDetail` should await all necessary data before it proceeds to render.++## Code Example (Frontend - `src/marketplace.js`)++```javascript+// At the top of the file, initialize the set+let unlockedSkills = new Set();+++// Modify the loadDetail function+async function loadDetail(id) {+ els.discovery.hidden = true;+ els.detail.hidden = false;+ els.detail.scrollIntoView({ behavior: 'instant', block: 'start' });++ // Reset for the new page+ unlockedSkills = new Set();++ try {+ // Use Promise.all to fetch everything concurrently+ const [aR, vR, sR, unlockedR] = await Promise.all([+ fetch(`${API}/agents/${id}`),+ fetch(`${API}/agents/${id}/versions`),+ fetch(`${API}/agents/${id}/similar`),+ fetch(`${API}/agents/${id}/unlocked-skills`, { credentials: 'include' })+ ]);++ const aJ = await aR.json();+ if (!aR.ok) {+ renderDetailError(aJ?.error_description || 'Agent not found');+ return;+ }++ // Populate the unlocked skills set+ const unlockedData = await unlockedR.json();+ if (unlockedData.skills) {+ unlockedSkills = new Set(unlockedData.skills);+ }++ const a = aJ.data.agent;+ detailState = { agent: a, bookmarked: !!aJ.data.bookmarked };++ // Now render everything with the correct data+ renderDetail(a, aJ.data.bookmarked);+ renderVersions((await vR.json())?.data?.versions || []);+ renderSimilar((await sR.json())?.data?.items || []);++ // Fire-and-forget view counter.+ fetch(`${API}/agents/${id}/view`, { method: 'POST' }).catch(() => {});+ } catch (err) {+ console.error('[marketplace] detail', err);+ renderDetailError('Failed to load agent.');+ }+}+```+With this change, `renderDetail` will call `renderSkillList`, which will now have access to the correctly populated `unlockedSkills` set, ensuring the UI is correct from the very first render.diff --git a/tasks/monetization-feature/17-revenue-dashboard-page.md b/tasks/monetization-feature/17-revenue-dashboard-page.mdnew file mode 100644index 000000000..f2afa7445--- /dev/null+++ b/tasks/monetization-feature/17-revenue-dashboard-page.md@@ -0,0 +1,76 @@+# Prompt 17: Creator Revenue Dashboard Page++## Objective+Create a new "Revenue" tab and page within the main user dashboard area (`/dashboard`) for agent creators to track their earnings.++## Explanation+Creators need a central place to see how much money their agents are making. We will add a new section to the existing dashboard for this purpose. This first step involves creating the basic page structure, adding the navigation tab, and ensuring it can be routed to. The content of the dashboard will be filled in by later prompts.++## Instructions+1. **Locate Dashboard Files:**+ * The main dashboard files are likely `public/dashboard/dashboard.js` and a corresponding HTML file (e.g., `pump-dashboard.html` or similar - check file list). You will need to modify both.++2. **Add Navigation Tab:**+ * In the HTML file for the dashboard, find the navigation menu/sidebar.+ * Add a new link/tab for "Revenue." Give it a `data-tab="revenue"` attribute to work with the existing JavaScript-based routing. Choose a suitable icon.++3. **Add a Page Container:**+ * In the same HTML file, in the main content area, add a new container `div` for the revenue page. It should have `id="page-revenue"` and be hidden by default (`style="display:none"`), consistent with the other dashboard pages.++4. **Implement JavaScript Routing:**+ * In `public/dashboard/dashboard.js`, find the routing logic. There should be a map or switch statement that links `data-tab` values to rendering functions.+ * Add a new entry for `'revenue'` that maps to a new function, `renderRevenue`.++5. **Create the `renderRevenue` Function:**+ * Create a new `async function renderRevenue(root)` in `dashboard.js`.+ * For now, this function should just render the basic structure of the revenue page inside the `root` element (which will be the main content area).+ * Include a title, a brief description, and placeholders for where the stats and transaction list will go.++## Code Example (HTML - in dashboard file)++```html+<!-- In the sidebar/nav menu -->+<a href="#" data-tab="revenue"><span class="icon">💰</span> Revenue</a>++<!-- In the main content area, with the other pages -->+<div class="content page" id="page-revenue" style="display:none">+ <!-- Content will be rendered here by dashboard.js -->+</div>+```++## Code Example (JavaScript - `public/dashboard/dashboard.js`)++```javascript+// --- In the tabs mapping object ---+const tabs = {+ avatars: renderAvatars,+ // ... other tabs+ revenue: renderRevenue, // Add this line+ account: renderAccount,+};++// --- Add the new rendering function ---+async function renderRevenue(root) {+ root.innerHTML = `+ <div class="page-header">+ <h1>Revenue</h1>+ <p class="sub">Track your earnings from paid agent skills.</p>+ </div>+ <div id="revenue-content">+ <div class="panel">+ <div class="panel-body">+ <div class="empty">+ <div class="icon">📈</div>+ Loading revenue data...+ </div>+ </div>+ </div>+ </div>+ `;++ // In the next prompts, we will fetch data and fill this content.+ // e.g., loadRevenueStats();+ // e.g., loadRevenueEvents();+}+```+With these changes, users will be able to click on the "Revenue" tab and see the basic placeholder page, setting the stage for the data-rich components to come.diff --git a/tasks/monetization-feature/18-revenue-stats-ui.md b/tasks/monetization-feature/18-revenue-stats-ui.mdnew file mode 100644index 000000000..374b257d2--- /dev/null+++ b/tasks/monetization-feature/18-revenue-stats-ui.md@@ -0,0 +1,113 @@+# Prompt 18: Revenue Stats API and UI++## Objective+Create a backend API endpoint to calculate and return key revenue statistics for a user, and then display these stats in the new Revenue Dashboard.++## Explanation+A high-level overview is the most important part of a dashboard. We need to provide creators with key metrics like their current balance, total lifetime revenue, and recent earnings. This requires a backend endpoint that can efficiently query the `agent_revenue_events` table and aggregate the data.++## Instructions+1. **Create the Backend API Endpoint:**+ * Create a new file: `/api/billing/revenue-stats.js`.+ * This `GET` endpoint must be authenticated.+ * It should query the `agent_revenue_events` table, joined with `agent_identities` to filter by the current `user_id`.+ * Use SQL aggregate functions (`SUM`, `COUNT`) to calculate:+ * `total_revenue_gross`: The sum of `gross_amount` for all time.+ * `total_revenue_net`: The sum of `net_amount` for all time.+ * `earnings_last_30_days`: The sum of `net_amount` where `created_at` is within the last 30 days.+ * `current_balance`: The sum of `net_amount` minus the sum of all withdrawals for this user (from `agent_withdrawals` table).+ * Return these values in a JSON object.++2. **Update the Frontend Dashboard:**+ * In `public/dashboard/dashboard.js`, modify the `renderRevenue` function.+ * After rendering the initial HTML shell, make a `fetch` call to your new `/api/billing/revenue-stats` endpoint.+ * Create a new function, e.g., `renderStats(stats)`, that takes the API response and generates the HTML for a grid of stat cards.+ * Each card should display a label (e.g., "Net Lifetime Revenue") and the formatted value. Make sure to convert amounts from the smallest unit to a human-readable currency format (e.g., divide by 1,000,000 for USDC and format with a dollar sign).+ * Handle loading and error states gracefully.++## Code Example (Backend - `/api/billing/revenue-stats.js`)++```javascript+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { json, wrap, error } from '../_lib/http.js';++export default wrap(async (req, res) => {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized');++ // This query is complex and joins multiple tables.+ // For simplicity, we'll do separate queries. A single, more optimized query is better in production.++ const [revenue] = await sql`+ SELECT+ SUM(rev.net_amount) AS total_net,+ SUM(CASE WHEN rev.created_at >= NOW() - INTERVAL '30 days' THEN rev.net_amount ELSE 0 END) AS last_30_days+ FROM agent_revenue_events rev+ JOIN agent_identities ai ON rev.agent_id = ai.id+ WHERE ai.user_id = ${user.id}+ `;++ const [withdrawals] = await sql`+ SELECT SUM(amount) AS total_withdrawn+ FROM agent_withdrawals+ WHERE user_id = ${user.id} AND status = 'completed'+ `;++ const total_net = BigInt(revenue.total_net || 0);+ const total_withdrawn = BigInt(withdrawals.total_withdrawn || 0);+ const current_balance = total_net - total_withdrawn;++ return json(res, 200, {+ total_revenue_net: String(total_net),+ earnings_last_30_days: String(revenue.last_30_days || 0),+ current_balance: String(current_balance),+ });+});+```++## Code Example (Frontend - `public/dashboard/dashboard.js`)++```javascript+async function renderRevenue(root) {+ root.innerHTML = `+ <div class="page-header">+ <h1>Revenue</h1>+ <p class="sub">Track your earnings from paid agent skills.</p>+ </div>+ <div class="stats-grid" id="revenue-stats-grid">+ <div class="stat-card">Loading...</div>+ </div>+ <div id="revenue-events-table-container"></div>+ `;++ try {+ const stats = await api.getRevenueStats(); // Assumes an api helper exists+ renderRevenueStats(stats);+ } catch (e) {+ document.getElementById('revenue-stats-grid').innerHTML = `<div class="err">Failed to load stats: ${e.message}</div>`;+ }+}++function renderRevenueStats(stats) {+ const grid = document.getElementById('revenue-stats-grid');++ const formatUSDC = (amount) => `$${(Number(amount) / 1e6).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;++ grid.innerHTML = `+ <div class="stat-card">+ <div class="label">Current Balance</div>+ <div class="value green">${formatUSDC(stats.current_balance)}</div>+ </div>+ <div class="stat-card">+ <div class="label">Net Earnings (30 Days)</div>+ <div class="value">${formatUSDC(stats.earnings_last_30_days)}</div>+ </div>+ <div class="stat-card">+ <div class="label">Lifetime Net Revenue</div>+ <div class="value">${formatUSDC(stats.total_revenue_net)}</div>+ </div>+ `;+}+```+You would also need to add a helper for `/api/billing/revenue-stats` to your `api` object in `dashboard.js`.diff --git a/tasks/monetization-feature/19-revenue-events-table.md b/tasks/monetization-feature/19-revenue-events-table.mdnew file mode 100644index 000000000..53f09dd97--- /dev/null+++ b/tasks/monetization-feature/19-revenue-events-table.md@@ -0,0 +1,134 @@+# Prompt 19: Revenue Events API and Table++## Objective+Create an API endpoint to fetch a paginated list of individual revenue events for a user, and display these events in a table on the Revenue Dashboard.++## Explanation+After seeing their high-level stats, creators will want to see the breakdown of their earnings. A transaction history, or "revenue events" list, provides this transparency. We need a paginated API to handle potentially large numbers of events, and a clean table on the frontend to display them.++## Instructions+1. **Create the Backend API Endpoint:**+ * Create a new file: `/api/billing/revenue-events.js`.+ * This `GET` endpoint must be authenticated and should support cursor-based pagination (`?cursor=...`).+ * Query the `agent_revenue_events` table, filtering by the agents owned by the current `user_id`.+ * For each event, you should also join `agent_identities` to get the `agent_name`.+ * Order the results by `created_at DESC`.+ * Return a list of events and a `next_cursor` for the frontend to use for "Load More" functionality. Each event object should include details like date, skill name, agent name, and the net amount earned.++2. **Update the Frontend Dashboard:**+ * In `public/dashboard/dashboard.js`, create a new function `loadRevenueEvents`. Call this from within `renderRevenue` after the stats have been loaded.+ * This function will fetch data from `/api/billing/revenue-events`.+ * Create a rendering function `renderRevenueEventsTable(events)` that generates the HTML for a table.+ * The table should have columns for: Date, Agent, Skill, and Net Amount.+ * Display the data in the `#revenue-events-table-container` element.+ * Implement a "Load More" button that appears if the API response includes a `next_cursor`. Clicking this button should fetch the next page and append the new rows to the table.++## Code Example (Backend - `/api/billing/revenue-events.js`)++```javascript+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { json, wrap, error } from '../_lib/http.js';++const PAGE_SIZE = 20;++export default wrap(async (req, res) => {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized');++ const url = new URL(req.url, 'http://x');+ const cursor = url.searchParams.get('cursor');++ const rows = await sql`+ SELECT+ rev.id,+ rev.created_at,+ rev.skill,+ rev.net_amount,+ ai.name AS agent_name+ FROM agent_revenue_events rev+ JOIN agent_identities ai ON rev.agent_id = ai.id+ WHERE ai.user_id = ${user.id}+ AND (${cursor}::timestamptz IS NULL OR rev.created_at < ${cursor})+ ORDER BY rev.created_at DESC+ LIMIT ${PAGE_SIZE + 1}+ `;++ const hasMore = rows.length > PAGE_SIZE;+ const events = rows.slice(0, PAGE_SIZE);+ const nextCursor = hasMore ? events[events.length - 1].created_at.toISOString() : null;++ return json(res, 200, {+ events,+ next_cursor: nextCursor,+ });+});+```++## Code Example (Frontend - `public/dashboard/dashboard.js`)++```javascript+async function renderRevenue(root) {+ // ... code to render page shell and stats ...++ // Add a container for the table+ root.querySelector('#revenue-events-table-container').innerHTML = `+ <div class="panel">+ <div class="panel-header"><h2>Transaction History</h2></div>+ <div class="panel-body no-pad">+ <table id="revenue-events-table">+ <thead>+ <tr><th>Date</th><th>Agent</th><th>Skill</th><th>Net Earning</th></tr>+ </thead>+ <tbody></tbody>+ </table>+ </div>+ <div class="panel-footer" id="revenue-load-more-container"></div>+ </div>+ `;++ loadRevenueEvents(); // Initial load+}++let eventsNextCursor = null;++async function loadRevenueEvents(cursor = null) {+ const container = document.getElementById('revenue-load-more-container');+ container.innerHTML = cursor ? '<button disabled>Loading...</button>' : '';++ try {+ const url = new URL('/api/billing/revenue-events', location.origin);+ if (cursor) url.searchParams.set('cursor', cursor);+ const res = await fetch(url, { credentials: 'include' });+ const { events, next_cursor } = await res.json();++ const tbody = document.querySelector('#revenue-events-table tbody');+ if (!cursor && !events.length) {+ tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;padding:2rem;">No revenue events yet.</td></tr>';+ container.innerHTML = '';+ return;+ }++ const formatUSDC = (amount) => `$${(Number(amount) / 1e6).toFixed(2)}`;+ tbody.insertAdjacentHTML('beforeend', events.map(e => `+ <tr>+ <td>${new Date(e.created_at).toLocaleDateString()}</td>+ <td>${esc(e.agent_name)}</td>+ <td>${esc(e.skill)}</td>+ <td>${formatUSDC(e.net_amount)}</td>+ </tr>+ `).join(''));++ eventsNextCursor = next_cursor;+ if (next_cursor) {+ container.innerHTML = '<button id="rev-load-more">Load More</button>';+ document.getElementById('rev-load-more').addEventListener('click', () => loadRevenueEvents(eventsNextCursor));+ } else {+ container.innerHTML = '';+ }++ } catch (e) {+ container.innerHTML = `<div class="err">Failed to load history.</div>`;+ }+}+```diff --git a/tasks/monetization-feature/20-payout-wallet-api.md b/tasks/monetization-feature/20-payout-wallet-api.mdnew file mode 100644index 000000000..c4952a5d8--- /dev/null+++ b/tasks/monetization-feature/20-payout-wallet-api.md@@ -0,0 +1,90 @@+# Prompt 20: Payout Wallet API++## Objective+Create backend API endpoints for creators to set, view, and delete their payout wallet addresses.++## Explanation+To receive their earnings, creators must specify a wallet address where they want to get paid. We need to build a secure API to manage this information. For simplicity, we'll start by supporting a single Solana wallet address per user. This information will be stored in the `agent_payout_wallets` table.++## Instructions+1. **Create a New API File:**+ * Create a file at `/api/billing/payout-wallet.js`.++2. **Define the Endpoint Logic:**+ * The endpoint must be authenticated.+ * It should handle multiple HTTP methods:+ * `GET`: To retrieve the user's currently configured payout wallet.+ * `POST` or `PUT`: To create or update the payout wallet address.+ * `DELETE`: To remove the payout wallet address.++3. **Implement `GET` Handler:**+ * Query the `agent_payout_wallets` table.+ * Filter by the `user_id` from the session.+ * Return the wallet address and chain, or `null` if none is configured.++4. **Implement `POST`/`PUT` Handler:**+ * Read the `address` and `chain` from the request body.+ * Perform basic validation on the address format (e.g., check for a valid Solana address format).+ * Use an `INSERT ... ON CONFLICT (user_id, chain) DO UPDATE ...` (UPSERT) statement to create or update the record in `agent_payout_wallets` for the given user and chain.++5. **Implement `DELETE` Handler:**+ * `DELETE` from the `agent_payout_wallets` table where `user_id` and `chain` match.++6. **Add Vercel Routing:**+ * Add a route in `vercel.json` for `/api/billing/payout-wallet`.++## Code Example (Backend - `/api/billing/payout-wallet.js`)++```javascript+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { PublicKey } from '@solana/web3.js'; // For validation++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized');++ if (req.method === 'GET') return handleGet(req, res, user);+ if (req.method === 'POST') return handlePost(req, res, user);+ if (req.method === 'DELETE') return handleDelete(req, res, user);++ return method(req, res, ['GET', 'POST', 'DELETE']);+});++async function handleGet(req, res, user) {+ const [wallet] = await sql`+ SELECT address, chain FROM agent_payout_wallets WHERE user_id = ${user.id} AND chain = 'solana' LIMIT 1+ `;+ return json(res, 200, { wallet: wallet || null });+}++async function handlePost(req, res, user) {+ const { address, chain = 'solana' } = await readJson(req);+ if (chain !== 'solana') return error(res, 400, 'validation_error', 'Only "solana" chain is supported.');++ // Validate Solana address+ try {+ new PublicKey(address);+ } catch {+ return error(res, 400, 'validation_error', 'Invalid Solana address format.');+ }++ const [wallet] = await sql`+ INSERT INTO agent_payout_wallets (user_id, address, chain, is_default)+ VALUES (${user.id}, ${address}, ${chain}, true)+ ON CONFLICT (user_id, chain) DO UPDATE SET address = EXCLUDED.address+ RETURNING address, chain+ `;+ return json(res, 200, { wallet });+}++async function handleDelete(req, res, user) {+ const { chain = 'solana' } = await readJson(req).catch(() => ({}));+ await sql`+ DELETE FROM agent_payout_wallets WHERE user_id = ${user.id} AND chain = ${chain}+ `;+ return json(res, 200, { success: true });+}+```diff --git a/tasks/monetization-feature/21-payout-wallet-ui.md b/tasks/monetization-feature/21-payout-wallet-ui.mdnew file mode 100644index 000000000..fdb56f72e--- /dev/null+++ b/tasks/monetization-feature/21-payout-wallet-ui.md@@ -0,0 +1,124 @@+# Prompt 21: Payout Wallet UI++## Objective+Create the user interface in the Revenue Dashboard for creators to view, add, and edit their Solana payout wallet address.++## Explanation+This is the frontend counterpart to the Payout Wallet API. We need to provide a simple form where a creator can input their Solana address. The UI should fetch the current address on load and allow them to save a new one.++## Instructions+1. **Locate the Frontend Dashboard Code:**+ * Open `public/dashboard/dashboard.js`.++2. **Add UI Placeholder:**+ * In the `renderRevenue` function, add a new panel or section for "Payout Settings" below the stats grid. This section will contain the form.++3. **Create a New Function to Manage the UI:**+ * Create an `async` function `initPayoutSettings()`. Call this from `renderRevenue`.+ * Inside `initPayoutSettings`, first `fetch` the current wallet settings from your `GET /api/billing/payout-wallet` endpoint.+ * Render the form. The input field should be pre-filled with the address if it exists.+ * The "Save" button should be accompanied by a "Remove" button if a wallet is already configured.++4. **Implement Save Logic:**+ * Add a `click` listener to the "Save" button.+ * On click, get the value from the input field.+ * Perform a basic client-side validation (e.g., check if it's not empty).+ * Make a `POST` request to `/api/billing/payout-wallet` with the new address.+ * Show a "Saving..." state, and then "Saved" or an error message based on the API response.++5. **Implement Remove Logic:**+ * Add a `click` listener to the "Remove" button.+ * On click, show a confirmation dialog (`if (confirm(...))`).+ * If confirmed, make a `DELETE` request to `/api/billing/payout-wallet`.+ * On success, clear the input field and remove the "Remove" button.++## Code Example (Frontend - `public/dashboard/dashboard.js`)++```javascript+// In renderRevenue, add the placeholder and call the init function+async function renderRevenue(root) {+ // ... code to render stats ...+ root.innerHTML += `+ <div class="panel">+ <div class="panel-header"><h2>Payout Settings</h2></div>+ <div class="panel-body" id="payout-settings-container">+ Loading settings...+ </div>+ </div>+ `;+ initPayoutSettings();+}++// Add the new function to manage this section+async function initPayoutSettings() {+ const container = document.getElementById('payout-settings-container');+ try {+ const res = await fetch('/api/billing/payout-wallet', { credentials: 'include' });+ const { wallet } = await res.json();+ renderPayoutForm(wallet);+ } catch (e) {+ container.innerHTML = `<div class="err">Failed to load payout settings.</div>`;+ }+}++function renderPayoutForm(wallet) {+ const container = document.getElementById('payout-settings-container');+ container.innerHTML = `+ <div class="form-group">+ <label for="payout-address">Solana Payout Wallet</label>+ <input type="text" id="payout-address" class="form-input" placeholder="Enter your Solana wallet address" value="${wallet ? esc(wallet.address) : ''}">+ <p class="subtle">This is where your earnings will be sent.</p>+ </div>+ <div class="form-actions">+ <button class="btn btn-primary" id="save-payout-btn">Save</button>+ ${wallet ? '<button class="btn btn-danger" id="remove-payout-btn">Remove</button>' : ''}+ <span class="form-status" id="payout-status"></span>+ </div>+ `;++ document.getElementById('save-payout-btn').addEventListener('click', savePayoutWallet);+ if (wallet) {+ document.getElementById('remove-payout-btn').addEventListener('click', removePayoutWallet);+ }+}++async function savePayoutWallet() {+ const status = document.getElementById('payout-status');+ const address = document.getElementById('payout-address').value.trim();+ if (!address) {+ status.textContent = 'Address cannot be empty.';+ return;+ }++ status.textContent = 'Saving...';+ try {+ const res = await fetch('/api/billing/payout-wallet', {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ address, chain: 'solana' }),+ });+ const { wallet } = await res.json();+ if (!res.ok) throw new Error('Failed to save.');++ status.textContent = 'Saved!';+ renderPayoutForm(wallet); // Re-render to add remove button if it's new+ } catch (e) {+ status.textContent = `Error: ${e.message}`;+ }+}++async function removePayoutWallet() {+ if (!confirm('Are you sure you want to remove your payout wallet?')) return;++ const status = document.getElementById('payout-status');+ status.textContent = 'Removing...';+ try {+ await fetch('/api/billing/payout-wallet', { method: 'DELETE', credentials: 'include' });+ status.textContent = 'Removed.';+ renderPayoutForm(null); // Re-render in empty state+ } catch (e) {+ status.textContent = `Error: ${e.message}`;+ }+}+```diff --git a/tasks/monetization-feature/22-withdrawal-api.md b/tasks/monetization-feature/22-withdrawal-api.mdnew file mode 100644index 000000000..774a35411--- /dev/null+++ b/tasks/monetization-feature/22-withdrawal-api.md@@ -0,0 +1,87 @@+# Prompt 22: Withdrawal API++## Objective+Create a backend API endpoint that allows a creator to request a withdrawal of their available balance to their configured payout wallet.++## Explanation+The final step in the money-out flow is the withdrawal. A creator with a positive balance and a configured payout wallet should be able to request a payout. This API will not perform the transfer instantly. Instead, it will log the request in a new `agent_withdrawals` table with a 'pending' status. A separate process (manual for now, but could be a cron job later) would then execute the on-chain transfers and update the status.++## Instructions+1. **Create a New API File:**+ * Create `/api/billing/withdraw.js`.++2. **Define the Endpoint Logic:**+ * The `POST` endpoint must be authenticated.+ * It does not need a request body; it should attempt to withdraw the user's *entire* available balance.++3. **Implement Core Logic:**+ * **Get Balance and Wallet:** In a single transaction for consistency (`BEGIN`/`COMMIT`):+ * Calculate the user's current balance by summing `net_amount` from `agent_revenue_events` and subtracting the sum of `amount` from `agent_withdrawals` (for 'pending' or 'completed' requests).+ * Fetch the user's configured payout wallet from `agent_payout_wallets`.+ * **Validate:**+ * If the balance is zero or less, return an error.+ * If the payout wallet is not configured, return an error.+ * **Create Withdrawal Record:**+ * If validation passes, `INSERT` a new row into the `agent_withdrawals` table.+ * The row should contain the `user_id`, the calculated `amount` (the entire balance), the `currency_mint` (USDC), the `chain` (Solana), the `to_address` from their payout wallet, and a `status` of 'pending'.+ * **Return Success:**+ * Return a 201 status with a success message indicating that the withdrawal request has been submitted.++## Code Example (Backend - `/api/billing/withdraw.js`)++```javascript+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';++const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized');++ try {+ const [result] = await sql.transaction(async (tx) => {+ // Get Payout Wallet+ const [wallet] = await tx`+ SELECT address FROM agent_payout_wallets WHERE user_id = ${user.id} AND chain = 'solana' LIMIT 1+ `;+ if (!wallet) throw new Error('Payout wallet not configured.');++ // Calculate available balance+ const [revenue] = await tx`+ SELECT SUM(rev.net_amount) as total_earned+ FROM agent_revenue_events rev JOIN agent_identities ai ON rev.agent_id = ai.id+ WHERE ai.user_id = ${user.id}+ `;+ const [withdrawn] = await tx`+ SELECT SUM(amount) as total_withdrawn+ FROM agent_withdrawals+ WHERE user_id = ${user.id} AND status IN ('pending', 'completed')+ `;+ const balance = BigInt(revenue.total_earned || 0) - BigInt(withdrawn.total_withdrawn || 0);++ if (balance <= 0) throw new Error('Insufficient balance to withdraw.');++ // Insert pending withdrawal record+ const [withdrawal] = await tx`+ INSERT INTO agent_withdrawals (user_id, amount, currency_mint, chain, to_address, status)+ VALUES (${user.id}, ${balance}, ${USDC_MINT}, 'solana', ${wallet.address}, 'pending')+ RETURNING id, amount, created_at+ `;+ return withdrawal;+ });++ return json(res, 201, {+ message: `Withdrawal request for ${Number(result.amount) / 1e6} USDC submitted successfully.`,+ withdrawal_id: result.id,+ });++ } catch (e) {+ return error(res, 400, 'withdrawal_error', e.message);+ }+});+```diff --git a/tasks/monetization-feature/23-withdrawal-ui.md b/tasks/monetization-feature/23-withdrawal-ui.mdnew file mode 100644index 000000000..95a2451dd--- /dev/null+++ b/tasks/monetization-feature/23-withdrawal-ui.md@@ -0,0 +1,135 @@+# Prompt 23: Withdrawal UI++## Objective+Create the user interface in the Revenue Dashboard for creators to see their current balance and request a withdrawal.++## Explanation+This UI component will tie together the balance calculation and the withdrawal API. It should clearly display the creator's withdrawable balance and provide a simple button to initiate the payout process. It should also include a section to display the history of their withdrawal requests.++## Instructions+1. **Locate Frontend Dashboard Code:**+ * Open `public/dashboard/dashboard.js`.++2. **Add Withdrawal UI Section:**+ * In the `renderRevenue` function, add a new panel for "Withdrawals" below the Payout Settings.+ * This panel should contain:+ * A display for the "Available Balance" (this will use the same data from the stats API).+ * A "Request Withdrawal" button. This button should be disabled if the balance is zero.+ * A placeholder for a table to show withdrawal history.++3. **Implement Withdrawal Request Logic:**+ * Add a `click` listener to the "Request Withdrawal" button.+ * When clicked, it should make a `POST` request to the `/api/billing/withdraw` endpoint.+ * While the request is pending, disable the button and show a "Processing..." message.+ * On success, display a success message (e.g., using a toast notification) and update the balance to show $0.00.+ * On error, display the error message from the API.++4. **Implement Withdrawal History:**+ * Create a new API endpoint `/api/billing/withdrawals` that fetches a user's withdrawal history from the `agent_withdrawals` table (paginated).+ * Create a function `loadWithdrawalHistory()` in `dashboard.js`.+ * This function should fetch from the new endpoint and render the results in a table, showing the date, amount, status (`pending`, `completed`, `failed`), and destination address for each withdrawal.++## Code Example (Frontend UI - in `renderRevenue` function of `dashboard.js`)++```javascript+// In renderRevenue function, after the payout settings panel+root.innerHTML += `+ <div class="panel">+ <div class="panel-header"><h2>Withdrawals</h2></div>+ <div class="panel-body" id="withdrawal-container">+ <div class="withdrawal-balance-area">+ <span>Available Balance</span>+ <strong id="withdrawal-balance-display">Loading...</strong>+ </div>+ <button class="btn btn-primary" id="request-withdrawal-btn" disabled>Request Withdrawal</button>+ <span class="form-status" id="withdrawal-status"></span>+ </div>+ </div>+ <div class="panel">+ <div class="panel-header"><h3>Withdrawal History</h3></div>+ <div class="panel-body no-pad">+ <table id="withdrawal-history-table">+ <thead><tr><th>Date</th><th>Amount</th><th>Status</th><th>Address</th></tr></thead>+ <tbody><tr><td colspan="4">Loading history...</td></tr></tbody>+ </table>+ </div>+ </div>+`;++// In your main stats loading logic, also update the balance display here+function renderRevenueStats(stats) {+ // ...+ const balanceEl = document.getElementById('withdrawal-balance-display');+ balanceEl.textContent = formatUSDC(stats.current_balance);+ const withdrawalBtn = document.getElementById('request-withdrawal-btn');+ if (Number(stats.current_balance) > 0) {+ withdrawalBtn.disabled = false;+ }+}++// Then, add the event listener+document.getElementById('request-withdrawal-btn').addEventListener('click', handleWithdrawalRequest);++loadWithdrawalHistory(); // Also call this+```++## Code Example (Frontend JS - new functions in `dashboard.js`)++```javascript+async function handleWithdrawalRequest() {+ if (!confirm('Are you sure you want to withdraw your entire available balance?')) return;++ const btn = document.getElementById('request-withdrawal-btn');+ const status = document.getElementById('withdrawal-status');++ btn.disabled = true;+ status.textContent = 'Submitting request...';++ try {+ const res = await fetch('/api/billing/withdraw', {+ method: 'POST',+ credentials: 'include',+ });+ const body = await res.json();+ if (!res.ok) throw new Error(body.error_description || 'Request failed.');++ status.textContent = body.message; // Success message from API+ // Refresh all revenue data+ const stats = await api.getRevenueStats();+ renderRevenueStats(stats);+ loadWithdrawalHistory();++ } catch (e) {+ status.textContent = `Error: ${e.message}`;+ btn.disabled = false; // Re-enable on failure+ }+}++async function loadWithdrawalHistory() {+ const tbody = document.querySelector('#withdrawal-history-table tbody');+ try {+ // Assume you create this API endpoint+ const res = await fetch('/api/billing/withdrawals', { credentials: 'include' });+ const { withdrawals } = await res.json();++ if (!withdrawals.length) {+ tbody.innerHTML = '<tr><td colspan="4" style="text-align:center;">No withdrawal history.</td></tr>';+ return;+ }++ const formatUSDC = (amount) => `${(Number(amount) / 1e6).toFixed(2)} USDC`;+ tbody.innerHTML = withdrawals.map(w => `+ <tr>+ <td>${new Date(w.created_at).toLocaleString()}</td>+ <td>${formatUSDC(w.amount)}</td>+ <td><span class="status-badge ${w.status}">${w.status}</span></td>+ <td>${esc(w.to_address.slice(0, 4))}...${esc(w.to_address.slice(-4))}</td>+ </tr>+ `).join('');++ } catch (e) {+ tbody.innerHTML = `<tr><td colspan="4" class="err">Failed to load history.</td></tr>`;+ }+}+```+You will also need to add some basic CSS for `.status-badge`.diff --git a/tasks/monetization-feature/24-add-toast-notifications.md b/tasks/monetization-feature/24-add-toast-notifications.mdnew file mode 100644index 000000000..c2d040dce--- /dev/null+++ b/tasks/monetization-feature/24-add-toast-notifications.md@@ -0,0 +1,107 @@+# Prompt 24: Implement Toast Notifications++## Objective+Integrate a simple, reusable toast notification system to provide users with clear, non-blocking feedback for actions like saving settings, successful payments, or errors.++## Explanation+Status messages next to buttons are good, but they can be missed. Toast notifications are small popups (usually in a corner of the screen) that provide timely feedback. They are a standard feature in modern web apps and greatly improve the user experience. We will create a simple, vanilla JS system for this.++## Instructions+1. **Add HTML and CSS:**+ * In your main layout/HTML files (e.g., `marketplace.html`, `pump-dashboard.html`), add a container element for toasts. It should be fixed to a corner of the viewport.+ * Add CSS to style the container and the individual toast messages. Toasts should have different styles for success, error, and info.++2. **Create a JavaScript Helper:**+ * In a shared JavaScript file (or create a new one like `src/ui-helpers.js`), write a function like `showToast(message, type = 'info', duration = 3000)`.+ * The function should:+ * Create a new `div` element for the toast.+ * Add the `message` text to it.+ * Add a class based on the `type` (e.g., `toast-success`, `toast-error`).+ * Append the new toast to the toast container element.+ * Use a `setTimeout` to automatically remove the toast element after the `duration`.+ * Consider adding an animation for the toast appearing and disappearing.++3. **Integrate with Existing Logic:**+ * Go through the feature code you've already written and replace or augment `status.textContent` messages with calls to your new `showToast` function.+ * **Payment Flow (`marketplace.js`):**+ * Show a success toast: `showToast('Payment successful! Skill unlocked.', 'success')`.+ * Show an error toast: `showToast(\`Error: ${error.message}\`, 'error')`.+ * **Payout Settings (`dashboard.js`):**+ * `showToast('Payout wallet saved.', 'success')`.+ * `showToast('Withdrawal request submitted.', 'success')`.++## Code Example (HTML & CSS)++Add to a main HTML file (e.g., `marketplace.html`):+```html+<!-- At the end of <body> -->+<div id="toast-container"></div>+```++Add to a main CSS file (e.g., `style.css`):+```css+#toast-container {+ position: fixed;+ bottom: 20px;+ right: 20px;+ z-index: 1000;+ display: flex;+ flex-direction: column;+ gap: 10px;+}++.toast {+ padding: 12px 16px;+ border-radius: 6px;+ color: #fff;+ font-size: 14px;+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);+ animation: toast-in 0.3s ease;+ opacity: 0.95;+}++.toast.toast-info {+ background-color: #374151;+}+.toast.toast-success {+ background-color: #059669;+}+.toast.toast-error {+ background-color: #b91c1c;+}++@keyframes toast-in {+ from {+ transform: translateX(100%);+ opacity: 0;+ }+ to {+ transform: translateX(0);+ opacity: 0.95;+ }+}+```++## Code Example (JavaScript Helper)++```javascript+// In a new file src/ui-helpers.js or similar+function showToast(message, type = 'info', duration = 3000) {+ const container = document.getElementById('toast-container');+ if (!container) return;++ const toast = document.createElement('div');+ toast.className = `toast toast-${type}`;+ toast.textContent = message;++ container.appendChild(toast);++ setTimeout(() => {+ toast.remove();+ }, duration);+}++// In marketplace.js, after a successful payment:+// showToast('Payment successful! Skill unlocked.', 'success');+```+Make sure to import/include this helper function where you need it.diff --git a/tasks/monetization-feature/25-end-to-end-testing-plan.md b/tasks/monetization-feature/25-end-to-end-testing-plan.mdnew file mode 100644index 000000000..0c0b61e7e--- /dev/null+++ b/tasks/monetization-feature/25-end-to-end-testing-plan.md@@ -0,0 +1,111 @@+# Prompt 25: End-to-End Testing Plan++## Objective+Write a comprehensive manual testing plan that a QA tester or developer can follow to validate the entire agent monetization feature from start to finish.++## Explanation+A complex feature like this has many moving parts. A structured testing plan ensures that we cover all critical paths and edge cases. This document will serve as a checklist to verify that the system works as expected before deploying to production. This is not about writing automated tests (which would be a separate, larger effort), but about defining the manual steps to confirm functionality.++## Instructions+Based on the features we've designed in the previous 24 prompts, write a detailed testing plan. Structure it into sections. For each test case, describe the prerequisite, the steps to perform, and the expected outcome.++---++## Agent Monetization: E2E Testing Plan++### **Section 1: Agent Creator Flow (Monetization Setup)**++**Test Case 1.1: Setting a Skill Price**+* **Prerequisite:** User is logged in and has at least one agent with defined skills.+* **Steps:**+ 1. Navigate to the agent edit page (`/agent/:id/edit`).+ 2. Go to the "Monetization" tab.+ 3. Enter a valid price (e.g., `1.50`) for a skill.+ 4. Enter an invalid price (e.g., `abc` or a negative number).+ 5. Click "Save Prices".+ 6. Reload the page.+* **Expected Outcome:**+ * The invalid price should show a validation error and not save.+ * The valid price should save successfully, showing a "Saved" status/toast.+ * After reloading, the saved price (`1.50`) should be correctly displayed in the input field.++**Test Case 1.2: Updating and Removing a Skill Price**+* **Prerequisite:** A skill already has a price set.+* **Steps:**+ 1. Navigate to the "Monetization" tab for the agent.+ 2. Change the price of the skill to a new value (e.g., `2.00`). Click "Save".+ 3. Clear the price input field for the skill. Click "Save".+* **Expected Outcome:**+ * The price should update successfully to `2.00`.+ * Clearing the price should successfully set the price to 0 (making the skill free again). The UI should reflect this on reload.++**Test Case 1.3: Verifying Price in Marketplace**+* **Prerequisite:** An agent is published and has a priced skill.+* **Steps:**+ 1. Navigate to the marketplace grid view (`/marketplace`).+ 2. Find the agent.+ 3. Navigate to the agent's detail page.+* **Expected Outcome:**+ * The agent card in the grid should display the "$ Paid" badge.+ * On the detail page, the skill should be listed with the correct price (e.g., "1.50 USDC").++### **Section 2: End-User Purchase Flow**++**Test Case 2.1: Successful Purchase**+* **Prerequisite:** Logged in as a different user (not the creator). Have a Solana wallet (e.g., Phantom) with devnet USDC. The agent skill has a price.+* **Steps:**+ 1. Go to the agent's detail page.+ 2. Click the "Purchase" button for the paid skill.+ 3. The payment modal should appear.+ 4. Click "Connect Wallet" and approve the connection in the wallet.+ 5. The modal should update to show the connected wallet.+ 6. Click "Confirm Purchase".+ 7. Approve the transaction in the wallet popup.+ 8. Wait for the on-chain and backend confirmation steps.+ 9. After the modal closes, observe the skill on the detail page.+ 10. Reload the page.+* **Expected Outcome:**+ * The modal should show success messages at each step.+ * After the flow completes, the skill's button should change to "Unlocked".+ * After reloading, the button should still say "Unlocked".++**Test Case 2.2: User Rejects Wallet Transaction**+* **Prerequisite:** Same as 2.1.+* **Steps:**+ 1. Proceed through the purchase flow until the wallet popup asks for transaction approval.+ 2. Click "Reject" in the wallet.+* **Expected Outcome:**+ * The payment modal should display an error message (e.g., "Transaction rejected by user.").+ * The modal should remain open, and the "Confirm Purchase" button should become active again.++### **Section 3: Creator Revenue & Payout Flow**++**Test Case 3.1: Verify Revenue Event**+* **Prerequisite:** A skill has been successfully purchased (Test Case 2.1 completed). Log in as the agent creator.+* **Steps:**+ 1. Navigate to the Dashboard, then the "Revenue" tab.+* **Expected Outcome:**+ * The "Current Balance" and other stats should reflect the net amount from the sale.+ * The "Transaction History" table should show a new entry for the skill purchase, with the correct agent, skill, and net amount.++**Test Case 3.2: Manage Payout Wallet**+* **Prerequisite:** Logged in as the creator.+* **Steps:**+ 1. Navigate to the "Revenue" tab.+ 2. In "Payout Settings", enter a valid Solana address and click "Save".+ 3. Enter an invalid address and click "Save".+ 4. Click "Remove".+* **Expected Outcome:**+ * The valid address should save successfully.+ * The invalid address should show a validation error.+ * The "Remove" button should successfully clear the address after confirmation.++**Test Case 3.3: Request Withdrawal**+* **Prerequisite:** Logged in as creator. Have a positive "Available Balance" and a configured payout wallet.+* **Steps:**+ 1. Navigate to the "Revenue" tab.+ 2. Click the "Request Withdrawal" button.+* **Expected Outcome:**+ * A success toast/message should appear.+ * The "Available Balance" should immediately update to $0.00.+ * The "Withdrawal History" table should show a new entry with the status "pending".