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
Subscription checkouts, skill gifts, on-chain skill license, gasless tx, MonetizationService, and marketplace updates
nirholas3d9c27b96f1d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db707c086..0c6bb533c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Connect a wallet and your $THREE tier is recognized — no account needed** — You no longer need a three.ws account to be seen as a $THREE holder. Connect your Solana wallet and the site reads your tier straight from your on-chain holdings: the holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) and holder features like High-quality generation on Forge unlock from the connected wallet alone. When a feature needs proof the wallet is yours, you approve a single free signature that moves no funds. Switch or disconnect a wallet and your tier updates instantly, no reload. Signed-in accounts keep working exactly as before. (`/forge`) `[improvement]`- **Embedded 3D agents animate on any site, not just three.ws** — When you drop the <agent-3d> tag onto a page hosted somewhere other than three.ws, the avatar's gestures — waving, celebrating, thinking — silently failed to load: the animation clips were being requested from the host page's own domain instead of from three.ws, so each one came back as a 404. The component now resolves its animation library against three.ws no matter where it's embedded, so an agent reacts and emotes correctly on partner pages, live demos, and any third-party site. `[fix, sdk]`- **Faster marketplace — agent pages load skill prices from cache** — Agent and marketplace pages now feel snappier. A creator's skill prices are cached for an hour and shared across our servers instead of being re-read from the database on every single page view, so opening an agent, browsing the marketplace, or checking what a skill costs returns faster — especially for popular agents. The cache stays honest: the moment a creator changes a price the old value is cleared everywhere, so you always see the current price, and a purchase is still quoted against the exact price at checkout time. `[improvement, infra]`+- **Forge always reaches for a free 3D engine first** — Text-to-3D and image-to-3D generation now exhaust the free engines before any paid one. A prompt is rendered on the free NVIDIA lane; if that's busy, the reference image is reconstructed into a mesh on a free engine too — the platform only reaches for a paid engine as a genuine last resort. And if every engine is briefly out of reach, you now get an honest "temporarily unavailable, try again shortly" instead of a confusing technical billing message. Same Forge, fewer dead ends, no surprise costs. (`/forge`) `[improvement, fix]`- **Forge checkout no longer dead-ends when generation is briefly busy** — When the 3D generator was momentarily rate-limited mid-checkout, Forge could show a raw technical error and look like the payment had failed for good. Now a brief upstream slowdown shows a clear message — your payment was not taken, and the generation retries in a few seconds — and the checkout auto-retries on its own before ever asking you to try again. Your payment only settles once the model is actually produced, so a busy moment never costs you anything. (`/forge`) `[fix]`- **Gasless checkout — buy skills and assets with no SOL in your wallet** — Buying a skill, time-pass, or whole asset no longer requires you to hold SOL for the network fee. When your Solana wallet is connected, three.ws now sponsors the transaction fee: the platform builds and pre-signs the payment, and your wallet only adds your own approval. You still pay the USDC price (and sellers still receive their split), but the tiny gas fee is on us — one fewer thing to top up before you check out. If sponsorship is ever unavailable, checkout falls back to the normal pay-your-own-gas flow automatically, so a purchase never gets blocked. `[feature, improvement]`- **Graduated coins show a live price on agent and community cards** — The bonding-curve card — the compact one on agent profiles, community coin pages, and embeddable widgets — used to go blank with a “No active bonding curve” message the moment a coin graduated to a DEX. Now it reads the coin's live on-chain price instead, marks it “Graduated” at 100%, and shows a real market cap, so $THREE and any other migrated coin display a refreshing price rather than empty space. Those cards also stopped opening a background websocket that could never connect — it had been silently retrying and logging errors on every load. Vault balances now refresh by polling directly and update within seconds. `[improvement, fix]`@@ -29,6 +30,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Pole Club avatar swaps now actually stick** — On the Pole Club stage, tapping “Change avatar” and picking a new look sometimes did nothing — the dancer quietly snapped back to the default. Two fixes: a pick made right after the room loads is no longer overwritten by the room's own startup, and any avatar whose rig can't be animated is now clearly flagged “can’t dance” and skipped — the dancer keeps her current look and a message says why, instead of silently failing. Picks that work apply instantly and stay put. (`/club`) `[fix]`- **See every skill you've bought and sold in one Transactions tab** — The dashboard now has a Transactions page that lays out your full payment history in one place: every skill you've purchased from other agents and every sale your own agents have made, newest first. Each row shows the date, whether it was a purchase or a sale, the skill and agent involved, the USDC amount (sellers see their take-home net of the platform fee), and a link straight to the transaction on Solscan or Basescan. Filter by purchases or sales, and download the whole thing as a CSV for your records or taxes. (`/dashboard/transactions`) `[feature]`- **Steadier token prices and 3D generation when a provider is busy** — Live bonding-curve prices, market caps, and trade quotes now stay accurate even when a Solana data provider hits its rate limit: the platform transparently rotates to a healthy provider and parks the busy one, instead of repeatedly retrying a maxed-out endpoint and showing stale numbers. The free text-to-3D forge also rides out a cold or briefly-unavailable generation node by retrying once before falling back, so a momentary upstream hiccup no longer turns into a failed generation. `[fix, infra]`+- **Subscribe to an agent in one click — pay once, unlock every paid skill** — Agent pages now show the creator's subscription tiers right under skills & pricing, each with a Subscribe button. Pick a tier, confirm the price and billing cycle in the checkout, and approve a single USDC payment in your wallet — the platform covers the network fee, so you don't need any SOL. Once the payment confirms on-chain your subscription goes live instantly and unlocks all of that agent's paid skills for the period; the page marks tiers you're already on so you never pay twice. Built on the same verified on-chain settlement as one-off skill purchases. (`/marketplace`) `[feature]`- **The $THREE page now shows a live price chart** — $THREE graduated long ago, so the token page no longer has a bonding curve to climb — but the page still showed a “No active bonding curve” placeholder where the chart should be. That dead space is now a real, live price chart: an area chart with a volume panel underneath, pulling actual trade history (Birdeye with a GeckoTerminal fallback) and refreshing every 30 seconds. Switch between 5m, 15m, 1H, 4H, and 1D timeframes, and read the price and percentage move over the window you're viewing — green when it's up, red when it's down. Buy $THREE and the live trade tape sit right alongside it, unchanged. (`/three-token`) `[improvement]`- **The 3D agent on the homepage moves again instead of standing frozen** — The live avatar in the homepage hero had stopped animating — it loaded but stood in a stiff arms-out pose, and the Wave, Dance, and Pray buttons did nothing. The viewer only renders frames while something is moving to save your battery, and a recent change meant that starting an animation no longer woke the renderer back up once it had gone idle, so the avatar was stuck on its first frame. The renderer is now nudged awake the instant any animation starts, so the homepage agent idles, walks, and responds to the move buttons as intended. `[fix]`- **The animated 3D bot in the site footer renders again** — The little animated 3D robot that sits in the footer across the site — and on the sign-in page — had gone missing, leaving an empty space. The model files it loads are compressed, but the footer loader wasn't set up to unpack that format, so it failed before the bot could appear. The decoder is now wired in, so the bot loads and spins as intended everywhere the footer shows. `[fix]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 0d963a96e..7138be306 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -25,6 +25,8 @@ bottom.| Integration demos | [multiplayer/](multiplayer), [examples/coach-leo/](examples/coach-leo) | In-repo | Multiplayer and VR demos || Avatar service backend | [api/](api) + [workers/](workers) | In-repo | Vercel functions + Cloudflare workers || On-chain identity | [contracts/](contracts) | In-repo | Foundry-based on-chain agent identity, ERC-8004 |+| On-chain skill licenses | [contracts/skill-license/](contracts/skill-license) `→ /api/skills/license-onchain` | In-repo | Anchor program: each purchased skill = a 1/1 SPL NFT + `SkillLicense` PDA, a trustless alternative to DB-backed access checks. Backend: [api/_lib/skill-license-onchain.js](api/_lib/skill-license-onchain.js) |+| On-chain agent invocation | [contracts/agent-invocation/](contracts/agent-invocation) | In-repo | Anchor program: verifiable agent-to-agent skill invocation events. SDK: [agent-protocol-sdk/](agent-protocol-sdk) || Cross-chain SDKs | [sdk/](sdk), [solana-agent-sdk/](solana-agent-sdk), [agent-payments-sdk/](agent-payments-sdk), [agent-protocol-sdk/](agent-protocol-sdk) | Published | Cross-chain agent SDKs || MCP integration | [mcp-server/](mcp-server), [mcp-bridge/](mcp-bridge) | Published as `@three-ws/mcp-server` | Model Context Protocol surface || SNS naming + pay-by-name | [api/sns.js](api/sns.js), [api/sns-subdomain.js](api/sns-subdomain.js), [api/threews/subdomain.js](api/threews/subdomain.js), [api/x402/pay-by-name.js](api/x402/pay-by-name.js), [src/solana/sns-subdomain.js](src/solana/sns-subdomain.js), [pages/threews-claim.html](pages/threews-claim.html) | In-repo | `*.threews.sol` subdomain mint, x402 payments addressed by name. Env: `THREEWS_SOL_PARENT_SECRET_BASE58`. See [SNS_PARTNERSHIP_PROPOSAL.md](docs/internal/SNS_PARTNERSHIP_PROPOSAL.md) |diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.jsindex c3c2c8c05..51c069bec 100644--- a/api/_lib/forge-tiers.js+++ b/api/_lib/forge-tiers.js@@ -340,6 +340,20 @@ function readEnv(name) {return null;}+// Free-first reconstruct ordering. When ON (the default), the forge prefers the+// free reconstruct lane (HuggingFace Spaces) over the paid Replicate default+// BEFORE it ever submits to the paid account — so a generation never spends on,+// nor dead-ends against, the paid lane while a free lane can serve it. The native+// free NVIDIA NIM text→3D lane is always tried first regardless; this governs the+// reconstruct step (image→3D, and the text→3D fallback after NIM). Reversible:+// set FORGE_PREFER_FREE=false to restore the fast paid-default ordering once the+// paid account is funded. Defaults ON because the platform's stance is free-first.+export function preferFreeReconstruct() {+ const v = readEnv('FORGE_PREFER_FREE');+ if (v == null || v === '') return true;+ return !/^(0|false|off|no)$/i.test(String(v).trim());+}+// A platform backend is "live" only when its required env is present. BYOK// backends are always selectable — liveness depends on the caller's key, which// is resolved per-request, not here.diff --git a/api/_lib/migrations/20260618130000_subscription_checkouts.sql b/api/_lib/migrations/20260618130000_subscription_checkouts.sqlnew file mode 100644index 000000000..5ea082082--- /dev/null+++ b/api/_lib/migrations/20260618130000_subscription_checkouts.sql@@ -0,0 +1,50 @@+-- Pending on-chain checkouts for the user→agent subscription flow.+--+-- When a user subscribes to an agent tier, the server quotes an exact USDC+-- split (creator leg + platform fee leg), mints a Solana-Pay reference, and+-- builds a transaction the buyer signs. That quote must be persisted server-side+-- so /api/subscriptions/verify validates the SAME amounts the buyer signed —+-- the client is never trusted for the price or the recipient. This mirrors the+-- role skill_purchases plays for one-off skill unlocks.+--+-- The row advances pending → confirmed (or failed/expired) exactly once; the+-- activated subscription lands in creator_subscriptions + user_agent_subscriptions.+--+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260618130000_subscription_checkouts.sql+-- Idempotent.++begin;++create table if not exists subscription_checkouts (+ id uuid primary key default gen_random_uuid(),+ reference text not null unique, -- base58 Solana-Pay reference pubkey+ user_id uuid not null references users(id) on delete cascade,+ plan_id uuid not null references subscription_plans(id) on delete cascade,+ agent_id uuid references agent_identities(id) on delete set null,+ status text not null default 'pending'+ check (status in ('pending', 'confirmed', 'failed', 'expired')),+ amount bigint not null, -- gross atomics the buyer pays+ creator_amount bigint not null, -- seller leg (gross − fee)+ platform_fee_amount bigint not null default 0,+ platform_fee_wallet text,+ currency_mint text not null,+ chain text not null default 'solana',+ recipient text not null, -- creator payout address+ buyer_public_key text,+ interval text not null, -- 'weekly' | 'monthly' (from the plan)+ tx_signature text,+ expires_at timestamptz not null,+ confirmed_at timestamptz,+ created_at timestamptz not null default now()+);++-- One live pending checkout per (user, plan): the subscribe endpoint reuses a+-- fresh pending row on retry instead of minting a new reference each click.+create unique index if not exists subscription_checkouts_pending_uq+ on subscription_checkouts(user_id, plan_id)+ where status = 'pending';++create index if not exists subscription_checkouts_user_idx+ on subscription_checkouts(user_id);++commit;diff --git a/api/_lib/migrations/20260618140000_skill_gifts.sql b/api/_lib/migrations/20260618140000_skill_gifts.sqlnew file mode 100644index 000000000..9d27a51be--- /dev/null+++ b/api/_lib/migrations/20260618140000_skill_gifts.sql@@ -0,0 +1,33 @@+-- Migration: gifting skills.+-- A buyer can purchase a skill for another user. The payer stays in `user_id`+-- (they sign the on-chain payment, poll confirm, and own the receipt); the+-- beneficiary who receives access is recorded in `recipient_user_id`.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260618140000_skill_gifts.sql+-- Idempotent.+--+-- Beneficiary = COALESCE(recipient_user_id, user_id):+-- • self-purchase → recipient_user_id NULL → beneficiary is the buyer.+-- • gift → recipient_user_id set → beneficiary is the recipient.+-- The access grant (skill_access_grants) and the already-owned short-circuit+-- both key off the beneficiary, so a buyer may gift the same skill to many+-- distinct recipients while still never double-paying for their own copy.++begin;++alter table skill_purchases+ add column if not exists recipient_user_id uuid references users(id);++create index if not exists skill_purchases_recipient+ on skill_purchases (recipient_user_id)+ where recipient_user_id is not null;++-- Replace the per-buyer active-ownership guard with a per-beneficiary one, so+-- "at most one active (confirmed/trial) copy" is enforced against whoever+-- actually receives the skill — not the wallet that paid for it.+drop index if exists skill_purchases_one_active_per_user;+drop index if exists skill_purchases_one_active_per_beneficiary;+create unique index if not exists skill_purchases_one_active_per_beneficiary+ on skill_purchases (coalesce(recipient_user_id, user_id), agent_id, skill)+ where status in ('confirmed', 'trial');++commit;diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.jsindex a15b8a146..476f356dd 100644--- a/api/_lib/purchase-confirm.js+++ b/api/_lib/purchase-confirm.js@@ -96,6 +96,9 @@ async function emitReceipt(purchase, txSignature, payoutAddress, kind) {purchase_id: purchase.id,reference: purchase.reference,user_id: purchase.user_id,+ ...(purchase.recipient_user_id && purchase.recipient_user_id !== purchase.user_id+ ? { recipient_user_id: purchase.recipient_user_id }+ : {}),agent_id: purchase.agent_id,skill: purchase.skill,amount: String(purchase.amount),@@ -443,9 +446,13 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfoRETURNING id, kind, valid_until`;if (updated.length > 0) {- // Grant skill access. Permanent purchases get a non-expiring grant;- // time-passes expire at their valid_until window. The skill_access_grants- // table is the authoritative access record; skill_purchases tracks payment.+ // Grant skill access to the BENEFICIARY. For a gift that's the recipient+ // (recipient_user_id); for a normal purchase it's the payer (user_id).+ // Permanent purchases get a non-expiring grant; time-passes expire at their+ // valid_until window. skill_access_grants is the authoritative access+ // record; skill_purchases tracks payment.+ const beneficiaryId = pur.recipient_user_id || pur.user_id;+ const isGift = !!pur.recipient_user_id && pur.recipient_user_id !== pur.user_id;const confirmedRow = updated[0];const grantExpiresAt = confirmedRow.kind === 'time_pass' && confirmedRow.valid_until? confirmedRow.valid_until@@ -455,7 +462,7 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfoINSERT INTO skill_access_grants(user_id, agent_id, skill_name, purchase_id, expires_at)VALUES- (${pur.user_id}, ${pur.agent_id}, ${pur.skill}, ${pur.id}, ${grantExpiresAt})+ (${beneficiaryId}, ${pur.agent_id}, ${pur.skill}, ${pur.id}, ${grantExpiresAt})ON CONFLICT (user_id, agent_id, skill_name) DO UPDATESET expires_at = EXCLUDED.expires_at,purchase_id = EXCLUDED.purchase_id,@@ -524,16 +531,45 @@ async function finalizeSkillConfirmation(pur, txSignature, payoutAddress, platfocurrency_mint: pur.currency_mint,tx_signature: txSignature,purchase_id: pur.id,+ gift: isGift,+ });+ }+ if (isGift) {+ // Tell the recipient they were gifted access, and confirm delivery to+ // the buyer. Names are best-effort, resolved from public profile fields.+ const [gifterName, recipientName] = await Promise.all([+ getUserDisplay(pur.user_id),+ getUserDisplay(beneficiaryId),+ ]);+ await insertNotification(beneficiaryId, 'skill_gift_received', {+ agent_id: pur.agent_id,+ skill: pur.skill,+ from: gifterName,+ from_user_id: pur.user_id,+ currency_mint: pur.currency_mint,+ tx_signature: txSignature,+ purchase_id: pur.id,+ });+ await insertNotification(pur.user_id, 'skill_gift_sent', {+ agent_id: pur.agent_id,+ skill: pur.skill,+ to: recipientName,+ to_user_id: beneficiaryId,+ amount: grossAmt.toString(),+ currency_mint: pur.currency_mint,+ tx_signature: txSignature,+ purchase_id: pur.id,+ });+ } else {+ await insertNotification(pur.user_id, 'skill_purchase_confirmed', {+ agent_id: pur.agent_id,+ skill: pur.skill,+ amount: grossAmt.toString(),+ currency_mint: pur.currency_mint,+ tx_signature: txSignature,+ purchase_id: pur.id,});}- await insertNotification(pur.user_id, 'skill_purchase_confirmed', {- agent_id: pur.agent_id,- skill: pur.skill,- amount: grossAmt.toString(),- currency_mint: pur.currency_mint,- tx_signature: txSignature,- purchase_id: pur.id,- });if (pur.referrer_user_id && referralAmt > 0n) {await insertNotification(pur.referrer_user_id, 'referral_earned', {skill: pur.skill,@@ -551,3 +587,15 @@ async function getSellerUserId(agentId) {const [row] = await sql`SELECT user_id FROM agent_identities WHERE id = ${agentId}`;return row?.user_id ?? null;}++// Best-effort friendly label for a user (gift notifications). Username first,+// then display name, then a short id — never the email.+async function getUserDisplay(userId) {+ if (!userId) return null;+ try {+ const [row] = await sql`SELECT username, display_name FROM users WHERE id = ${userId}`;+ return row?.username || row?.display_name || `user ${String(userId).slice(0, 8)}`;+ } catch {+ return null;+ }+}diff --git a/api/_lib/resolve-recipient.js b/api/_lib/resolve-recipient.jsnew file mode 100644index 000000000..cb00cb6ca--- /dev/null+++ b/api/_lib/resolve-recipient.js@@ -0,0 +1,82 @@+// Resolve a gift recipient from a public identifier the gifter typed:+// a username (@-prefix optional), a wallet address (EVM 0x… or Solana base58),+// or a raw user id. Returns a *public* profile only — never email, never the+// private account fields — so this can safely back an authenticated lookup+// endpoint without leaking who holds which email.+//+// Resolution order is identifier-shaped, not a blind fan-out:+// uuid → users.id+// 0x… → users.wallet_address OR user_wallets.address (case-insensitive)+// base58 → user_wallets.address (Solana, case-sensitive)+// else → username (case-insensitive)+//+// Email is intentionally NOT resolvable here: usernames and wallet addresses+// are public handles; emails are not, and matching on them would turn this into+// an account-enumeration oracle.++import { sql } from './db.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const EVM_RE = /^0x[0-9a-fA-F]{40}$/;+const SOL_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const PUBLIC_COLS = 'id, username, display_name, avatar_url';++/**+ * @param {string} identifier - username, wallet address, or user id.+ * @returns {Promise<{id:string, username:string|null, display_name:string|null, avatar_url:string|null}|null>}+ */+export async function resolveRecipient(identifier) {+ if (typeof identifier !== 'string') return null;+ let q = identifier.trim();+ if (!q) return null;+ if (q[0] === '@') q = q.slice(1).trim();+ if (!q) return null;++ // 1. Raw user id.+ if (UUID_RE.test(q)) {+ const [u] = await sql`+ SELECT id, username, display_name, avatar_url+ FROM users WHERE id = ${q} AND deleted_at IS NULL LIMIT 1`;+ return u ?? null;+ }++ // 2. EVM wallet — stored lowercased on both the login column and user_wallets.+ if (EVM_RE.test(q)) {+ const lc = q.toLowerCase();+ const [u] = await sql`+ SELECT u.id, u.username, u.display_name, u.avatar_url+ FROM users u+ WHERE u.deleted_at IS NULL+ AND (lower(u.wallet_address) = ${lc}+ OR EXISTS (+ SELECT 1 FROM user_wallets w+ WHERE w.user_id = u.id AND lower(w.address) = ${lc}))+ LIMIT 1`;+ return u ?? null;+ }++ // 3. Solana wallet — base58 is case-sensitive, matched verbatim.+ if (SOL_RE.test(q)) {+ const [u] = await sql`+ SELECT u.id, u.username, u.display_name, u.avatar_url+ FROM users u+ JOIN user_wallets w ON w.user_id = u.id+ WHERE u.deleted_at IS NULL AND w.address = ${q} AND w.chain_type = 'solana'+ LIMIT 1`;+ if (u) return u;+ // fall through: a base58-shaped string could still be a literal username.+ }++ // 4. Username (case-insensitive).+ const [u] = await sql`+ SELECT id, username, display_name, avatar_url+ FROM users+ WHERE lower(username) = lower(${q}) AND deleted_at IS NULL+ LIMIT 1`;+ return u ?? null;+}++// PUBLIC_COLS is exported so the lookup endpoint and any future caller stay in+// lockstep on exactly which fields are safe to surface.+export { PUBLIC_COLS };diff --git a/api/_lib/services/MonetizationService.js b/api/_lib/services/MonetizationService.jsnew file mode 100644index 000000000..4b9bbbc0b--- /dev/null+++ b/api/_lib/services/MonetizationService.js@@ -0,0 +1,472 @@+// MonetizationService — one place for skill-monetization business logic.+//+// Before this, the rules for "what does a skill cost", "who may change a+// price", "build a purchase", "confirm a payment", "does this user own a+// skill", and "what has a creator earned" were spread across half a dozen API+// handlers, each re-deriving ownership checks, fee splits, and payout lookups.+// This class is the single seam those handlers call through, so the policy+// lives in one tested unit and the handlers shrink to HTTP plumbing+// (auth → validate → call service → map result/error to a response).+//+// It does not reinvent the lower-level primitives — payout resolution, on-chain+// confirmation, access checks, fee math, and balance accounting already have+// dedicated, tested modules. The service orchestrates them and owns the+// handler-shaped business rules (ownership gating, idempotent purchase create,+// already-owned short-circuit) that previously lived inline.+//+// Errors are thrown with `status` (HTTP code) and `code` (machine string) so a+// handler can map them with `error(res, e.status, e.code, e.message)` without+// knowing the internals.++import { Keypair } from '@solana/web3.js';++import { sql as defaultSql } from '../db.js';+import { hasSkillAccess } from '../skill-access.js';+import { getAvailableBalance } from '../monetization.js';+import { resolveMarketplaceFee } from '../marketplace-platform-fee.js';+import { invalidateSkillPriceCache } from '../skill-price-cache.js';+import {+ confirmSkillPurchase,+ resolvePayoutAddress,+ logEvent,+} from '../purchase-confirm.js';++// Build an Error that carries the HTTP status + machine code a handler maps from.+function svcError(status, code, message) {+ return Object.assign(new Error(message), { status, code });+}++export class MonetizationService {+ /**+ * @param {object|string|null} user - a session user ({ id }), an auth object+ * ({ userId }), a raw user-id string, or null for anonymous callers.+ * @param {object} [deps] - injectable dependencies (mainly for tests).+ * @param {object} [deps.sql] - tagged-template SQL client; defaults to the+ * shared Neon client.+ */+ constructor(user, deps = {}) {+ this.user = user ?? null;+ this.userId =+ typeof user === 'string' ? user : user?.id ?? user?.userId ?? null;+ this.sql = deps.sql || defaultSql;+ }++ requireAuth() {+ if (!this.userId) throw svcError(401, 'unauthorized', 'sign in required');+ return this.userId;+ }++ /**+ * Load an agent and assert the current user owns it.+ * @returns {Promise<{id: string, user_id: string}>}+ * @throws 401 if anonymous, 404 if missing, 403 if not the owner.+ */+ async assertOwnership(agentId) {+ this.requireAuth();+ const [agent] = await this.sql`+ SELECT id, user_id FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) throw svcError(404, 'not_found', 'agent not found');+ if (agent.user_id !== this.userId) {+ throw svcError(403, 'forbidden', 'not your agent');+ }+ return agent;+ }++ /**+ * Active per-skill prices for an agent. Pure read — callers decide whether the+ * surface is public (marketplace) or owner-gated (dashboard).+ */+ async getSkillPricesForAgent(agentId) {+ return this.sql`+ SELECT skill, amount, currency_mint, chain, mint_decimals,+ trial_uses, time_pass_hours, time_pass_amount+ FROM agent_skill_prices+ WHERE agent_id = ${agentId} AND is_active = true+ ORDER BY skill+ `;+ }++ /**+ * Atomically replace the agent's active price set with the submitted prices.+ * Deactivates everything currently active, then upserts the submitted rows in+ * one transaction. Input is expected to be already validated by the caller.+ *+ * @param {string} agentId+ * @param {Array<{skill,amount,currency_mint,chain,trial_uses?,time_pass_hours?,time_pass_amount?}>} prices+ * @param {object} [opts]+ * @param {boolean} [opts.skipOwnershipCheck] - set when the caller already+ * verified ownership (avoids a redundant lookup).+ */+ async setSkillPrices(agentId, prices, { skipOwnershipCheck = false } = {}) {+ if (!skipOwnershipCheck) await this.assertOwnership(agentId);++ // Neon's serverless driver runs a transaction as an ARRAY of queries in a+ // single round-trip. Every statement is known up front, so we build the+ // array and pass it. Atomic: the deactivate + all upserts commit together+ // or not at all.+ const statements = [+ this.sql`UPDATE agent_skill_prices SET is_active = false WHERE agent_id = ${agentId}`,+ ...prices.map(+ (p) => this.sql`+ INSERT INTO agent_skill_prices+ (agent_id, skill, amount, currency_mint, chain, is_active, trial_uses, time_pass_hours, time_pass_amount)+ VALUES+ (${agentId}, ${p.skill}, ${p.amount}, ${p.currency_mint}, ${p.chain}, true,+ ${p.trial_uses ?? 0}, ${p.time_pass_hours ?? null}, ${p.time_pass_amount ?? null})+ ON CONFLICT (agent_id, skill) DO UPDATE SET+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ chain = EXCLUDED.chain,+ is_active = true,+ trial_uses = EXCLUDED.trial_uses,+ time_pass_hours = EXCLUDED.time_pass_hours,+ time_pass_amount = EXCLUDED.time_pass_amount,+ updated_at = now()+ `,+ ),+ ];++ await this.sql.transaction(statements);+ await invalidateSkillPriceCache(agentId);+ return { ok: true, count: prices.length };+ }++ /**+ * Prepare a Solana-Pay skill purchase for the current user. Resolves the+ * price + payout wallet, computes the platform-fee split, short-circuits if+ * the user already has active access, reuses a still-valid pending row+ * (idempotent), and otherwise records a new pending purchase.+ *+ * Returns the payment quote the client signs against (reference, recipient,+ * amounts, fee leg, time-pass window). Despite the name it returns Solana-Pay+ * parameters rather than a serialized transaction — the wallet builds the tx+ * from these; the serialized-tx variant lives in payments/prepare-skill-purchase.+ *+ * Gifting: pass `recipientUserId` to buy the skill for someone else. The+ * payer stays in `user_id` (they sign + confirm the payment); the recipient+ * is recorded in `recipient_user_id` and is the one who receives access. The+ * already-owned check and the access grant both key off the beneficiary+ * (`COALESCE(recipient_user_id, user_id)`), so a buyer may gift the same skill+ * to many distinct recipients without colliding with their own copy.+ *+ * @param {string} agentId+ * @param {string} skillName+ * @param {object} [opts]+ * @param {number|null} [opts.durationHours] - explicit time-pass length.+ * @param {string|null} [opts.referrerUserId] - resolved referrer (handler reads the request).+ * @param {string|null} [opts.recipientUserId] - gift beneficiary (resolved by the handler).+ */+ async preparePurchaseTransaction(agentId, skillName, { durationHours = null, referrerUserId = null, recipientUserId = null } = {}) {+ this.requireAuth();++ const isGift = !!recipientUserId && recipientUserId !== this.userId;+ if (recipientUserId && recipientUserId === this.userId) {+ throw svcError(400, 'cannot_gift_self', 'you already own purchases you make for yourself');+ }+ const beneficiaryId = isGift ? recipientUserId : this.userId;++ const [price] = await this.sql`+ SELECT amount, currency_mint, chain, mint_decimals, trial_uses, time_pass_hours, time_pass_amount+ FROM agent_skill_prices+ WHERE agent_id = ${agentId} AND skill = ${skillName} AND is_active = true+ `;+ if (!price) throw svcError(404, 'not_found', 'this skill is not for sale');++ const payoutAddress = await resolvePayoutAddress(agentId, price.chain);+ if (!payoutAddress) {+ throw svcError(412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');+ }++ // Already-owned short-circuit: any active access (confirmed purchase, live+ // trial, unexpired time-pass) the BENEFICIARY already holds returns early so+ // nobody pays twice. For a gift this means "the recipient already owns it" —+ // the buyer is told without their own ownership leaking into the answer.+ const [existing] = await this.sql`+ SELECT reference, status, tx_signature, confirmed_at, valid_until, trial_remaining, kind+ FROM skill_purchases+ WHERE COALESCE(recipient_user_id, user_id) = ${beneficiaryId}+ AND agent_id = ${agentId} AND skill = ${skillName}+ AND status IN ('confirmed', 'trial')+ AND (valid_until IS NULL OR valid_until > now())+ ORDER BY (status = 'confirmed') DESC, confirmed_at DESC NULLS LAST+ LIMIT 1+ `;+ if (existing) {+ if (isGift) {+ // Don't surface the recipient's own purchase reference / tx to the buyer.+ return { already_owned: true, recipient_owns: true };+ }+ return {+ already_owned: true,+ reference: existing.reference,+ status: existing.status,+ tx_signature: existing.tx_signature,+ confirmed_at: existing.confirmed_at,+ valid_until: existing.valid_until,+ trial_remaining: existing.trial_remaining,+ kind: existing.kind,+ };+ }++ // Idempotent create: reuse a fresh pending row for the same (buyer, agent,+ // skill, recipient) rather than minting a new reference on every retry click.+ // `IS NOT DISTINCT FROM` matches a NULL recipient (self-purchase) too, and+ // keeps gifts to different recipients on their own pending rows.+ const [pending] = await this.sql`+ SELECT reference, amount, currency_mint, chain, expires_at,+ platform_fee_amount, platform_fee_wallet+ FROM skill_purchases+ WHERE user_id = ${this.userId} AND agent_id = ${agentId} AND skill = ${skillName}+ AND recipient_user_id IS NOT DISTINCT FROM ${recipientUserId}+ AND status = 'pending'+ AND expires_at > now()+ ORDER BY created_at DESC+ LIMIT 1+ `;++ // Time-pass: prefer an explicit duration, else the skill's configured window.+ const effectiveDurationHours = durationHours ?? (price.time_pass_hours || null);+ const isTimePass = effectiveDurationHours != null;+ const purchaseAmount = isTimePass && price.time_pass_amount ? price.time_pass_amount : price.amount;+ const purchaseKind = isTimePass ? 'time_pass' : 'purchase';++ // Platform fee (Solana only — the split is one atomic SPL transfer the buyer+ // signs). Computed once at create and persisted on the row so confirm+ // verifies the exact split quoted, even if fee config changes meanwhile.+ const feeInfo = price.chain === 'solana'+ ? await resolveMarketplaceFee({ grossAtomics: BigInt(purchaseAmount) })+ : null;+ const platformFeeAmount = feeInfo ? feeInfo.feeAtomics : 0n;+ const platformFeeWallet = feeInfo ? feeInfo.recipient.toBase58() : null;++ const reference = pending?.reference ?? Keypair.generate().publicKey.toBase58();+ const label = isTimePass+ ? `${effectiveDurationHours}h Access: ${skillName.slice(0, 30)}`+ : `Skill: ${skillName.slice(0, 40)}`;+ const message = isTimePass+ ? `Get ${effectiveDurationHours}-hour access to '${skillName}'`+ : `Unlock '${skillName}' for this agent`;++ let row = pending;+ if (!pending) {+ const validUntil = isTimePass+ ? this.sql`now() + (${effectiveDurationHours} || ' hours')::interval`+ : this.sql`null`;++ const [inserted] = await this.sql`+ INSERT INTO skill_purchases (+ user_id, agent_id, skill, status, reference,+ amount, currency_mint, chain, expires_at, kind, referrer_user_id, valid_until,+ platform_fee_amount, platform_fee_wallet, recipient_user_id+ )+ VALUES (+ ${this.userId}, ${agentId}, ${skillName}, 'pending', ${reference},+ ${purchaseAmount}, ${price.currency_mint}, ${price.chain},+ now() + interval '30 minutes', ${purchaseKind}, ${referrerUserId}, ${validUntil},+ ${platformFeeAmount.toString()}, ${platformFeeWallet}, ${recipientUserId}+ )+ RETURNING reference, amount, currency_mint, chain, expires_at, valid_until,+ platform_fee_amount, platform_fee_wallet+ `;+ row = inserted;+ await logEvent(row.reference, 'created', { agent_id: agentId, skill: skillName, kind: purchaseKind, gift: isGift });+ } else {+ await logEvent(pending.reference, 'create_idempotent_hit', { agent_id: agentId, skill: skillName });+ }++ // The split the buyer signs, derived from the PERSISTED row so the quote+ // matches exactly what confirm verifies on-chain. `amount` is the full+ // price; `creator_amount` is the seller's leg; `fee` is the treasury leg+ // (omitted entirely when no fee applies).+ const rowFee = BigInt(row.platform_fee_amount || 0);+ const creatorAmount = (BigInt(row.amount) - rowFee).toString();+ const feeBlock = rowFee > 0n && row.platform_fee_wallet+ ? {+ fee: {+ recipient: row.platform_fee_wallet,+ amount: rowFee.toString(),+ bps: Number((rowFee * 10000n) / BigInt(row.amount)),+ },+ }+ : {};++ return {+ already_owned: false,+ reference: row.reference,+ recipient: payoutAddress,+ amount: String(row.amount),+ creator_amount: creatorAmount,+ currency_mint: row.currency_mint,+ chain: row.chain,+ mint_decimals: price.mint_decimals,+ expires_at: row.expires_at,+ valid_until: row.valid_until,+ kind: purchaseKind,+ label,+ message,+ ...feeBlock,+ ...(isGift ? { is_gift: true, gift_recipient_id: recipientUserId } : {}),+ ...(isTimePass ? { duration_hours: effectiveDurationHours } : {}),+ ...(price.time_pass_hours+ ? { time_pass_hours: price.time_pass_hours, time_pass_amount: price.time_pass_amount }+ : {}),+ };+ }++ /**+ * Confirm a pending purchase the current user owns, identified by its+ * Solana-Pay reference. Solana scans the chain by reference; EVM settles by a+ * tx hash the buyer submits.+ *+ * @param {string} reference+ * @param {object} [opts]+ * @param {string|null} [opts.txHash] - settlement tx hash (required for EVM).+ * @returns {Promise<{status:'pending'|'confirmed'|'tipped'|'mismatch', tx_signature?:string, tipped_amount?:string, message?:string}>}+ * @throws 404 if not found, 410 if expired, 400 if an EVM confirm omits tx_hash.+ */+ async confirmPurchase(reference, { txHash = null } = {}) {+ this.requireAuth();++ const [pur] = await this.sql`+ SELECT sp.id, sp.user_id, sp.agent_id, sp.skill, sp.status,+ sp.amount, sp.currency_mint, sp.chain, sp.tx_signature,+ sp.expires_at, sp.referrer_user_id, sp.recipient_user_id,+ sp.platform_fee_amount, sp.platform_fee_wallet,+ COALESCE(asp.mint_decimals, 6) AS mint_decimals+ FROM skill_purchases sp+ LEFT JOIN agent_skill_prices asp+ ON asp.agent_id = sp.agent_id AND asp.skill = sp.skill+ WHERE sp.reference = ${reference} AND sp.user_id = ${this.userId}+ `;+ if (!pur) throw svcError(404, 'not_found', 'purchase not found');+ if (pur.status === 'confirmed') {+ return { status: 'confirmed', tx_signature: pur.tx_signature };+ }+ if (pur.status === 'expired' || (pur.expires_at && new Date(pur.expires_at) < new Date())) {+ throw svcError(410, 'purchase_expired', 'this pending purchase expired; please start a new one');+ }+ if (pur.chain !== 'solana' && !txHash) {+ throw svcError(400, 'tx_hash_required', 'tx_hash is required to confirm an EVM purchase');+ }++ return confirmSkillPurchase({ ...pur, reference }, { txHash });+ }++ /**+ * Does the current user have access to a paid skill on an agent? Delegates to+ * the canonical access check, so trials, time-passes, and agent-level+ * subscriptions all count — not just confirmed one-off purchases.+ *+ * @returns {{has_access:boolean, paid:boolean, owned:boolean, reason?:string,+ * trial?:boolean, trial_remaining?:number, via_subscription?:boolean, price?:object}}+ */+ async checkSkillOwnership(agentId, skillName) {+ const access = await hasSkillAccess(this.userId, agentId, skillName);+ return { has_access: !!access.owned, ...access };+ }++ /**+ * Creator sales overview for the current user: per-sale ledger entries (skill+ * royalties + asset sales) plus pending/settled USD totals.+ *+ * @returns {Promise<{pending_usd:number, settled_usd:number, entries:Array}>}+ */+ async getCreatorSalesData() {+ const userId = this.requireAuth();++ const rows = await this.sql`+ SELECT+ rl.id,+ rl.price_usd,+ rl.status,+ rl.created_at,+ ms.name AS skill_name,+ ai.name AS agent_name+ FROM royalty_ledger rl+ JOIN marketplace_skills ms ON ms.id = rl.skill_id+ JOIN agent_identities ai ON ai.id = rl.agent_id+ WHERE rl.author_user_id = ${userId}+ ORDER BY rl.created_at DESC+ LIMIT 100+ `;++ // Asset sales (avatars / agents / plugins). asset_purchases stores amount+ // in atomic USDC units (6 decimals) — divide for USD reporting.+ let assetRows = [];+ try {+ assetRows = await this.sql`+ SELECT+ ap.id,+ ap.item_type,+ ap.item_id,+ ap.amount,+ ap.currency_mint,+ ap.confirmed_at,+ ap.created_at,+ ap.status,+ CASE ap.item_type+ WHEN 'avatar' THEN (SELECT name FROM avatars WHERE id = ap.item_id)+ WHEN 'agent' THEN (SELECT name FROM agent_identities WHERE id = ap.item_id)+ ELSE NULL+ END AS item_name+ FROM asset_purchases ap+ WHERE ap.seller_user_id = ${userId}+ AND ap.status = 'confirmed'+ ORDER BY ap.confirmed_at DESC NULLS LAST+ LIMIT 100+ `;+ } catch {+ // asset_purchases migration hasn't run yet — leave list empty.+ }++ const pending_usd = rows+ .filter((r) => r.status === 'pending')+ .reduce((s, r) => s + Number(r.price_usd), 0);++ const settled_usd = rows+ .filter((r) => r.status === 'settled')+ .reduce((s, r) => s + Number(r.price_usd), 0);++ const asset_settled_usd = assetRows.reduce((s, r) => s + Number(r.amount) / 1_000_000, 0);++ const entries = rows.map((r) => ({+ skill_name: r.skill_name,+ agent_name: r.agent_name,+ price_usd: Number(r.price_usd),+ status: r.status,+ created_at: r.created_at,+ kind: 'skill',+ }));+ for (const r of assetRows) {+ entries.push({+ skill_name: `${r.item_type[0].toUpperCase()}${r.item_type.slice(1)} sale`,+ agent_name: r.item_name || '(deleted)',+ price_usd: Number(r.amount) / 1_000_000,+ status: 'settled',+ created_at: r.confirmed_at || r.created_at,+ kind: r.item_type,+ });+ }+ entries.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));++ return {+ pending_usd,+ settled_usd: settled_usd + asset_settled_usd,+ entries,+ };+ }++ /**+ * Withdrawable balance for the current user across (or filtered to) a+ * currency. Thin pass-through to the accounting helper so handlers reach+ * balance state through the same service seam as everything else.+ */+ async getAvailableBalance(currencyMint = null) {+ const userId = this.requireAuth();+ return getAvailableBalance(userId, currencyMint);+ }+}++export default MonetizationService;diff --git a/api/_lib/skill-access.js b/api/_lib/skill-access.jsindex 6cefac120..d78925549 100644--- a/api/_lib/skill-access.js+++ b/api/_lib/skill-access.js@@ -4,9 +4,19 @@// before doing the work. Agent-to-agent x402 callers go through verifyPaid in x402.js// instead; this helper covers the human-buyer / direct-API path.//-// Returns { paid, owned, price?, reason? }-// paid — boolean: is this skill priced (i.e. requires payment)?-// owned — boolean: does the user have a confirmed (or active trial / valid time-window) purchase?+// A user is granted access through any one of (checked in priority order so a+// confirmed purchase or a subscription is never satisfied by burning a trial):+// 1. The skill is not priced in agent_skill_prices → free, always allowed.+// 2. A confirmed one-time purchase in skill_purchases (honouring time-passes).+// 3. An agent-level flat subscription (user_agent_subscriptions) — covers+// every paid skill on the agent.+// 4. A creator subscription tier (creator_subscriptions → subscription_plans)+// whose included_skills array lists this skill.+// 5. An active trial with remaining uses.+//+// Returns { paid, owned, price?, reason?, via_subscription?, trial?, trial_remaining? }+// paid — boolean: is this skill priced in agent_skill_prices (i.e. payment-gated)?+// owned — boolean: may the user execute it right now?// price — { skill, amount, currency_mint, chain } when paid; undefined otherwise// reason — short string when access is denied ('not_purchased' | 'trial_exhausted' | 'expired')@@ -22,17 +32,9 @@ export async function hasSkillAccess(userId, agentId, skill) {if (!userId) return { paid: true, owned: false, price, reason: 'not_purchased' };- // Agent-level subscription grants access to all paid skills on this agent.- const [activeSub] = await sql`- SELECT id FROM user_agent_subscriptions- WHERE user_id = ${userId}- AND agent_id = ${agentId}- AND status = 'active'- AND current_period_ends_at > now()- LIMIT 1- `.catch(() => []);- if (activeSub) return { paid: true, owned: true, price, via_subscription: true };-+ // Best purchase row for this (user, agent, skill): a confirmed purchase wins+ // over a trial. Fetched up front so trials are only consumed when nothing+ // stronger (purchase or subscription) already grants access.const [purchase] = await sql`SELECT status, valid_until, trial_remainingFROM skill_purchases@@ -45,24 +47,53 @@ export async function hasSkillAccess(userId, agentId, skill) {LIMIT 1`;- if (!purchase) return { paid: true, owned: false, price, reason: 'not_purchased' };-- if (purchase.status === 'confirmed') {- // Time-limited access (C3): if valid_until is set, it must be in the future.- if (purchase.valid_until && new Date(purchase.valid_until) <= new Date()) {- return { paid: true, owned: false, price, reason: 'expired' };- }+ // 2. Confirmed one-time purchase (honour time-limited passes).+ const confirmedExpired =+ purchase?.status === 'confirmed' &&+ purchase.valid_until &&+ new Date(purchase.valid_until) <= new Date();+ if (purchase?.status === 'confirmed' && !confirmedExpired) {return { paid: true, owned: true, price };}- // Trial mode (C2)- if (purchase.status === 'trial') {+ // 3. Agent-level flat subscription grants access to every paid skill on this agent.+ const [flatSub] = await sql`+ SELECT id FROM user_agent_subscriptions+ WHERE user_id = ${userId}+ AND agent_id = ${agentId}+ AND status = 'active'+ AND current_period_ends_at > now()+ LIMIT 1+ `.catch(() => []);+ if (flatSub) return { paid: true, owned: true, price, via_subscription: true };++ // 4. Creator subscription tier whose included_skills covers this skill. A tier+ // matches when it is scoped to this agent, or is creator-wide (agent_id NULL)+ // and owned by this agent's creator.+ const [tierSub] = await sql`+ SELECT cs.id+ FROM creator_subscriptions cs+ JOIN subscription_plans sp ON sp.id = cs.plan_id+ JOIN agent_identities ai ON ai.id = ${agentId}+ WHERE cs.subscriber_user_id = ${userId}+ AND cs.status = 'active'+ AND cs.current_period_end > now()+ AND ${skill} = ANY(sp.included_skills)+ AND (sp.agent_id = ${agentId} OR (sp.agent_id IS NULL AND sp.creator_id = ai.user_id))+ LIMIT 1+ `.catch(() => []);+ if (tierSub) return { paid: true, owned: true, price, via_subscription: true };++ // 5. Active trial with remaining uses (consumed by the caller on success).+ if (purchase?.status === 'trial') {if ((purchase.trial_remaining ?? 0) <= 0) {return { paid: true, owned: false, price, reason: 'trial_exhausted' };}return { paid: true, owned: true, price, trial: true, trial_remaining: purchase.trial_remaining };}+ // Denied — distinguish an expired time-pass from a skill never purchased.+ if (confirmedExpired) return { paid: true, owned: false, price, reason: 'expired' };return { paid: true, owned: false, price, reason: 'not_purchased' };}diff --git a/api/_lib/skill-license-onchain.js b/api/_lib/skill-license-onchain.jsnew file mode 100644index 000000000..e8903d3a7--- /dev/null+++ b/api/_lib/skill-license-onchain.js@@ -0,0 +1,357 @@+/**+ * On-chain skill-license verification + minting (the `skill_license` Anchor+ * program — see contracts/skill-license/).+ * ---------------------------------------------------------------------------+ * The program records each purchased skill as a `SkillLicense` PDA backed by a+ * 1-of-1 SPL NFT in the buyer's wallet. The PDA is derived deterministically+ * from `(owner, agent_mint, sha256(skill_name))`, so anyone can re-derive it and+ * read it back — giving the platform an *alternative, trustless* way to verify+ * skill access that does not depend on our database:+ *+ * a license PDA that exists with `revoked_at == 0` ⇒ the wallet owns the skill.+ *+ * This module is the JS counterpart to the on-chain program: it derives the same+ * PDAs (matching the Rust `seeds`), decodes the account, verifies ownership, and+ * — when a minter key is configured — builds and submits the `mint_skill_license`+ * instruction. PDA derivation is pure and dependency-light so it is unit-tested+ * directly; the RPC calls are only made by `verify*`/`mint*`.+ */++import { createHash } from 'node:crypto';++import {+ Connection,+ Keypair,+ PublicKey,+ SystemProgram,+ SYSVAR_RENT_PUBKEY,+ Transaction,+ TransactionInstruction,+ sendAndConfirmTransaction,+} from '@solana/web3.js';+import bs58 from 'bs58';++import { env } from './env.js';++/** Program id baked into the on-chain program's `declare_id!`. Override per+ * deployment with SKILL_LICENSE_PROGRAM_ID. */+export const SKILL_LICENSE_PROGRAM_ID =+ process.env.SKILL_LICENSE_PROGRAM_ID || 'EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8';++export const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');+export const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey(+ 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL',+);++// Seed prefixes — must byte-match the constants in contracts/skill-license/src/lib.rs.+const MARKETPLACE_SEED = Buffer.from('marketplace');+const SKILL_LICENSE_SEED = Buffer.from('skill_license');+const SKILL_MINT_SEED = Buffer.from('skill_mint');++// Anchor instruction discriminators (sha256("global:<name>")[..8]).+const INITIALIZE_MARKETPLACE_DISCRIMINATOR = Buffer.from([47, 81, 64, 0, 96, 56, 105, 7]);+const MINT_DISCRIMINATOR = Buffer.from([179, 127, 15, 8, 180, 22, 10, 122]);++// Anchor account discriminator for `SkillLicense` (sha256("account:SkillLicense")[..8]).+const SKILL_LICENSE_DISCRIMINATOR = Buffer.from([212, 242, 220, 5, 112, 253, 200, 97]);++function programPk(programId) {+ return programId instanceof PublicKey ? programId : new PublicKey(programId);+}++/** sha256(skill_name) — the fixed-length third PDA seed. Matches the Rust+ * `skill_seed()` (Solana `hash::hash` is sha256). */+export function skillSeed(skillName) {+ return createHash('sha256').update(String(skillName), 'utf8').digest();+}++/** The singleton marketplace config PDA. */+export function deriveMarketplacePda(programId = SKILL_LICENSE_PROGRAM_ID) {+ return PublicKey.findProgramAddressSync([MARKETPLACE_SEED], programPk(programId));+}++/** The license PDA for a given owner + agent + skill. */+export function deriveSkillLicensePda(owner, agentMint, skillName, programId = SKILL_LICENSE_PROGRAM_ID) {+ return PublicKey.findProgramAddressSync(+ [+ SKILL_LICENSE_SEED,+ new PublicKey(owner).toBuffer(),+ new PublicKey(agentMint).toBuffer(),+ skillSeed(skillName),+ ],+ programPk(programId),+ );+}++/** The 1/1 NFT mint PDA backing a license. */+export function deriveSkillMintPda(owner, agentMint, skillName, programId = SKILL_LICENSE_PROGRAM_ID) {+ return PublicKey.findProgramAddressSync(+ [+ SKILL_MINT_SEED,+ new PublicKey(owner).toBuffer(),+ new PublicKey(agentMint).toBuffer(),+ skillSeed(skillName),+ ],+ programPk(programId),+ );+}++/** The owner's associated token account for a mint (standard ATA derivation). */+export function deriveAssociatedTokenAddress(owner, mint) {+ const [ata] = PublicKey.findProgramAddressSync(+ [new PublicKey(owner).toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), new PublicKey(mint).toBuffer()],+ ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ return ata;+}++/**+ * Decode a raw `SkillLicense` account buffer (Anchor layout). Throws if the+ * discriminator does not match, so a wrong account can never be read as a valid+ * license.+ *+ * @param {Buffer|Uint8Array} data+ */+export function decodeSkillLicense(data) {+ const buf = Buffer.from(data);+ if (buf.length < 8 || !buf.subarray(0, 8).equals(SKILL_LICENSE_DISCRIMINATOR)) {+ throw new Error('not a SkillLicense account (discriminator mismatch)');+ }+ let o = 8;+ const pk = () => {+ const p = new PublicKey(buf.subarray(o, o + 32));+ o += 32;+ return p;+ };+ const authority = pk();+ const agentMint = pk();+ const nftMint = pk();+ const skillHash = Buffer.from(buf.subarray(o, o + 32));+ o += 32;+ const purchaseDate = Number(buf.readBigInt64LE(o));+ o += 8;+ const revokedAt = Number(buf.readBigInt64LE(o));+ o += 8;+ const bump = buf.readUInt8(o);+ o += 1;+ const nameLen = buf.readUInt32LE(o);+ o += 4;+ const skillName = buf.subarray(o, o + nameLen).toString('utf8');++ return {+ authority: authority.toBase58(),+ agentMint: agentMint.toBase58(),+ nftMint: nftMint.toBase58(),+ skillHash: skillHash.toString('hex'),+ purchaseDate,+ revokedAt,+ bump,+ skillName,+ revoked: revokedAt !== 0,+ };+}++function rpcForNetwork(network) {+ return network === 'devnet' ? env.SOLANA_RPC_URL_DEVNET : env.SOLANA_RPC_URL;+}++/** Is the program deployed + executable on this connection? */+export async function isProgramDeployed(connection, programId = SKILL_LICENSE_PROGRAM_ID) {+ const info = await connection.getAccountInfo(programPk(programId));+ return Boolean(info && info.executable);+}++/**+ * Verify whether `ownerWallet` holds an active on-chain license for `skill` on+ * `agentMint`. Reads the license PDA directly — no database involved.+ *+ * @param {object} p+ * @param {string} p.ownerWallet buyer's base58 Solana pubkey+ * @param {string} p.agentMint the agent's on-chain grouping mint (base58)+ * @param {string} p.skill skill name/slug+ * @param {'mainnet'|'devnet'} [p.network]+ * @param {Connection} [p.connection] reuse an existing connection+ * @param {string} [p.programId]+ * @returns {Promise<{deployed:boolean, exists:boolean, owned:boolean, revoked:boolean,+ * license:string, nftMint:string, ownerTokenAccount:string,+ * record:ReturnType<typeof decodeSkillLicense>|null}>}+ */+export async function verifyOnchainSkillLicense({+ ownerWallet,+ agentMint,+ skill,+ network = 'mainnet',+ connection,+ programId = SKILL_LICENSE_PROGRAM_ID,+}) {+ const conn = connection || new Connection(rpcForNetwork(network), 'confirmed');+ const [license] = deriveSkillLicensePda(ownerWallet, agentMint, skill, programId);+ const [nftMint] = deriveSkillMintPda(ownerWallet, agentMint, skill, programId);+ const ownerTokenAccount = deriveAssociatedTokenAddress(ownerWallet, nftMint);++ const base = {+ license: license.toBase58(),+ nftMint: nftMint.toBase58(),+ ownerTokenAccount: ownerTokenAccount.toBase58(),+ };++ const deployed = await isProgramDeployed(conn, programId);+ if (!deployed) {+ return { deployed: false, exists: false, owned: false, revoked: false, record: null, ...base };+ }++ const info = await conn.getAccountInfo(license);+ if (!info) {+ return { deployed: true, exists: false, owned: false, revoked: false, record: null, ...base };+ }++ let record;+ try {+ record = decodeSkillLicense(info.data);+ } catch {+ return { deployed: true, exists: false, owned: false, revoked: false, record: null, ...base };+ }++ const owned = record.revokedAt === 0 && record.authority === new PublicKey(ownerWallet).toBase58();+ return {+ deployed: true,+ exists: true,+ owned,+ revoked: record.revoked,+ record,+ ...base,+ };+}++/** Load the minter keypair from the environment (base58 secret), or null. */+export function minterKeypair() {+ const secret = process.env.SKILL_LICENSE_MINTER_KEY;+ if (!secret) return null;+ return Keypair.fromSecretKey(bs58.decode(secret.trim()));+}++/**+ * Build the one-time `initialize_marketplace` instruction. `authority` becomes+ * the admin (can rotate the minter); `minter` is the wallet allowed to mint+ * licenses. Account order matches the IDL / `InitializeMarketplace` struct.+ */+export function buildInitializeMarketplaceIx({+ authority,+ minter,+ programId = SKILL_LICENSE_PROGRAM_ID,+}) {+ const pid = programPk(programId);+ const [marketplace] = deriveMarketplacePda(pid);+ const data = Buffer.concat([+ INITIALIZE_MARKETPLACE_DISCRIMINATOR,+ new PublicKey(minter).toBuffer(),+ ]);+ const keys = [+ { pubkey: marketplace, isSigner: false, isWritable: true },+ { pubkey: new PublicKey(authority), isSigner: true, isWritable: true },+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },+ ];+ return {+ instruction: new TransactionInstruction({ programId: pid, keys, data }),+ accounts: { marketplace: marketplace.toBase58() },+ };+}++/** Borsh-encode a string (u32 LE length + utf8 bytes). */+function encodeString(value) {+ const bytes = Buffer.from(value, 'utf8');+ const len = Buffer.alloc(4);+ len.writeUInt32LE(bytes.length);+ return Buffer.concat([len, bytes]);+}++/**+ * Build the `mint_skill_license` instruction. Account order must match the IDL /+ * `MintSkillLicense` accounts struct exactly.+ */+export function buildMintSkillLicenseIx({+ minter,+ owner,+ agentMint,+ skillName,+ programId = SKILL_LICENSE_PROGRAM_ID,+}) {+ const pid = programPk(programId);+ const ownerPk = new PublicKey(owner);+ const agentPk = new PublicKey(agentMint);+ const [marketplace] = deriveMarketplacePda(pid);+ const [skillLicense] = deriveSkillLicensePda(ownerPk, agentPk, skillName, pid);+ const [nftMint] = deriveSkillMintPda(ownerPk, agentPk, skillName, pid);+ const ownerTokenAccount = deriveAssociatedTokenAddress(ownerPk, nftMint);++ const data = Buffer.concat([MINT_DISCRIMINATOR, encodeString(skillName)]);++ const keys = [+ { pubkey: marketplace, isSigner: false, isWritable: true },+ { pubkey: new PublicKey(minter), isSigner: true, isWritable: true },+ { pubkey: ownerPk, isSigner: false, isWritable: false },+ { pubkey: agentPk, isSigner: false, isWritable: false },+ { pubkey: skillLicense, isSigner: false, isWritable: true },+ { pubkey: nftMint, isSigner: false, isWritable: true },+ { pubkey: ownerTokenAccount, isSigner: false, isWritable: true },+ { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },+ { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },+ { pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false },+ ];++ return {+ instruction: new TransactionInstruction({ programId: pid, keys, data }),+ accounts: {+ marketplace: marketplace.toBase58(),+ skillLicense: skillLicense.toBase58(),+ nftMint: nftMint.toBase58(),+ ownerTokenAccount: ownerTokenAccount.toBase58(),+ },+ };+}++/**+ * Mint an on-chain skill license to `ownerWallet`. Server-signed by the+ * configured minter keypair. Idempotent at the program level: a second mint for+ * the same (owner, agent, skill) fails because the license/mint PDAs already+ * exist — callers should treat an "already in use" error as success.+ *+ * @returns {Promise<{signature:string, license:string, nftMint:string, ownerTokenAccount:string, alreadyMinted:boolean}>}+ */+export async function mintSkillLicenseOnchain({+ ownerWallet,+ agentMint,+ skill,+ network = 'mainnet',+ connection,+ programId = SKILL_LICENSE_PROGRAM_ID,+}) {+ const minter = minterKeypair();+ if (!minter) {+ throw Object.assign(new Error('SKILL_LICENSE_MINTER_KEY not configured'), {+ code: 'minter_unconfigured',+ });+ }+ const conn = connection || new Connection(rpcForNetwork(network), 'confirmed');++ const { instruction, accounts } = buildMintSkillLicenseIx({+ minter: minter.publicKey,+ owner: ownerWallet,+ agentMint,+ skillName: skill,+ programId,+ });++ // If the license PDA already exists this mint is a no-op success.+ const existing = await conn.getAccountInfo(new PublicKey(accounts.skillLicense));+ if (existing) {+ return { signature: null, ...accounts, alreadyMinted: true };+ }++ const tx = new Transaction().add(instruction);+ const signature = await sendAndConfirmTransaction(conn, tx, [minter], {+ commitment: 'confirmed',+ });+ return { signature, ...accounts, alreadyMinted: false };+}diff --git a/api/_lib/skill-price-cache.js b/api/_lib/skill-price-cache.jsindex 7411717fe..c1ac7f2d4 100644--- a/api/_lib/skill-price-cache.js+++ b/api/_lib/skill-price-cache.js@@ -1,60 +1,78 @@-// In-memory cache for agent skill prices.+// Cache for agent skill prices — Upstash Redis (shared) with in-memory fallback.//-// Skill prices are read on every purchase flow, agent embed load, and-// marketplace detail fetch. They change infrequently (creator-initiated-// updates), so caching them for a short window cuts DB round-trips without-// ever serving stale prices for meaningful durations.+// Skill prices are read on every purchase flow, agent embed load, marketplace+// detail fetch, and agent-detail GET. They change only when a creator edits+// them, so caching them takes a DB round-trip off all of those hot read paths.//-// TTL: 2 minutes per agent. Writes (set-price, bulk-pricing) must call-// invalidateSkillPriceCache(agentId) so the next read reflects the update.+// Backed by the shared cache adapter (_lib/cache.js): Upstash Redis when it is+// configured, an in-memory Map otherwise (dev + tests need no extra config).+// Using the shared adapter — instead of a process-local Map — is what makes+// invalidation correct on Vercel: a price edit handled by one serverless+// instance issues a Redis DEL that every other warm instance observes on its+// next read. A per-instance Map cannot do that; it can only clear the one+// instance that handled the write, leaving every other instance to serve stale+// prices until its own TTL lapses. The adapter's short read-memo additionally+// collapses bursts of identical reads into a single Redis round-trip.//-// Vercel serverless: each function instance has its own heap, so cache-// entries only persist for the lifetime of that warm instance. There is no-// cross-instance coordination — an update invalidates the local instance's-// entry only. In the worst case a stale instance serves old prices for up-// to TTL seconds. This is acceptable: prices don't change mid-purchase (the-// purchase flow persists the quoted price on the skill_purchases row at-// create time and confirms against that snapshot, not the live price).+// TTL: 1 hour. Writes to agent_skill_prices MUST call+// invalidateSkillPriceCache(agentId) so a change is reflected immediately+// rather than after the TTL. A brief stale window can never overcharge a buyer:+// the purchase flow snapshots the quoted price onto the skill_purchases row at+// create time and confirms against that snapshot, not the live price.import { sql } from './db.js';+import { cacheGet, cacheSet, cacheDel } from './cache.js';-const CACHE_TTL_MS = 2 * 60 * 1000; // 2 minutes+const TTL_SECONDS = 60 * 60; // 1 hour+const KEY_PREFIX = 'skill-prices:v1:';-const _cache = new Map(); // agentId → { rows, ts }+function keyFor(agentId) {+ return `${KEY_PREFIX}${agentId}`;+}++async function loadFromDb(agentId) {+ return sql`+ SELECT skill, amount, currency_mint, chain, mint_decimals,+ trial_uses, time_pass_hours, time_pass_amount+ FROM agent_skill_prices+ WHERE agent_id = ${agentId} AND is_active = true+ `;+}/**- * Fetch active skill prices for an agent, using the cache.+ * Active skill prices for an agent, served from the cache when warm and read+ * through to the database (then cached for 1 hour) on a miss. A cache backend+ * failure degrades to a direct DB read — it never fails the caller.* @param {string} agentId* @returns {Promise<Array<{ skill, amount, currency_mint, chain, mint_decimals,* trial_uses, time_pass_hours, time_pass_amount }>>}*/export async function getSkillPrices(agentId) {- const cached = _cache.get(agentId);- if (cached && Date.now() - cached.ts < CACHE_TTL_MS) {- return cached.rows;- }- const rows = await sql`- SELECT skill, amount, currency_mint, chain, mint_decimals,- trial_uses, time_pass_hours, time_pass_amount- FROM agent_skill_prices- WHERE agent_id = ${agentId} AND is_active = true- `;- _cache.set(agentId, { rows, ts: Date.now() });+ const key = keyFor(agentId);+ const cached = await cacheGet(key).catch(() => null);+ if (Array.isArray(cached)) return cached;++ const rows = await loadFromDb(agentId);+ // Write-through is best-effort: a cache hiccup must not fail the read.+ await cacheSet(key, rows, TTL_SECONDS).catch(() => {});return rows;}/*** Invalidate the cached prices for an agent. Call after any write to- * agent_skill_prices for this agent.+ * agent_skill_prices for this agent. Async because the backing DEL may hit+ * Redis — await it so the response is returned only once the entry is cleared+ * (and, with Redis, cleared for every instance).* @param {string} agentId+ * @returns {Promise<void>}*/-export function invalidateSkillPriceCache(agentId) {- _cache.delete(agentId);+export async function invalidateSkillPriceCache(agentId) {+ await cacheDel(keyFor(agentId)).catch(() => {});}/**- * Fetch ONE active price row for (agentId, skill). Uses the agent's full- * price cache so a warm agent hit only costs a Map lookup.+ * Fetch ONE active price row for (agentId, skill). Uses the agent's full price+ * cache so a warm agent hit costs no extra DB round-trip.* @param {string} agentId* @param {string} skill* @returns {Promise<object|null>}@@ -63,3 +81,29 @@ export async function getSkillPrice(agentId, skill) {const rows = await getSkillPrices(agentId);return rows.find((r) => r.skill === skill) ?? null;}++/**+ * Fold active price rows into the `skill_prices` map that agent-detail,+ * marketplace-detail, and skill-access surfaces return: keyed by skill name,+ * each value carrying the atomic amount, currency, chain, and the dimensions the+ * purchase UI needs. Missing optional columns default deterministically so the+ * shape is identical whether a row carries them or not.+ * @param {Array<object>} rows+ * @returns {Record<string, { amount, currency_mint, chain, mint_decimals,+ * trial_uses, time_pass_hours, time_pass_amount }>}+ */+export function skillPriceMap(rows) {+ const map = {};+ for (const p of rows || []) {+ map[p.skill] = {+ amount: p.amount,+ currency_mint: p.currency_mint,+ chain: p.chain,+ mint_decimals: p.mint_decimals ?? 6,+ trial_uses: p.trial_uses ?? 0,+ time_pass_hours: p.time_pass_hours ?? null,+ time_pass_amount: p.time_pass_amount ?? null,+ };+ }+ return map;+}diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.jsindex c44fd9561..abb35b062 100644--- a/api/_lib/solana-signers.js+++ b/api/_lib/solana-signers.js@@ -75,6 +75,14 @@ export const SOLANA_SIGNERS = [purpose: 'pays SPL withdrawal gas (process-withdrawals cron)',network: 'mainnet',},+ {+ name: 'marketplace-payer',+ env: 'MARKETPLACE_PAYER_KEYPAIR',+ fallbackEnv: 'PLATFORM_TREASURY_KEYPAIR',+ minSol: 0.05,+ purpose: 'sponsors network fees for gasless skill/asset checkout (fee-payer on prepared VersionedTransactions)',+ network: 'mainnet',+ },{name: 'a2a-payer',env: 'A2A_PAYER_SOLANA_SECRET',diff --git a/api/_lib/solana/gasless-tx.js b/api/_lib/solana/gasless-tx.jsnew file mode 100644index 000000000..30570f711--- /dev/null+++ b/api/_lib/solana/gasless-tx.js@@ -0,0 +1,162 @@+// Gasless purchase transactions — the platform sponsors Solana network fees.+//+// Users hold USDC but rarely hold SOL. Forcing them to acquire SOL just to pay+// the ~0.000005 SOL signature fee is real friction at checkout. Here the+// platform's marketplace payer becomes the transaction fee-payer and co-signs+// the transaction on the backend; the buyer still authorizes the SPL token+// transfer with their own signature, but pays no network fee.+//+// The buyer receives a partially-signed `VersionedTransaction` (the payer's+// signature is already attached) and adds only their authority signature in the+// wallet. The reference key rides the seller leg so @solana/pay's findReference+// / validateTransfer can locate and verify the payment — see+// api/_lib/purchase-confirm.js, which validates the exact split this builds.+//+// The payer keypair is one of the monitored signers (`marketplace-payer` in+// api/_lib/solana-signers.js). If it runs dry every gasless purchase silently+// breaks, so the balance-check cron watches it. When no payer is configured the+// builder returns null and callers fall back to a buyer-pays transaction.++import {+ PublicKey,+ TransactionMessage,+ VersionedTransaction,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync,+ createTransferCheckedInstruction,+ getMint,+} from '@solana/spl-token';++import { decodeSecretKey } from '../solana-signers.js';++// Resolve the marketplace fee-payer keypair from the environment once per+// lambda instance. `undefined` = not yet resolved, `null` = not configured /+// undecodable (callers fall back to buyer-pays).+let _payer = undefined;++/**+ * Load the platform's gasless fee-payer keypair, preferring the dedicated+ * MARKETPLACE_PAYER_KEYPAIR and falling back to the shared platform treasury.+ * @returns {Promise<import('@solana/web3.js').Keypair | null>}+ */+export async function resolveMarketplacePayer() {+ if (_payer !== undefined) return _payer;+ const secret =+ process.env.MARKETPLACE_PAYER_KEYPAIR ||+ process.env.PLATFORM_TREASURY_KEYPAIR ||+ process.env.TREASURY_KEYPAIR ||+ '';+ if (!secret) {+ _payer = null;+ return null;+ }+ const bytes = await decodeSecretKey(secret);+ if (!bytes) {+ _payer = null;+ return null;+ }+ try {+ const { Keypair } = await import('@solana/web3.js');+ _payer = Keypair.fromSecretKey(bytes);+ } catch {+ _payer = null;+ }+ return _payer;+}++/** Reset the cached payer — test-only seam so env changes take effect. */+export function _resetMarketplacePayerCache() {+ _payer = undefined;+}++/**+ * Build a partially-signed (gasless) SPL-token purchase transaction.+ *+ * The platform payer is the fee-payer and co-signs; the buyer authorizes the+ * transfer leg(s) with their wallet. Pass a non-zero `platformFeeAtomics` ++ * `platformFeeWallet` to add the treasury fee leg atomically (skill purchases);+ * omit them for a single full-amount transfer (whole-asset purchases).+ *+ * @param {object} args+ * @param {import('@solana/web3.js').Connection} args.connection+ * @param {string} args.buyerPublicKey base58 — token-transfer authority+ * @param {string} args.recipient base58 — seller / creator payout wallet+ * @param {string} args.mint base58 — SPL mint (e.g. USDC)+ * @param {bigint} args.creatorAtomics seller leg amount, atomic units+ * @param {string} args.reference base58 — Solana Pay reference key+ * @param {number} [args.decimals] mint decimals; fetched on-chain if omitted+ * @param {bigint} [args.platformFeeAtomics] treasury leg amount, atomic units+ * @param {string} [args.platformFeeWallet] base58 — treasury wallet for the fee leg+ * @returns {Promise<{ transaction: string, feePayer: string, gasless: true } | null>}+ * base64 VersionedTransaction, or null when no payer is configured.+ */+export async function buildGaslessPurchaseTx({+ connection,+ buyerPublicKey,+ recipient,+ mint,+ creatorAtomics,+ reference,+ decimals,+ platformFeeAtomics = 0n,+ platformFeeWallet = null,+}) {+ const payer = await resolveMarketplacePayer();+ if (!payer) return null;++ const mintKey = new PublicKey(mint);+ const buyer = new PublicKey(buyerPublicKey);+ const referenceKey = new PublicKey(reference);++ const mintDecimals =+ decimals == null ? (await getMint(connection, mintKey)).decimals : Number(decimals);++ const fromAta = getAssociatedTokenAddressSync(mintKey, buyer);+ const creatorAta = getAssociatedTokenAddressSync(mintKey, new PublicKey(recipient));++ // Seller leg — carries the Solana Pay reference so the confirm pipeline can+ // locate this transaction via findReference.+ const creatorIx = createTransferCheckedInstruction(+ fromAta,+ mintKey,+ creatorAta,+ buyer,+ creatorAtomics,+ mintDecimals,+ );+ creatorIx.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });++ const instructions = [creatorIx];++ // Platform fee leg — same transaction, atomic with the seller leg.+ if (platformFeeAtomics > 0n && platformFeeWallet) {+ const feeAta = getAssociatedTokenAddressSync(mintKey, new PublicKey(platformFeeWallet));+ instructions.push(+ createTransferCheckedInstruction(+ fromAta,+ mintKey,+ feeAta,+ buyer,+ platformFeeAtomics,+ mintDecimals,+ ),+ );+ }++ const { blockhash } = await connection.getLatestBlockhash('confirmed');+ const messageV0 = new TransactionMessage({+ payerKey: payer.publicKey, // platform pays the network fee+ recentBlockhash: blockhash,+ instructions,+ }).compileToV0Message();++ const tx = new VersionedTransaction(messageV0);+ tx.sign([payer]); // partial: buyer adds the authority signature in their wallet++ return {+ transaction: Buffer.from(tx.serialize()).toString('base64'),+ feePayer: payer.publicKey.toBase58(),+ gasless: true,+ };+}diff --git a/api/_lib/solana/rpc-fallback.js b/api/_lib/solana/rpc-fallback.jsindex c98671b19..60ec396f4 100644--- a/api/_lib/solana/rpc-fallback.js+++ b/api/_lib/solana/rpc-fallback.js@@ -12,7 +12,12 @@// burn through fallbacks).import { Connection } from '@solana/web3.js';-import { solanaRpcEndpoints, isEndpointCooling, markEndpointCooldown } from './connection.js';+import {+ solanaRpcEndpoints,+ isEndpointCooling,+ markEndpointCooldown,+ makeRotatingFetch,+} from './connection.js';const MAX_CONSECUTIVE_FAILS = 3;const COOLDOWN_MS = 60_000;@@ -78,6 +83,18 @@ export class RpcFallback {// instead of web3.js running its 500/1000/2000/4000ms backoff loop// ("Server responded with 429 … Retrying after Nms") on a dead lane.disableRetryOnRateLimit: true,+ // Rotate across the WHOLE endpoint set at the fetch layer, sharing the+ // process-wide cooldown map. This is essential for call sites whose fn+ // swallows the RPC error instead of rethrowing it: the sdk-bridge+ // curve/quote reads return null on a 429 rather than throwing, so the+ // withFallback() loop below would never observe a failure, never+ // rotate, never mark a cooldown — and re-hammer a quota-dead provider+ // (Helius -32429 "max usage reached") on every single poll. That was+ // the source of the "[sdk-bridge] … 429" storm. With the rotating+ // fetch the dead endpoint is skipped BEFORE the SDK call runs and is+ // parked in cooldown, so the read transparently lands on a healthy+ // provider and subsequent polls skip the dead lane outright.+ ...(this.urls.length > 1 ? { fetch: makeRotatingFetch(this.urls) } : {}),});}return this.connections[this.currentIndex];diff --git a/api/_lib/solana/sdk-bridge.js b/api/_lib/solana/sdk-bridge.jsindex 6bd60776d..1a473242a 100644--- a/api/_lib/solana/sdk-bridge.js+++ b/api/_lib/solana/sdk-bridge.js@@ -33,6 +33,20 @@ function isMissingAccount(err) {return /account does not exist|has no data|could not find/i.test(String(err));}+// Transient RPC *infrastructure* failures — provider rate-limit/quota (429,+// -32429 "max usage reached"), gateway 5xx, or a network blip. These are not+// code faults and are already handled upstream: the RpcFallback connection+// rotates off the throttled provider at the fetch layer (logging a single+// "[solana-rpc] … cooling" line) and the curve/quote endpoints fall back to a+// Jupiter price. Re-warning on every swallowed 429 here is what turned one+// quota-exhausted provider into thousands of duplicate "[sdk-bridge] … 429"+// lines. Stay quiet for these; genuine parse/programming errors still warn.+function isTransientRpc(err) {+ return /\b(429|500|502|503|504)\b|-32429|max usage reached|rate.?limit|quota|exhausted|timed?\s*out|fetch failed|socket hang up|ECONNRESET|ETIMEDOUT|ECONNREFUSED|EAI_AGAIN|all solana rpc endpoints failed|all rpc endpoints exhausted/i.test(+ String(err && err.message ? err.message : err),+ );+}+async function fetchState(connection, mint) {const { OnlinePumpSdk } = await loadSdk();const sdk = new OnlinePumpSdk(connection);@@ -57,7 +71,7 @@ export async function getTokenPrice(connection, mint) {const { global, feeConfig, bondingCurve, mintSupply } = await fetchState(connection, pk);return sdkGetTokenPrice({ global, feeConfig, mintSupply, bondingCurve });} catch (err) {- if (!err?.graduated && !isMissingAccount(err)) {+ if (!err?.graduated && !isMissingAccount(err) && !isTransientRpc(err)) {console.warn('[sdk-bridge] getTokenPrice failed: %s', String(err).slice(0, 120));}return null;@@ -75,7 +89,7 @@ export async function getGraduationProgress(connection, mint) {]);return sdkGetGrad(global, bondingCurve);} catch (err) {- if (!isMissingAccount(err)) {+ if (!isMissingAccount(err) && !isTransientRpc(err)) {console.warn('[sdk-bridge] getGraduationProgress failed: %s', String(err).slice(0, 120));}return null;@@ -96,7 +110,7 @@ export async function getBuyQuote(connection, mint, solAmount) {const impact = calculateBuyPriceImpact({ global, feeConfig, mintSupply, bondingCurve, solAmount: amount });return { tokens, priceImpact: impact.impactBps / 100 };} catch (err) {- if (!isMissingAccount(err)) {+ if (!isMissingAccount(err) && !isTransientRpc(err)) {console.warn('[sdk-bridge] getBuyQuote failed: %s', String(err).slice(0, 120));}return null;@@ -117,7 +131,7 @@ export async function getSellQuote(connection, mint, tokenAmount) {const impact = calculateSellPriceImpact({ global, feeConfig, mintSupply, bondingCurve, tokenAmount: amount });return { sol, priceImpact: impact.impactBps / 100 };} catch (err) {- if (!isMissingAccount(err)) {+ if (!isMissingAccount(err) && !isTransientRpc(err)) {console.warn('[sdk-bridge] getSellQuote failed: %s', String(err).slice(0, 120));}return null;@@ -141,7 +155,7 @@ export async function getBondingCurveState(connection, mint) {isMayhemMode: Boolean(bc.isMayhemMode),};} catch (err) {- if (!isMissingAccount(err)) {+ if (!isMissingAccount(err) && !isTransientRpc(err)) {console.warn('[sdk-bridge] getBondingCurveState failed: %s', String(err).slice(0, 120));}return null;diff --git a/api/_lib/subscription-checkout.js b/api/_lib/subscription-checkout.jsnew file mode 100644index 000000000..184bb5455--- /dev/null+++ b/api/_lib/subscription-checkout.js@@ -0,0 +1,298 @@+// Subscription checkout — the on-chain "build tx → sign → verify → activate"+// path for a user subscribing to an agent's tier (subscription_plans row).+//+// Flow:+// 1. /api/subscriptions/subscribe quotes the exact USDC split, mints a+// Solana-Pay reference, persists a `subscription_checkouts` row, and returns+// a server-built VersionedTransaction the buyer signs.+// 2. /api/subscriptions/verify hands the broadcast signature back here. We+// validate the on-chain transfer against the PERSISTED quote (never the+// client's numbers), then activate the subscription:+// · creator_subscriptions — the tier subscription record (status active)+// · subscription_payments — the first-period payment ledger row+// · user_agent_subscriptions — the access gate hasSkillAccess() reads+//+// Mirrors api/_lib/purchase-confirm.js (one-off skill unlocks) for the+// subscription context.++import { PublicKey } from '@solana/web3.js';+import { findReference, validateTransfer } from '@solana/pay';+import BigNumber from 'bignumber.js';++import { sql } from './db.js';+import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';+import { insertNotification } from './notify.js';+import { resolvePayoutAddress } from './purchase-confirm.js';+import {+ USDC_MAINNET_MINT,+ USDC_DECIMALS,+ usdToUsdcAtomics,+ intervalMs,+ computePeriod,+} from './subscription-pricing.js';++// Re-export the pure pricing helpers so existing callers keep importing them+// from here; the math itself lives in subscription-pricing.js (I/O-free, tested).+export { USDC_MAINNET_MINT, USDC_DECIMALS, usdToUsdcAtomics, intervalMs, computePeriod };++let _rpc;+function rpc() {+ if (!_rpc) _rpc = rpcFallbackFromEnv({ network: 'mainnet' });+ return _rpc;+}++// ── Payout resolution ────────────────────────────────────────────────────────++/**+ * Resolve the Solana payout address that should receive the subscription+ * payment. Agent-scoped tiers route to the agent owner's payout wallet; the+ * marketplace UI only ever surfaces agent-scoped tiers.+ * @param {{ agent_id: string|null }} plan+ * @returns {Promise<string|null>}+ */+export async function resolveSubscriptionPayout(plan) {+ if (plan.agent_id) {+ const direct = await resolvePayoutAddress(plan.agent_id, 'solana');+ if (direct) return direct;+ // Fall back to the agent metadata's recorded Solana address.+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${plan.agent_id}`;+ return row?.meta?.solana_address ?? null;+ }+ // Creator-scoped plan (no agent): use the creator's default Solana payout wallet.+ const [row] = await sql`+ SELECT address FROM agent_payout_wallets+ WHERE user_id = ${plan.creator_id} AND chain = 'solana' AND is_default = true+ ORDER BY created_at ASC+ LIMIT 1+ `;+ return row?.address ?? null;+}++// ── On-chain verification ────────────────────────────────────────────────────++// The fee leg carries no Solana-Pay reference of its own (the reference rides+// the seller leg, which validateTransfer checks), so confirm it via the same+// balance-delta technique @solana/pay uses — matched on the parsed token+// balance's `owner`, robust to versioned txs and ATA addressing.+async function feeLegSatisfied(txSignature, feeWallet, splTokenMint, minAtomics) {+ if (minAtomics <= 0n) return true;+ const tx = await rpc().withFallback((conn) =>+ conn.getParsedTransaction(txSignature, {+ commitment: 'confirmed',+ maxSupportedTransactionVersion: 0,+ }),+ );+ if (!tx || tx.meta?.err) return false;+ const mintStr = splTokenMint.toBase58();+ const matches = (b) => b && b.mint === mintStr && b.owner === feeWallet;+ const pre = tx.meta.preTokenBalances?.find(matches);+ const post = tx.meta.postTokenBalances?.find(matches);+ const preAmt = BigInt(pre?.uiTokenAmount?.amount ?? '0');+ const postAmt = BigInt(post?.uiTokenAmount?.amount ?? '0');+ return postAmt - preAmt >= minAtomics;+}++/**+ * Validate that the on-chain transaction settles the persisted checkout quote.+ *+ * The buyer signs a server-built tx with two legs — (price − fee) to the creator+ * and the fee to the treasury — both bound by the shared reference. We also+ * accept a single full-amount transfer to the creator (no fee taken), so a buyer+ * who paid the full price via a fallback path is never blocked.+ *+ * @param {object} checkout — a subscription_checkouts row.+ * @param {string|null} txSignature — the broadcast signature (preferred); when+ * absent we locate the tx by reference.+ * @returns {Promise<{ status: 'confirmed'|'pending'|'mismatch', tx_signature?: string, message?: string }>}+ */+export async function verifySubscriptionPayment(checkout, txSignature = null) {+ const refKey = new PublicKey(checkout.reference);+ const recipient = new PublicKey(checkout.recipient);+ const splToken = new PublicKey(checkout.currency_mint);+ const pow = new BigNumber(10).pow(USDC_DECIMALS);+ const gross = new BigNumber(checkout.amount);+ const creatorLeg = new BigNumber(checkout.creator_amount);+ const feeAtomics = new BigNumber(checkout.platform_fee_amount || 0);+ const feeWallet = checkout.platform_fee_wallet || null;++ // Resolve the signature: trust a caller-supplied one, else scan by reference.+ let signature = txSignature;+ if (!signature) {+ try {+ const info = await rpc().withFallback((conn) =>+ findReference(conn, refKey, { finality: 'confirmed' }),+ );+ signature = info.signature;+ } catch (e) {+ if (/FindReferenceError|not found/i.test(e?.message || '')) return { status: 'pending' };+ throw e;+ }+ }++ const validateLeg = (who, amountAtomics) =>+ rpc().withFallback((conn) =>+ validateTransfer(+ conn,+ signature,+ { recipient: who, amount: amountAtomics.dividedBy(pow), splToken, reference: refKey },+ { commitment: 'confirmed' },+ ),+ );++ // Attempt the quoted split first, then the full-amount fallback.+ const attempts = [];+ if (feeAtomics.gt(0) && feeWallet) {+ attempts.push({ creator: creatorLeg, feeTaken: feeAtomics, feeWallet });+ }+ attempts.push({ creator: gross, feeTaken: new BigNumber(0), feeWallet: null });++ let lastErr = null;+ for (const a of attempts) {+ try {+ await validateLeg(recipient, a.creator);+ if (a.feeTaken.gt(0)) {+ const ok = await feeLegSatisfied(signature, a.feeWallet, splToken, BigInt(a.feeTaken.toFixed(0)));+ if (!ok) throw new Error('platform fee leg missing or short');+ }+ return { status: 'confirmed', tx_signature: signature };+ } catch (e) {+ // A tx that simply isn't on-chain yet surfaces as a validation error too;+ // treat "not found / not finalized" as still-pending so the client retries.+ if (/not found|was not found|not.*confirmed|not.*finalized/i.test(e?.message || '')) {+ return { status: 'pending' };+ }+ lastErr = e;+ }+ }+ return { status: 'mismatch', tx_signature: signature, message: lastErr?.message || 'transfer did not match the quoted amount' };+}++// ── Activation ───────────────────────────────────────────────────────────────++/**+ * Activate a verified checkout: flip the checkout to confirmed (once), then+ * create/refresh the tier subscription, ledger the payment, and open the+ * agent-level access gate. Idempotent — a second call returns the existing+ * subscription without double-writing.+ *+ * @param {object} checkout — a subscription_checkouts row (must include plan_id,+ * user_id, agent_id, amount, currency_mint, chain, interval, reference).+ * @param {string} txSignature+ * @param {string|null} buyerWallet — the buyer's wallet address (for the record).+ */+export async function activateSubscription(checkout, txSignature, buyerWallet = null) {+ // Claim the checkout exactly once.+ const claimed = await sql`+ UPDATE subscription_checkouts+ SET status = 'confirmed', tx_signature = ${txSignature}, confirmed_at = now()+ WHERE id = ${checkout.id} AND status = 'pending'+ RETURNING id+ `;+ if (claimed.length === 0) {+ // Already processed (concurrent verify / double-click) — return current state.+ const [sub] = await sql`+ SELECT cs.id, cs.status, cs.current_period_start, cs.current_period_end, cs.plan_id+ FROM creator_subscriptions cs+ WHERE cs.plan_id = ${checkout.plan_id} AND cs.subscriber_user_id = ${checkout.user_id}+ `;+ return { subscription: sub || null, already_processed: true };+ }++ const [plan] = await sql`+ SELECT id, creator_id, agent_id, name, price_usd, interval+ FROM subscription_plans WHERE id = ${checkout.plan_id}+ `;+ const interval = checkout.interval || plan?.interval || 'monthly';+ const { start, end } = computePeriod(interval);+ const priceUsd = plan?.price_usd != null ? Number(plan.price_usd) : Number(checkout.amount) / 10 ** USDC_DECIMALS;++ // 1. Tier subscription record (creator_subscriptions). Re-activate a prior+ // cancelled/past_due row, else insert fresh.+ const [existing] = await sql`+ SELECT id FROM creator_subscriptions+ WHERE plan_id = ${checkout.plan_id} AND subscriber_user_id = ${checkout.user_id}+ `;+ let subscription;+ if (existing) {+ [subscription] = await sql`+ UPDATE creator_subscriptions+ SET status = 'active',+ current_period_start = ${start.toISOString()},+ current_period_end = ${end.toISOString()},+ payment_method = 'solana',+ wallet_address = ${buyerWallet},+ cancelled_at = NULL+ WHERE id = ${existing.id}+ RETURNING id, plan_id, status, current_period_start, current_period_end+ `;+ } else {+ [subscription] = await sql`+ INSERT INTO creator_subscriptions+ (plan_id, subscriber_user_id, status, current_period_start, current_period_end,+ payment_method, wallet_address)+ VALUES+ (${checkout.plan_id}, ${checkout.user_id}, 'active', ${start.toISOString()},+ ${end.toISOString()}, 'solana', ${buyerWallet})+ RETURNING id, plan_id, status, current_period_start, current_period_end+ `;+ }++ // 2. First-period payment ledger row.+ await sql`+ INSERT INTO subscription_payments (subscription_id, amount_usd, status, tx_hash, paid_at)+ VALUES (${subscription.id}, ${priceUsd}, 'succeeded', ${txSignature}, now())+ `;++ // 3. Open the access gate hasSkillAccess() reads. Agent-scoped only.+ if (checkout.agent_id) {+ try {+ await sql`+ INSERT INTO user_agent_subscriptions+ (user_id, agent_id, status, current_period_ends_at, tx_signature,+ price_amount, currency_mint, chain)+ VALUES+ (${checkout.user_id}, ${checkout.agent_id}, 'active', ${end.toISOString()},+ ${txSignature}, ${checkout.amount}, ${checkout.currency_mint}, ${checkout.chain})+ ON CONFLICT (user_id, agent_id) DO UPDATE SET+ status = 'active',+ current_period_ends_at = EXCLUDED.current_period_ends_at,+ tx_signature = EXCLUDED.tx_signature,+ price_amount = EXCLUDED.price_amount,+ currency_mint = EXCLUDED.currency_mint,+ chain = EXCLUDED.chain,+ cancelled_at = NULL,+ updated_at = now()+ `;+ } catch (e) {+ // Access still tracked via creator_subscriptions; never block the+ // confirm on the gate write.+ console.warn('[subscription-checkout] access gate upsert failed', e?.message);+ }+ }++ // 4. Notify both sides.+ await insertNotification(checkout.user_id, 'subscription_activated', {+ plan_id: checkout.plan_id,+ agent_id: checkout.agent_id,+ plan_name: plan?.name || null,+ amount_usd: priceUsd,+ current_period_end: end.toISOString(),+ tx_signature: txSignature,+ }).catch(() => {});+ if (plan?.creator_id && plan.creator_id !== checkout.user_id) {+ await insertNotification(plan.creator_id, 'new_subscriber', {+ plan_id: checkout.plan_id,+ agent_id: checkout.agent_id,+ plan_name: plan?.name || null,+ amount_usd: priceUsd,+ tx_signature: txSignature,+ }).catch(() => {});+ }++ return {+ subscription,+ current_period_start: start.toISOString(),+ current_period_end: end.toISOString(),+ already_processed: false,+ };+}diff --git a/api/_lib/subscription-pricing.js b/api/_lib/subscription-pricing.jsnew file mode 100644index 000000000..26a3d512d--- /dev/null+++ b/api/_lib/subscription-pricing.js@@ -0,0 +1,41 @@+// Pure subscription pricing + period math. No I/O, no Solana, no DB — so it is+// cheap to unit-test and safe to import anywhere. The on-chain + DB logic lives+// in subscription-checkout.js, which re-exports these for its callers.++// Canonical mainnet USDC mint (6 decimals). Subscriptions price in USD; the+// on-chain leg settles in USDC at parity.+export const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+export const USDC_DECIMALS = 6;++/**+ * Convert a USD price (numeric, e.g. 9.99) to USDC atomic units (6 decimals).+ * Rounds to the nearest atomic so a price like 4.999 can't silently truncate.+ * @param {number|string} priceUsd+ * @returns {bigint}+ */+export function usdToUsdcAtomics(priceUsd) {+ const n = Number(priceUsd);+ if (!Number.isFinite(n) || n < 0) throw new Error('invalid price');+ return BigInt(Math.round(n * 10 ** USDC_DECIMALS));+}++/**+ * Period length in ms for a plan interval. weekly → 7d, anything else → 30d+ * (matches subscription-billing.js + the creator_subscriptions cron).+ * @param {string} interval+ */+export function intervalMs(interval) {+ return interval === 'weekly' ? 7 * 24 * 3600 * 1000 : 30 * 24 * 3600 * 1000;+}++/**+ * Compute the subscription period window from a start date + plan interval.+ * @param {string} interval+ * @param {Date} [from]+ * @returns {{ start: Date, end: Date }}+ */+export function computePeriod(interval, from = new Date()) {+ const start = new Date(from.getTime());+ const end = new Date(start.getTime() + intervalMs(interval));+ return { start, end };+}diff --git a/api/_providers/nvidia.js b/api/_providers/nvidia.jsindex a131cdd1c..7485ea7a0 100644--- a/api/_providers/nvidia.js+++ b/api/_providers/nvidia.js@@ -94,6 +94,18 @@ const NVCF_POLL_SECONDS = 30;const SUBMIT_TIMEOUT_MS = 45_000;const POLL_TIMEOUT_MS = 60_000;+// NVCF can answer a cold model — or a momentary capacity/routing blip at the+// gateway — with a transient 502/503/504, or drop the socket before a worker is+// warm. None of these is terminal: a single short retry usually lands once the+// model spins up, which keeps the FREE lane from dead-ending straight to the+// (often equally throttled) paid Replicate lane and surfacing to the user as a+// hard 502. Bounded to one retry so a genuinely-down upstream still fails over+// fast rather than burning the whole serverless budget on a dead provider.+const GATEWAY_RETRY_STATUSES = new Set([502, 503, 504]);+const MAX_INVOKE_ATTEMPTS = 2;+const INVOKE_RETRY_DELAY_MS = 1_500;+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+// Sampling steps per quality tier, clamped to TRELLIS's accepted 10–50 window.// More steps = finer geometry/texture at higher latency; draft stays cheap so// the free lane returns a usable preview fast.@@ -279,63 +291,92 @@ export function createNvidiaProvider() {// generation completed synchronously (200) or { done:false, reqId } when NVCF// accepted it for async processing (202). Throws normalized provider errors.async function postInvoke(body, extraHeaders) {- let res;- try {- res = await fetch(TRELLIS_INVOKE_URL, {- method: 'POST',- headers: { ...invokeHeaders, ...extraHeaders },- body: JSON.stringify(body),- signal: AbortSignal.timeout(SUBMIT_TIMEOUT_MS),- });- } catch (err) {- throw Object.assign(new Error(`nvidia unreachable: ${err?.message}`), {- code: 'provider_unreachable',- status: 502,- });- }-- if (res.status === 202) {- const reqId = res.headers.get('nvcf-reqid');- if (!reqId) {- throw Object.assign(new Error('NVCF accepted the job but returned no NVCF-REQID'), {- code: 'provider_error',+ let lastErr = null;+ for (let attempt = 1; attempt <= MAX_INVOKE_ATTEMPTS; attempt++) {+ let res;+ try {+ res = await fetch(TRELLIS_INVOKE_URL, {+ method: 'POST',+ headers: { ...invokeHeaders, ...extraHeaders },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(SUBMIT_TIMEOUT_MS),+ });+ } catch (err) {+ // Socket abort / DNS blip — transient. Retry once before giving up so a+ // single dropped connection doesn't fail the whole free lane.+ lastErr = Object.assign(new Error(`nvidia unreachable: ${err?.message}`), {+ code: 'provider_unreachable',status: 502,});+ if (attempt < MAX_INVOKE_ATTEMPTS) {+ await sleep(INVOKE_RETRY_DELAY_MS);+ continue;+ }+ throw lastErr;}- return { done: false, reqId };- }- if (res.ok) {- // NVCF sometimes returns 200 (instead of 202) with { artifacts: [] } and- // an NVCF-REQID header when routing to async processing. Read the header- // before consuming the body so we can fall through to the poll path.- const reqId = res.headers.get('nvcf-reqid');- const { base64, diag } = await extractGlbBase64(res);- if (!base64) {- if (reqId) {- // Async job on 200 — same path as 202.- return { done: false, reqId };+ if (res.status === 202) {+ const reqId = res.headers.get('nvcf-reqid');+ if (!reqId) {+ throw Object.assign(new Error('NVCF accepted the job but returned no NVCF-REQID'), {+ code: 'provider_error',+ status: 502,+ });}- console.warn('[nvidia] sync 200 but no GLB artifact — %s', diag);- throw Object.assign(new Error('TRELLIS completed but returned no GLB artifact'), {- code: 'provider_error',- status: 502,- });+ return { done: false, reqId };}- return { done: true, glbBase64: base64 };- }- let detail = '';- try {- const d = await res.json();- detail = d?.detail || d?.message || d?.title || '';- // TRELLIS 422s carry `detail` as an array of validation objects — keep- // it human-readable rather than collapsing to "[object Object]".- if (detail && typeof detail !== 'string') detail = JSON.stringify(detail);- } catch {- detail = await res.text().catch(() => '');+ if (res.ok) {+ // NVCF sometimes returns 200 (instead of 202) with { artifacts: [] } and+ // an NVCF-REQID header when routing to async processing. Read the header+ // before consuming the body so we can fall through to the poll path.+ const reqId = res.headers.get('nvcf-reqid');+ const { base64, diag } = await extractGlbBase64(res);+ if (!base64) {+ if (reqId) {+ // Async job on 200 — same path as 202.+ return { done: false, reqId };+ }+ console.warn('[nvidia] sync 200 but no GLB artifact — %s', diag);+ throw Object.assign(new Error('TRELLIS completed but returned no GLB artifact'), {+ code: 'provider_error',+ status: 502,+ });+ }+ return { done: true, glbBase64: base64 };+ }++ // Transient gateway status — the model is likely cold-starting or a node+ // is momentarily unavailable. Drain the body so the socket frees, then+ // retry once; everything else (auth, quota, 4xx, 429) is terminal here and+ // surfaced as a normalized provider error the forge layer routes around.+ if (GATEWAY_RETRY_STATUSES.has(res.status) && attempt < MAX_INVOKE_ATTEMPTS) {+ await res.text().catch(() => {});+ lastErr = providerError(res.status, undefined, res.headers.get('retry-after'));+ await sleep(INVOKE_RETRY_DELAY_MS);+ continue;+ }++ let detail = '';+ try {+ const d = await res.json();+ detail = d?.detail || d?.message || d?.title || '';+ // TRELLIS 422s carry `detail` as an array of validation objects — keep+ // it human-readable rather than collapsing to "[object Object]".+ if (detail && typeof detail !== 'string') detail = JSON.stringify(detail);+ } catch {+ detail = await res.text().catch(() => '');+ }+ throw providerError(res.status, detail || undefined, res.headers.get('retry-after'));}- throw providerError(res.status, detail || undefined, res.headers.get('retry-after'));+ // Exhausted retries on a transient status/throw without a terminal verdict.+ throw (+ lastErr ||+ Object.assign(new Error('nvidia invoke failed after retries'), {+ code: 'provider_error',+ status: 502,+ })+ );}// Finish a submission: persist immediately on synchronous completion,diff --git a/api/agent-skill-price.js b/api/agent-skill-price.jsindex 2e605ec77..615a6f524 100644--- a/api/agent-skill-price.js+++ b/api/agent-skill-price.js@@ -9,6 +9,7 @@ import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.jimport { cors, error, json, method, readJson, wrap, rateLimited } from './_lib/http.js';import { requireCsrf } from './_lib/csrf.js';import { clientIp, limits } from './_lib/rate-limit.js';+import { invalidateSkillPriceCache } from './_lib/skill-price-cache.js';import { z } from 'zod';const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -84,5 +85,6 @@ export default wrap(async (req, res) => {`;}+ await invalidateSkillPriceCache(agentId);return json(res, 200, { data: { ok: true } });});diff --git a/api/agent-skills.js b/api/agent-skills.jsindex 481370137..a6ab59787 100644--- a/api/agent-skills.js+++ b/api/agent-skills.js@@ -8,6 +8,7 @@ import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.jimport { cors, error, json, method, readJson, wrap, rateLimited } from './_lib/http.js';import { requireCsrf } from './_lib/csrf.js';import { clientIp, limits } from './_lib/rate-limit.js';+import { invalidateSkillPriceCache } from './_lib/skill-price-cache.js';import { z } from 'zod';const setPriceSchema = z.object({@@ -81,6 +82,7 @@ async function handleSetPrice(req, res, agentId) {`;}+ await invalidateSkillPriceCache(agentId);return json(res, 200, { data: { ok: true } });}diff --git a/api/agents.js b/api/agents.jsindex 334093b49..52ed210c3 100644--- a/api/agents.js+++ b/api/agents.js@@ -21,6 +21,7 @@ import { checkIdentityIntegrity } from './_lib/identity-integrity.js';import { publicUrl } from './_lib/r2.js';import { pingIndexNow } from './_lib/indexnow.js';import { publishFeedEvent } from './_lib/feed.js';+import { getSkillPrices, skillPriceMap } from './_lib/skill-price-cache.js';import { env } from './_lib/env.js';import { z } from 'zod';@@ -321,31 +322,13 @@ export async function handleGetOne(req, res, id) {const rl = await limits.publicIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- // Single roundtrip: pull skill_prices as a JSON-aggregated subquery- // instead of a follow-up SELECT. Saves a second DB hop per GET on- // /api/agents/:id (was the dominant cost on cached pages where- // healStaleAvatarId is a no-op).const [row] = await sql`SELECT i.*,u.display_name as author_name,u.avatar_url as author_avatar,a.storage_key AS avatar_storage_key,a.thumbnail_key AS avatar_thumbnail_key,- a.visibility AS avatar_visibility,- COALESCE(- (SELECT jsonb_object_agg(- sp.skill,- jsonb_build_object(- 'amount', sp.amount,- 'currency_mint', sp.currency_mint,- 'chain', sp.chain,- 'trial_uses', sp.trial_uses- )- )- FROM agent_skill_prices sp- WHERE sp.agent_id = i.id AND sp.is_active = true),- '{}'::jsonb- ) AS skill_prices+ a.visibility AS avatar_visibilityFROM agent_identities iLEFT JOIN users u ON i.user_id = u.idLEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL@@ -353,6 +336,11 @@ export async function handleGetOne(req, res, id) {`;if (!row) return error(res, 404, 'not_found', 'agent not found');+ // Skill prices come from the cache (1h TTL, invalidated on price edits)+ // rather than an inline subquery, so the dominant repeat read on this hot+ // path never touches agent_skill_prices once the agent is warm.+ row.skill_prices = skillPriceMap(await getSkillPrices(id));+await healStaleAvatarId(row);// chat_count is supplementary decoration on the agent record — never letdiff --git a/api/agents/[id]/skill-access.js b/api/agents/[id]/skill-access.jsindex b9a6e73e2..764ea4f42 100644--- a/api/agents/[id]/skill-access.js+++ b/api/agents/[id]/skill-access.js@@ -21,7 +21,7 @@ import { sql } from '../../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';import { clientIp, limits } from '../../_lib/rate-limit.js';-import { getSkillPrices } from '../../_lib/skill-price-cache.js';+import { getSkillPrices, skillPriceMap } from '../../_lib/skill-price-cache.js';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -61,20 +61,7 @@ export default wrap(async (req, res) => {: Promise.resolve([]),]);- const skill_prices = Object.fromEntries(- priceRows.map((p) => [- p.skill,- {- amount: p.amount,- currency_mint: p.currency_mint,- chain: p.chain,- mint_decimals: p.mint_decimals ?? 6,- trial_uses: p.trial_uses ?? 0,- time_pass_hours: p.time_pass_hours ?? null,- time_pass_amount: p.time_pass_amount ?? null,- },- ]),- );+ const skill_prices = skillPriceMap(priceRows);const purchased_skills = purchasedRows.map((r) => r.skill);return json(diff --git a/api/agents/[id]/skill-prices.js b/api/agents/[id]/skill-prices.jsindex 3fa4bad22..9d27f2f5b 100644--- a/api/agents/[id]/skill-prices.js+++ b/api/agents/[id]/skill-prices.js@@ -89,7 +89,7 @@ export default wrap(async (req, res) => {is_active = true,updated_at = now()`;- invalidateSkillPriceCache(agentId);+ await invalidateSkillPriceCache(agentId);return json(res, 200, { data: { ok: true } });}@@ -111,7 +111,7 @@ export default wrap(async (req, res) => {RETURNING agent_id`;if (r.length === 0) return error(res, 404, 'not_found', 'no existing price for this skill');- invalidateSkillPriceCache(agentId);+ await invalidateSkillPriceCache(agentId);return json(res, 200, { data: { ok: true } });}@@ -125,6 +125,6 @@ export default wrap(async (req, res) => {SET is_active = false, updated_at = now()WHERE agent_id = ${agentId} AND skill = ${parsed.data.skill}`;- invalidateSkillPriceCache(agentId);+ await invalidateSkillPriceCache(agentId);return json(res, 200, { data: { ok: true } });});diff --git a/api/agents/[id]/skills-pricing.js b/api/agents/[id]/skills-pricing.jsindex cee94e4da..30a2b8ca3 100644--- a/api/agents/[id]/skills-pricing.js+++ b/api/agents/[id]/skills-pricing.js@@ -1,8 +1,7 @@-import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';import { requireCsrf } from '../../_lib/csrf.js';-import { invalidateSkillPriceCache } from '../../_lib/skill-price-cache.js';+import { MonetizationService } from '../../_lib/services/MonetizationService.js';import { z } from 'zod';const priceSchema = z.object({@@ -32,28 +31,27 @@ export default wrap(async (req, res) => {// CSRF on state-changing session-cookie requests; bearer tokens are exempt.if (req.method === 'PUT' && !(await requireCsrf(req, res, auth.userId))) return;- const [agent] = await sql`- SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL- `;- if (!agent) return error(res, 404, 'not_found', 'agent not found');- if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');+ const service = new MonetizationService(auth);- if (req.method === 'GET') return handleGet(req, res, id);- if (req.method === 'PUT') return handlePut(req, res, id);+ // Ownership gates both reads and writes on this owner-only surface.+ try {+ await service.assertOwnership(id);+ } catch (e) {+ return error(res, e.status || 500, e.code || 'error', e.message);+ }++ if (req.method === 'GET') return handleGet(req, res, service, id);+ if (req.method === 'PUT') return handlePut(req, res, service, id);return method(req, res, ['GET', 'PUT']);});-async function handleGet(req, res, agentId) {- const prices = await sql`- SELECT skill, amount, currency_mint, chain- FROM agent_skill_prices- WHERE agent_id = ${agentId} AND is_active = true- `;+async function handleGet(req, res, service, agentId) {+ const prices = await service.getSkillPricesForAgent(agentId);return json(res, 200, { prices });}-async function handlePut(req, res, agentId) {+async function handlePut(req, res, service, agentId) {const body = await readJson(req);const parsed = pricingUpdateSchema.safeParse(body);if (!parsed.success) {@@ -61,40 +59,9 @@ async function handlePut(req, res, agentId) {return error(res, 400, 'validation_error', msg);}- const { prices } = parsed.data;-- // Neon's serverless driver runs a transaction as an ARRAY of queries in a- // single round-trip — not the interactive `async (tx) => {}` callback of- // node-postgres (which throws "transaction() expects an array of queries, or- // a function returning an array of queries"). Every statement is known up- // front, so we build the array and pass it. Atomic: the deactivate + all- // upserts commit together or not at all.- const statements = [- // Deactivate all existing prices for this agent…- sql`UPDATE agent_skill_prices SET is_active = false WHERE agent_id = ${agentId}`,- // …then (re)assert the submitted set as the active prices.- ...prices.map(- (p) => sql`- INSERT INTO agent_skill_prices- (agent_id, skill, amount, currency_mint, chain, is_active, trial_uses, time_pass_hours, time_pass_amount)- VALUES- (${agentId}, ${p.skill}, ${p.amount}, ${p.currency_mint}, ${p.chain}, true,- ${p.trial_uses ?? 0}, ${p.time_pass_hours ?? null}, ${p.time_pass_amount ?? null})- ON CONFLICT (agent_id, skill) DO UPDATE SET- amount = EXCLUDED.amount,- currency_mint = EXCLUDED.currency_mint,- chain = EXCLUDED.chain,- is_active = true,- trial_uses = EXCLUDED.trial_uses,- time_pass_hours = EXCLUDED.time_pass_hours,- time_pass_amount = EXCLUDED.time_pass_amount,- updated_at = now()- `,- ),- ];-- await sql.transaction(statements);- invalidateSkillPriceCache(agentId);+ // Ownership already asserted above — the service performs the atomic+ // deactivate-then-upsert and invalidates the price cache.+ await service.setSkillPrices(agentId, parsed.data.prices, { skipOwnershipCheck: true });return json(res, 200, { ok: true });}diff --git a/api/agents/[id]/tiers.js b/api/agents/[id]/tiers.jsindex d974c42a1..2c72a31bf 100644--- a/api/agents/[id]/tiers.js+++ b/api/agents/[id]/tiers.js@@ -4,7 +4,8 @@* Routes (vercel.json rewrites map /api/agents/:id/tiers → this file):* GET /api/agents/:id/tiers list active tiers for agent (public)* POST /api/agents/:id/tiers create tier (auth, agent owner)- * PATCH /api/agents/:id/tiers/:tierId update tier (auth, agent owner)+ * PUT /api/agents/:id/tiers/:tierId update tier (auth, agent owner)+ * PATCH /api/agents/:id/tiers/:tierId update tier (alias of PUT)* DELETE /api/agents/:id/tiers/:tierId deactivate tier (auth, agent owner)** Tiers are stored in the `subscription_plans` table scoped by agent_id.@@ -26,6 +27,7 @@ const createSchema = z.object({price_usd: z.number().min(0.99).max(999),interval: z.enum(['weekly', 'monthly']).default('monthly'),perks: z.array(z.string().trim().max(120)).max(10).default([]),+ included_skills: z.array(z.string().trim().min(1).max(120)).max(50).default([]),});const patchSchema = z.object({@@ -33,11 +35,12 @@ const patchSchema = z.object({price_usd: z.number().min(0.99).max(999).optional(),interval: z.enum(['weekly', 'monthly']).optional(),perks: z.array(z.string().trim().max(120)).max(10).optional(),+ included_skills: z.array(z.string().trim().min(1).max(120)).max(50).optional(),active: z.boolean().optional(),});export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;+ if (cors(req, res, { methods: 'GET,POST,PUT,PATCH,DELETE,OPTIONS', credentials: true })) return;const url = new URL(req.url, 'http://x');// Path: /api/agents/:agentId/tiers or /api/agents/:agentId/tiers/:tierId@@ -50,7 +53,7 @@ export default wrap(async (req, res) => {if (req.method === 'GET') return handleList(req, res, agentId);if (req.method === 'POST' && !tierId) return handleCreate(req, res, agentId);- if (req.method === 'PATCH' && tierId) return handlePatch(req, res, agentId, tierId);+ if ((req.method === 'PUT' || req.method === 'PATCH') && tierId) return handleUpdate(req, res, agentId, tierId);if (req.method === 'DELETE' && tierId) return handleDelete(req, res, agentId, tierId);return error(res, 405, 'method_not_allowed', 'method not allowed');@@ -77,7 +80,7 @@ async function handleList(req, res, agentId) {if (!rl.success) return rateLimited(res, rl);const rows = await sql`- SELECT id, name, price_usd, interval, perks, active, created_at+ SELECT id, name, price_usd, interval, perks, included_skills, active, created_atFROM subscription_plansWHERE agent_id = ${agentId} AND active = trueORDER BY price_usd ASC@@ -109,18 +112,18 @@ async function handleCreate(req, res, agentId) {const [tier] = await sql`INSERT INTO subscription_plans- (creator_id, agent_id, name, price_usd, interval, perks)+ (creator_id, agent_id, name, price_usd, interval, perks, included_skills)VALUES- (${user.id}, ${agentId}, ${body.name}, ${body.price_usd}, ${body.interval}, ${body.perks})- RETURNING id, name, price_usd, interval, perks, active, created_at+ (${user.id}, ${agentId}, ${body.name}, ${body.price_usd}, ${body.interval}, ${body.perks}, ${body.included_skills})+ RETURNING id, name, price_usd, interval, perks, included_skills, active, created_at`;return json(res, 201, { tier });}-// ── Update ────────────────────────────────────────────────────────────────────+// ── Update (PUT / PATCH) ──────────────────────────────────────────────────────-async function handlePatch(req, res, agentId, tierId) {- if (!method(req, res, ['PATCH'])) return;+async function handleUpdate(req, res, agentId, tierId) {+ if (!method(req, res, ['PUT', 'PATCH'])) return;const user = await requireAgentOwner(req, res, agentId);if (!user) return;@@ -140,6 +143,7 @@ async function handlePatch(req, res, agentId, tierId) {if (body.price_usd !== undefined) { params.push(body.price_usd); setFrags.push(`price_usd = $${params.length}`); }if (body.interval !== undefined) { params.push(body.interval); setFrags.push(`interval = $${params.length}`); }if (body.perks !== undefined) { params.push(body.perks); setFrags.push(`perks = $${params.length}`); }+ if (body.included_skills !== undefined) { params.push(body.included_skills); setFrags.push(`included_skills = $${params.length}`); }if (body.active !== undefined) { params.push(body.active); setFrags.push(`active = $${params.length}`); }if (setFrags.length === 0) return error(res, 400, 'validation_error', 'nothing to update');@@ -149,7 +153,7 @@ async function handlePatch(req, res, agentId, tierId) {const [tier] = await sql(`UPDATE subscription_plans SET ${setFrags.join(', ')}WHERE id = $${tidIdx} AND creator_id = $${uidIdx}- RETURNING id, name, price_usd, interval, perks, active, created_at`,+ RETURNING id, name, price_usd, interval, perks, included_skills, active, created_at`,params,);return json(res, 200, { tier });diff --git a/api/agents/_id/pricing/[skill].js b/api/agents/_id/pricing/[skill].jsindex 3aab48f7f..94d1fe77e 100644--- a/api/agents/_id/pricing/[skill].js+++ b/api/agents/_id/pricing/[skill].js@@ -5,6 +5,7 @@ import { cors, json, method, readJson, wrap, error, rateLimited } from '../../..import { parse } from '../../../_lib/validate.js';import { limits, clientIp } from '../../../_lib/rate-limit.js';import { requireCsrf } from '../../../_lib/csrf.js';+import { invalidateSkillPriceCache } from '../../../_lib/skill-price-cache.js';// First char must be alphanumeric; rest may include hyphens; total 1–64 chars.const SKILL_RE = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/;@@ -79,6 +80,7 @@ export default wrap(async (req, res) => {FROM agent_skill_prices WHERE agent_id = ${id} AND skill = ${skill}`;+ await invalidateSkillPriceCache(id);return json(res, existing ? 200 : 201, row);}@@ -95,5 +97,6 @@ export default wrap(async (req, res) => {`;}+ await invalidateSkillPriceCache(id);return json(res, 200, { deleted: true });});diff --git a/api/agents/pricing.js b/api/agents/pricing.jsindex d3ac337ea..b4be4eee5 100644--- a/api/agents/pricing.js+++ b/api/agents/pricing.js@@ -8,6 +8,7 @@ import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';+import { invalidateSkillPriceCache } from '../_lib/skill-price-cache.js';import { z } from 'zod';const bodySchema = z.object({@@ -75,5 +76,6 @@ export default wrap(async (req, res) => {`;}+ await invalidateSkillPriceCache(agentId);return json(res, 200, { data: { ok: true } });});diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].jsindex d5521cbab..134175627 100644--- a/api/agents/x402/[action].js+++ b/api/agents/x402/[action].js@@ -9,9 +9,24 @@ import { parse, isUuid } from '../../_lib/validate.js';import { emit402, verifyPaid, consumeIntent, manifestOnly } from '../../_lib/x402.js';import { calculateFee } from '../../_lib/fee.js';import { insertNotification } from '../../_lib/notify.js';+import { hasSkillAccess, consumeTrialUse, logSkillUsage } from '../../_lib/skill-access.js';const HANDLERS = { echo: async (args) => ({ ok: true, echoed: args }) };+// Run a skill either via a registered server handler or by delegating to the+// in-process skill-runtime. The skill name on the agent is treated as a+// "<skill>.<tool>" qualifier; a bare call defaults the tool to the skill name —+// the runtime surfaces a descriptive error if there's no matching export.+async function executeSkill(agent, body, caller, signerAddress) {+ if (HANDLERS[body.skill]) {+ return HANDLERS[body.skill](body.args, { agent, caller });+ }+ const { makeRuntime } = await import('../../_lib/skill-runtime.js');+ const runtime = makeRuntime({ agentId: agent.id, signerAddress });+ const tool = typeof body.args?._tool === 'string' ? body.args._tool : body.skill;+ return runtime.invoke(`${body.skill}.${tool}`, body.args);+}+// C1 — x402 bridge: prices come from the canonical agent_skill_prices table// first (the marketplace's source of truth), with the legacy meta.skill_prices// jsonb as a fallback for agents priced before the marketplace migration.@@ -35,9 +50,9 @@ async function priceFor(agent, skill) {async function resolveAuth(req) {const session = await getSessionUser(req);- if (session) return { userId: session.id };+ if (session) return { userId: session.id, kind: 'session' };const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId, scope: bearer.scope };+ if (bearer) return { userId: bearer.userId, scope: bearer.scope, kind: 'bearer' };return null;}@@ -83,6 +98,55 @@ async function handleInvoke(req, res) {if (!price) {return error(res, 409, 'no_payments', `skill "${body.skill}" is not priced on this agent`);}++ // Access-control gate. For skills carrying a canonical agent_skill_prices+ // entry (access.paid), a buyer who already purchased the skill or holds a+ // subscription/trial covering it executes WITHOUT a fresh x402 charge —+ // double-billing someone who already paid would be theft. Legacy meta-priced+ // skills (no canonical price row) report paid:false and fall through to the+ // pay-per-call x402 path below unchanged.+ const access = await hasSkillAccess(auth.userId, agent.id, body.skill);+ if (access.paid && access.owned) {+ const startedAt = Date.now();+ const result = await executeSkill(agent, body, auth, null);+ if (access.trial) {+ await consumeTrialUse(auth.userId, agent.id, body.skill).catch(() => {});+ }+ logSkillUsage({+ userId: auth.userId,+ agentId: agent.id,+ skillName: body.skill,+ status: result?.ok === false ? 'failure' : 'success',+ executionTimeMs: Date.now() - startedAt,+ });+ return json(res, 200, {+ ok: true,+ access: access.via_subscription ? 'subscription' : access.trial ? 'trial' : 'purchase',+ ...(access.trial+ ? { trial_remaining: Math.max(0, (access.trial_remaining ?? 1) - 1) }+ : {}),+ result,+ });+ }++ // Priced but unowned. A human session caller (cookie auth) cannot construct an+ // x402 payment, so a 402 pay-per-call challenge — meant for autonomous agents —+ // is a dead end for them. Send them to the marketplace with a 403 instead.+ if (access.paid && auth.kind === 'session') {+ return error(+ res,+ 403,+ 'skill_access_denied',+ 'You do not have access to this skill. Please purchase it from the marketplace.',+ {+ agent_id: agent.id,+ skill: body.skill,+ reason: access.reason || 'not_purchased',+ price: { amount: price.amount, currency: price.currency, chain: price.chain ?? 'solana' },+ },+ );+ }+const paid = await verifyPaid(req, {agentId: agent.id,skill: body.skill,@@ -124,22 +188,7 @@ async function handleInvoke(req, res) {// Execute the skill BEFORE consuming the payment intent: if the handler// throws, wrap() returns the error with the intent untouched, so the buyer's// payment still covers a retry instead of being burned on a failed call.- let result;- if (handlerExists) {- result = await HANDLERS[body.skill](body.args, { agent, caller: auth });- } else {- // Delegate to the in-process skill-runtime. The skill name on the agent- // is treated as a "<skill>.<tool>" qualifier; if the caller passed bare- // args (no tool), default to the skill name as the tool too — runtime- // will surface a descriptive error if there's no matching export.- const { makeRuntime } = await import('../../_lib/skill-runtime.js');- const runtime = makeRuntime({- agentId: agent.id,- signerAddress: paid.payerAddress || null,- });- const tool = typeof body.args?._tool === 'string' ? body.args._tool : body.skill;- result = await runtime.invoke(`${body.skill}.${tool}`, body.args);- }+ const result = await executeSkill(agent, body, auth, paid.payerAddress || null);await consumeIntent(paid.intentId);const gross = parseInt(paid.amount, 10);diff --git a/api/forge.js b/api/forge.jsindex 694396a85..e5d89c199 100644--- a/api/forge.js+++ b/api/forge.js@@ -46,6 +46,7 @@ import {resolveBackendId,estimateEtaSeconds,estimateCredits,+ preferFreeReconstruct,buildCatalog,} from './_lib/forge-tiers.js';import { resolveProviderKey } from './_lib/forge-provider-key.js';@@ -194,6 +195,19 @@ function isUpstreamUnavailable(err) {);}+// A leaked paid-account billing/credit message from the platform's OWN vendor+// (e.g. Replicate "You have insufficient credit to run this model… purchase+// credit") is internal infra state — surfacing it to the user is both useless+// (they can't fund our account) and a billing-state leak. Detect it so the+// boundary can answer with an honest, generic "temporarily unavailable" instead.+// BYOK callers are excluded at the call site: a credit message about THEIR OWN+// account is actionable, so it's surfaced verbatim.+function isPaidCreditFailure(err) {+ if (err?.providerStatus === 402) return true;+ const text = `${err?.message || ''} ${err?.providerDetail || ''}`.toLowerCase();+ return /insufficient credit|purchase credit|account\/billing|out of credit|not enough credit/.test(text);+}+// Free NVIDIA NIM TRELLIS text→3D lane, extracted so it serves two callers:// 1. the draft default (backendId === 'nvidia'), and// 2. the never-dead-end fallback the paid image-intermediate TRELLIS lane@@ -303,7 +317,23 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path }) {// this returns status:'done' synchronously like the NVIDIA sync branch — no// poll handle to route. Returns true once a 200 is written, false when the lane// is unavailable so the caller can surface its own error.-async function runHfImageLane({ req, res, ip, imageUrls, prompt, aspect, tier, path }) {+async function runHfImageLane({+ req,+ res,+ ip,+ imageUrls,+ prompt,+ aspect,+ tier,+ path,+ // Text→3D feeds this lane a FLUX-synthesized reference view, so provenance must+ // be able to report text_to_3d (+ the synthesis model) rather than always+ // image_to_3d. Defaults keep the original image→3D behavior for callers that+ // pass user photos.+ mode = 'image_to_3d',+ previewImageUrl = null,+ textToImageModel = null,+}) {let provider;try {const mod = await import('./_providers/huggingface.js');@@ -333,16 +363,18 @@ async function runHfImageLane({ req, res, ip, imageUrls, prompt, aspect, tier, p}const backendId = 'huggingface';+ const isImageMode = mode === 'image_to_3d';+ const preview = previewImageUrl || imageUrls[0];const clientKey = clientKeyFrom(req);const syntheticJob = randomUUID().replace(/-/g, '');const creationId = await createCreation({clientKey,ipHash: hashIp(ip),- prompt: prompt || 'image-to-3d',+ prompt: prompt || (isImageMode ? 'image-to-3d' : ''),aspect,- previewImageUrl: imageUrls[0],+ previewImageUrl: preview,replicateJobId: syntheticJob,- textToImageModel: null,+ textToImageModel: isImageMode ? null : textToImageModel,viewsRequested: imageUrls.length,viewsUsed: imageUrls.length,multiview: imageUrls.length > 1,@@ -363,13 +395,14 @@ async function runHfImageLane({ req, res, ip, imageUrls, prompt, aspect, tier, pstatus: 'done',glb_url: durable?.glbUrl ?? resultGlbUrl,durable: Boolean(durable),- mode: 'image_to_3d',+ mode,path,tier: tier.id,backend: backendId,prompt: prompt || null,- preview_image_url: imageUrls[0],- reference_image_urls: [imageUrls[0]],+ preview_image_url: preview,+ reference_image_urls: isImageMode ? [imageUrls[0]] : [preview],+ text_to_image_model: isImageMode ? null : textToImageModel,eta_seconds: estimateEtaSeconds({ backendId, tier }),estimated_credits: estimateCredits({ backendId, path, tier }),});@@ -880,6 +913,35 @@ async function startJob(req, res) {views = [referenceImageUrl];}+ // Free-first: exhaust the free reconstruct lane (HuggingFace Spaces) BEFORE+ // the paid Replicate default, so a forge call never spends on — or dead-ends+ // against — the paid account while a free lane can serve it. We already hold+ // the reference views (uploaded, or FLUX-synthesized above), so the free lane+ // reconstructs from exactly what Replicate would have. Scoped to the default+ // trellis lane: an explicitly chosen Hunyuan3D / Replicate-BYOK backend is+ // honored as picked. When the free lane is unavailable (no HF_TOKEN) or it+ // fails, we fall through to Replicate, which keeps its own fallback chain.+ // Reversible via FORGE_PREFER_FREE=false. Provenance reports backend:huggingface+ // so the chosen lane is never silent.+ if (preferFreeReconstruct() && backendId === 'trellis') {+ if (+ await runHfImageLane({+ req,+ res,+ ip,+ imageUrls: views,+ prompt,+ aspect,+ tier,+ path,+ mode: isImageMode ? 'image_to_3d' : 'text_to_3d',+ previewImageUrl: referenceImageUrl,+ textToImageModel,+ })+ )+ return;+ }+// Only poly-aware backends (Hunyuan3D self-host) accept a target budget;// TRELLIS validates its input schema and would 422 on an unknown field, so// the tier rides along as the recorded provenance only.@@ -943,7 +1005,21 @@ async function startJob(req, res) {console.warn(`[forge] platform TRELLIS lane unavailable (${submitErr?.providerStatus || submitErr?.code}); trying free HuggingFace ${mode3d} lane`,);- if (await runHfImageLane({ req, res, ip, imageUrls: views, prompt, aspect, tier, path })) {+ if (+ await runHfImageLane({+ req,+ res,+ ip,+ imageUrls: views,+ prompt,+ aspect,+ tier,+ path,+ mode: isImageMode ? 'image_to_3d' : 'text_to_3d',+ previewImageUrl: referenceImageUrl,+ textToImageModel,+ })+ ) {return;}throw submitErr;@@ -1016,7 +1092,10 @@ async function startJob(req, res) {message: err.message || 'The provider rejected this API key.',});}- if (err?.code === 'insufficient_credits') {+ if (err?.code === 'insufficient_credits' && BACKENDS[backendId]?.byok) {+ // BYOK lane: the message names the CALLER'S own provider account, which+ // they can act on — surface it. The platform's own paid lane falls through+ // to the sanitized "temporarily unavailable" state below.return json(res, 402, {error: 'insufficient_credits',message: err.message || 'The provider account is out of credits.',@@ -1054,6 +1133,22 @@ async function startJob(req, res) {retry_after: retryAfter,});}+ // Free lanes are exhausted and the only remaining lane was the platform's+ // PAID vendor account, which is out of credit. The vendor's raw "buy credit"+ // message is our internal billing state and is useless to the user — answer+ // with an honest, generic unavailable state instead of leaking it. (BYOK lanes+ // kept their actionable account message via the insufficient_credits branch.)+ if (!BACKENDS[backendId]?.byok && isPaidCreditFailure(err)) {+ console.warn(+ `[forge] paid reconstruct lane out of credit and no free lane available: ${err?.message || err}`,+ );+ res.setHeader('retry-after', '30');+ return json(res, 503, {+ error: 'generation_unavailable',+ message: 'Free 3D generation is temporarily unavailable. Please try again shortly.',+ retry_after: 30,+ });+ }return json(res, 502, {error: 'generation_failed',message: err?.message || 'The generator could not start this job.',diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex 2761a950a..6fd33e64d 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -23,6 +23,7 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/import { publicUrl } from '../_lib/r2.js';import { clientIp, limits } from '../_lib/rate-limit.js';import { markProviderCooldown, AUTH_COOLDOWN_SECONDS } from '../_lib/provider-health.js';+import { getSkillPrices, skillPriceMap } from '../_lib/skill-price-cache.js';import { z } from 'zod';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -653,18 +654,51 @@ async function handleDetail(req, res, id) {return error(res, 404, 'not_found', 'agent not found');}- const [priceRows, purchasedRows] = await Promise.all([- sql`- SELECT skill, currency_mint, chain, amount, mint_decimals, trial_uses, time_pass_hours, time_pass_amount- FROM agent_skill_prices- WHERE agent_id = ${id} AND is_active = true- `,+ // Skill prices via the shared cache (1h TTL, invalidated on price edits) so+ // the marketplace detail page — the highest-traffic priced read — serves+ // warm agents without re-querying agent_skill_prices on every view.+ // Missing-table tolerance: subscription_plans / creator_subscriptions ship+ // behind a migration. If a deploy hasn't applied them yet, treat them as+ // "no tiers" rather than 500-ing the whole agent detail.+ const tolerateMissing = async (run) => {+ try {+ return await run();+ } catch (err) {+ if (err.code === '42P01') return [];+ throw err;+ }+ };++ const [priceRows, purchasedRows, tierRows, subRows] = await Promise.all([+ getSkillPrices(id),auth? sql`SELECT skill FROM skill_purchasesWHERE user_id = ${auth.userId} AND agent_id = ${id} AND status = 'confirmed'`: Promise.resolve([]),+ // Active subscription tiers configured for this agent, cheapest first.+ tolerateMissing(() => sql`+ SELECT id, name, price_usd, interval, perks, included_skills+ FROM subscription_plans+ WHERE agent_id = ${id} AND active = true+ ORDER BY price_usd ASC+ `),+ // The signed-in viewer's active subscription to this agent (if any), so+ // the UI can mark the current tier and offer management instead of a+ // duplicate sign-up.+ auth+ ? tolerateMissing(() => sql`+ SELECT cs.id, cs.plan_id, cs.status, cs.current_period_end+ FROM creator_subscriptions cs+ JOIN subscription_plans sp ON sp.id = cs.plan_id+ WHERE cs.subscriber_user_id = ${auth.userId}+ AND sp.agent_id = ${id}+ AND cs.status = 'active'+ ORDER BY cs.current_period_end DESC+ LIMIT 1+ `)+ : Promise.resolve([]),]);let bookmarked = false;@@ -674,27 +708,52 @@ async function handleDetail(req, res, id) {bookmarked = !!b;}- const skill_prices = Object.fromEntries(- priceRows.map((p) => [- p.skill,- {- amount: p.amount,- currency_mint: p.currency_mint,- chain: p.chain,- mint_decimals: p.mint_decimals ?? 6,- trial_uses: p.trial_uses ?? 0,- time_pass_hours: p.time_pass_hours ?? null,- time_pass_amount: p.time_pass_amount ?? null,- },- ]),- );+ const skill_prices = skillPriceMap(priceRows);const purchased_skills = purchasedRows.map((r) => r.skill);+ const subscription_tiers = tierRows.map((t) => ({+ id: t.id,+ name: t.name,+ // numeric(8,2) comes back as a string from postgres — normalise to a+ // number so the client doesn't have to guess the shape.+ price_usd: Number(t.price_usd),+ interval: t.interval,+ perks: Array.isArray(t.perks) ? t.perks : [],+ included_skills: Array.isArray(t.included_skills) ? t.included_skills : [],+ }));+ const user_subscription = subRows[0]+ ? {+ id: subRows[0].id,+ plan_id: subRows[0].plan_id,+ status: subRows[0].status,+ current_period_end: subRows[0].current_period_end,+ }+ : null;++ // The payload carries viewer-specific state (bookmarked, purchased_skills,+ // user_subscription). Only the anonymous shape is safe for a shared cache —+ // authenticated reads must stay private so one viewer's state never lands+ // in another's response.+ const cacheControl = auth+ ? 'private, max-age=0, must-revalidate'+ : 'public, max-age=15';+return json(res,200,- { data: { agent: { ...toDetail(row), skill_prices, bookmarked, purchased_skills } } },- { 'cache-control': 'public, max-age=15' },+ {+ data: {+ agent: {+ ...toDetail(row),+ skill_prices,+ bookmarked,+ purchased_skills,+ subscription_tiers,+ user_subscription,+ },+ },+ },+ { 'cache-control': cacheControl },);}diff --git a/api/marketplace/buy-asset.js b/api/marketplace/buy-asset.jsindex de5a75368..c2599441c 100644--- a/api/marketplace/buy-asset.js+++ b/api/marketplace/buy-asset.js@@ -26,11 +26,14 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/import { clientIp, limits } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';+import { solanaConnection } from '../_lib/solana/connection.js';+import { buildGaslessPurchaseTx } from '../_lib/solana/gasless-tx.js';import { insertNotification } from '../_lib/notify.js';import { verifyEvmUsdcPayment, evmChainId } from '../_lib/evm-payment-verify.js';const REFERENCE_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const ITEM_TYPES = ['avatar', 'agent', 'plugin'];+const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';let _rpc;function rpc() {@@ -116,6 +119,11 @@ async function handleCreate(req, res) {if (!ITEM_TYPES.includes(itemType) || !itemId) {return error(res, 400, 'validation_error', 'item_type and item_id required');}+ // Optional connected-wallet pubkey → platform-sponsored (gasless) transaction.+ const buyerPublicKey =+ typeof body?.buyer_public_key === 'string' && REFERENCE_RE.test(body.buyer_public_key)+ ? body.buyer_public_key+ : null;const [price] = await sql`SELECT amount, currency_mint, chain, mint_decimals, owner_user_id@@ -183,6 +191,31 @@ async function handleCreate(req, res) {row = inserted;}+ // Gasless checkout: sponsor the network fee with a pre-signed+ // VersionedTransaction when the buyer's Solana wallet is connected. A whole+ // asset is a single full-amount transfer to the seller (no platform fee leg).+ let gaslessBlock = {};+ if (buyerPublicKey && row.chain === 'solana') {+ try {+ const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });+ const prepared = await buildGaslessPurchaseTx({+ connection,+ buyerPublicKey,+ recipient: payoutAddress,+ mint: row.currency_mint,+ creatorAtomics: BigInt(row.amount),+ reference: row.reference,+ decimals: price.mint_decimals,+ });+ if (prepared) {+ gaslessBlock = { transaction: prepared.transaction, gasless: true, fee_payer: prepared.feePayer };+ }+ } catch (e) {+ // Sponsorship is best-effort — the buyer can still pay for the tx.+ console.warn('[buy-asset] gasless prepare failed:', e?.message);+ }+ }+return json(res, 201, {data: {reference: row.reference,@@ -196,6 +229,7 @@ async function handleCreate(req, res) {message,item_type: itemType,item_id: itemId,+ ...gaslessBlock,},});}diff --git a/api/marketplace/check-skill-access.js b/api/marketplace/check-skill-access.jsindex f4a5710e9..18e3738df 100644--- a/api/marketplace/check-skill-access.js+++ b/api/marketplace/check-skill-access.js@@ -3,10 +3,10 @@* Returns { has_access: boolean } for the authenticated caller.*/-import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';+import { MonetizationService } from '../_lib/services/MonetizationService.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -27,11 +27,7 @@ export default wrap(async (req, res) => {return error(res, 400, 'validation_error', 'agent_id and skill required');}- const [row] = await sql`- SELECT 1 AS x FROM skill_purchases- WHERE user_id = ${userId} AND agent_id = ${agentId}- AND skill = ${skill} AND status = 'confirmed'- LIMIT 1- `;- return json(res, 200, { data: { has_access: !!row } });+ const service = new MonetizationService(userId);+ const { has_access } = await service.checkSkillOwnership(agentId, skill);+ return json(res, 200, { data: { has_access } });});diff --git a/api/marketplace/purchase.js b/api/marketplace/purchase.jsindex 7a1ed9e43..1cceec0ee 100644--- a/api/marketplace/purchase.js+++ b/api/marketplace/purchase.js@@ -16,15 +16,18 @@* Routed via vercel.json rewrites — see project root.*/-import { Keypair } from '@solana/web3.js';-import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';-import { confirmSkillPurchase, logEvent, resolvePayoutAddress } from '../_lib/purchase-confirm.js';+import { logEvent } from '../_lib/purchase-confirm.js';import { requireCsrf } from '../_lib/csrf.js';-import { resolveMarketplaceFee } from '../_lib/marketplace-platform-fee.js';+import { MonetizationService } from '../_lib/services/MonetizationService.js';+import { solanaConnection } from '../_lib/solana/connection.js';+import { buildGaslessPurchaseTx } from '../_lib/solana/gasless-tx.js';+import { resolveRecipient } from '../_lib/resolve-recipient.js';++const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';const REFERENCE_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/; // base58 Pubkey@@ -81,156 +84,83 @@ async function handleCreate(req, res) {if (!agentId || !skill) {return error(res, 400, 'validation_error', 'agent_id and skill required');}+ // Optional: when the browser wallet is already connected it passes its+ // pubkey so we can return a platform-sponsored (gasless) transaction.+ const buyerPublicKey =+ typeof body?.buyer_public_key === 'string' && REFERENCE_RE.test(body.buyer_public_key)+ ? body.buyer_public_key+ : null;++ // Referrer is resolved from the request (querystring / account link) and+ // attributed only when a brand-new pending row is created.+ const referrerUserId = await resolveReferrer(req, auth.userId);- // Look up the active price for this skill on this agent.- const [price] = await sql`- SELECT amount, currency_mint, chain, mint_decimals, trial_uses, time_pass_hours, time_pass_amount- FROM agent_skill_prices- WHERE agent_id = ${agentId} AND skill = ${skill} AND is_active = true- `;- if (!price) return error(res, 404, 'not_found', 'this skill is not for sale');-- // Resolve the agent owner's payout wallet for the relevant chain.- const [payout] = await sql`- SELECT pw.address- FROM agent_identities a- JOIN agent_payout_wallets pw- ON pw.user_id = a.user_id- AND pw.chain = ${price.chain}- AND (pw.agent_id = a.id OR pw.is_default = true)- WHERE a.id = ${agentId} AND a.deleted_at IS NULL- ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC- LIMIT 1- `;- if (!payout?.address) {- return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');+ // Gifting: the buyer may target another user by username / wallet / id. We+ // resolve it to a real account here (never trusting a raw id from the client),+ // so the service only ever sees a validated recipient user id. An unresolvable+ // recipient fails the whole checkout — better than silently buying for self.+ const recipientRaw = body?.recipient ?? body?.recipient_id ?? null;+ let recipientUserId = null;+ if (recipientRaw != null && String(recipientRaw).trim() !== '') {+ const recipient = await resolveRecipient(String(recipientRaw));+ if (!recipient) {+ return error(res, 400, 'recipient_not_found', 'no user matches that username or wallet');+ }+ if (recipient.id === auth.userId) {+ return error(res, 400, 'cannot_gift_self', 'you already own purchases you make for yourself');+ }+ recipientUserId = recipient.id;}- // Already-owned short-circuit: any active access (confirmed purchase, live trial,- // unexpired time-pass) returns the existing row so the buyer doesn't pay twice.- const [existing] = await sql`- SELECT reference, status, tx_signature, confirmed_at, valid_until, trial_remaining, kind- FROM skill_purchases- WHERE user_id = ${auth.userId} AND agent_id = ${agentId} AND skill = ${skill}- AND status IN ('confirmed', 'trial')- AND (valid_until IS NULL OR valid_until > now())- ORDER BY (status = 'confirmed') DESC, confirmed_at DESC NULLS LAST- LIMIT 1- `;- if (existing) {- return json(res, 200, {- data: {- already_owned: true,- reference: existing.reference,- status: existing.status,- tx_signature: existing.tx_signature,- confirmed_at: existing.confirmed_at,- valid_until: existing.valid_until,- trial_remaining: existing.trial_remaining,- kind: existing.kind,- },- });+ // The service owns the purchase quote: price lookup, payout resolution,+ // already-owned short-circuit, idempotent pending reuse, fee split, and the+ // persisted skill_purchases row. The handler stays at the HTTP + transport+ // layer (gasless sponsorship) on top of that quote.+ const service = new MonetizationService(auth);+ let result;+ try {+ result = await service.preparePurchaseTransaction(agentId, skill, { durationHours, referrerUserId, recipientUserId });+ } catch (e) {+ if (e.status) return error(res, e.status, e.code, e.message);+ throw e;}- // Idempotent create (A4): reuse a fresh pending row for the same (user, agent, skill)- // rather than minting a new reference on every retry click.- const referrerUserId = await resolveReferrer(req, auth.userId);- const [pending] = await sql`- SELECT reference, amount, currency_mint, chain, expires_at,- platform_fee_amount, platform_fee_wallet- FROM skill_purchases- WHERE user_id = ${auth.userId} AND agent_id = ${agentId} AND skill = ${skill}- AND status = 'pending'- AND expires_at > now()- ORDER BY created_at DESC- LIMIT 1- `;- // Determine if this is a time-pass purchase. Prefer explicitly passed duration_hours,- // then fall back to the skill's time_pass_hours if set.- const effectiveDurationHours = durationHours ?? (price.time_pass_hours || null);- const isTimePass = effectiveDurationHours != null;- const purchaseAmount = isTimePass && price.time_pass_amount ? price.time_pass_amount : price.amount;- const purchaseKind = isTimePass ? 'time_pass' : 'purchase';-- // Platform fee (Solana only — the split is one atomic SPL transfer the buyer- // signs). Computed once at create and persisted on the row so confirm verifies- // the exact split that was quoted, even if the fee config changes meanwhile.- const feeInfo = price.chain === 'solana'- ? await resolveMarketplaceFee({ grossAtomics: BigInt(purchaseAmount) })- : null;- const platformFeeAmount = feeInfo ? feeInfo.feeAtomics : 0n;- const platformFeeWallet = feeInfo ? feeInfo.recipient.toBase58() : null;-- const reference = pending?.reference ?? Keypair.generate().publicKey.toBase58();- const label = isTimePass- ? `${effectiveDurationHours}h Access: ${skill.slice(0, 30)}`- : `Skill: ${skill.slice(0, 40)}`;- const message = isTimePass- ? `Get ${effectiveDurationHours}-hour access to '${skill}'`- : `Unlock '${skill}' for this agent`;-- let row = pending;- if (!pending) {- const validUntil = isTimePass- ? sql`now() + (${effectiveDurationHours} || ' hours')::interval`- : sql`null`;-- const [inserted] = await sql`- INSERT INTO skill_purchases (- user_id, agent_id, skill, status, reference,- amount, currency_mint, chain, expires_at, kind, referrer_user_id, valid_until,- platform_fee_amount, platform_fee_wallet- )- VALUES (- ${auth.userId}, ${agentId}, ${skill}, 'pending', ${reference},- ${purchaseAmount}, ${price.currency_mint}, ${price.chain},- now() + interval '30 minutes', ${purchaseKind}, ${referrerUserId}, ${validUntil},- ${platformFeeAmount.toString()}, ${platformFeeWallet}- )- RETURNING reference, amount, currency_mint, chain, expires_at, valid_until,- platform_fee_amount, platform_fee_wallet- `;- row = inserted;- await logEvent(row.reference, 'created', { agent_id: agentId, skill, kind: purchaseKind });- } else {- await logEvent(pending.reference, 'create_idempotent_hit', { agent_id: agentId, skill });+ if (result.already_owned) return json(res, 200, { data: result });++ const { already_owned, ...quote } = result;++ // Gasless checkout: when the buyer's wallet is connected and this is a Solana+ // purchase, the platform builds the SPL transfer as a fee-payer-sponsored+ // VersionedTransaction and pre-signs it. The buyer adds only their authority+ // signature in the wallet — no SOL required. Falls back to a buyer-pays+ // transaction (transaction = null) when no payer is configured or for the+ // mobile QR path. The split here matches exactly what confirm verifies.+ let gaslessBlock = {};+ if (buyerPublicKey && quote.chain === 'solana') {+ try {+ const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });+ const prepared = await buildGaslessPurchaseTx({+ connection,+ buyerPublicKey,+ recipient: quote.recipient,+ mint: quote.currency_mint,+ creatorAtomics: BigInt(quote.creator_amount),+ reference: quote.reference,+ decimals: quote.mint_decimals,+ platformFeeAtomics: quote.fee ? BigInt(quote.fee.amount) : 0n,+ platformFeeWallet: quote.fee?.recipient ?? null,+ });+ if (prepared) {+ gaslessBlock = { transaction: prepared.transaction, gasless: true, fee_payer: prepared.feePayer };+ }+ } catch (e) {+ // Never block checkout on the sponsorship optimization — the buyer can+ // still build and pay for the transaction themselves.+ await logEvent(quote.reference, 'gasless_prepare_failed', { reason: e?.message });+ }}- // The split the buyer will sign, derived from the PERSISTED row so the- // quote here matches exactly what confirm verifies on-chain. `amount` is the- // full price the buyer pays; `creator_amount` is the seller's leg; `fee` is- // the platform leg to the treasury (omitted entirely when no fee applies).- const rowFee = BigInt(row.platform_fee_amount || 0);- const creatorAmount = (BigInt(row.amount) - rowFee).toString();- const feeBlock = rowFee > 0n && row.platform_fee_wallet- ? {- fee: {- recipient: row.platform_fee_wallet,- amount: rowFee.toString(),- bps: Number((rowFee * 10000n) / BigInt(row.amount)),- },- }- : {};-- return json(res, 201, {- data: {- reference: row.reference,- recipient: payout.address,- amount: String(row.amount),- creator_amount: creatorAmount,- currency_mint: row.currency_mint,- chain: row.chain,- mint_decimals: price.mint_decimals,- expires_at: row.expires_at,- valid_until: row.valid_until,- kind: purchaseKind,- label,- message,- ...feeBlock,- ...(isTimePass ? { duration_hours: effectiveDurationHours } : {}),- ...(price.time_pass_hours ? { time_pass_hours: price.time_pass_hours, time_pass_amount: price.time_pass_amount } : {}),- },- });+ return json(res, 201, { data: { ...quote, ...gaslessBlock } });}// ── Status ─────────────────────────────────────────────────────────────────@@ -270,34 +200,21 @@ async function handleConfirm(req, res, reference) {const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const [pur] = await sql`- SELECT sp.id, sp.user_id, sp.agent_id, sp.skill, sp.status,- sp.amount, sp.currency_mint, sp.chain, sp.tx_signature,- sp.expires_at, sp.referrer_user_id,- sp.platform_fee_amount, sp.platform_fee_wallet,- COALESCE(asp.mint_decimals, 6) AS mint_decimals- FROM skill_purchases sp- LEFT JOIN agent_skill_prices asp- ON asp.agent_id = sp.agent_id AND asp.skill = sp.skill- WHERE sp.reference = ${reference} AND sp.user_id = ${auth.userId}- `;- if (!pur) return error(res, 404, 'not_found', 'purchase not found');- if (pur.status === 'confirmed') {- return json(res, 200, { data: { status: 'confirmed', tx_signature: pur.tx_signature } });- }- if (pur.status === 'expired' || (pur.expires_at && new Date(pur.expires_at) < new Date())) {- return error(res, 410, 'purchase_expired', 'this pending purchase expired; please start a new one');- }// EVM purchases settle by a tx hash the buyer submits in the confirm body;- // Solana scans the chain by reference and needs no body.- let txHash = null;- if (pur.chain !== 'solana') {- const body = await readJson(req).catch(() => null);- txHash = body?.tx_hash || body?.txHash || null;- if (!txHash) return error(res, 400, 'tx_hash_required', 'tx_hash is required to confirm an EVM purchase');+ // Solana scans the chain by reference and ignores it. Read it+ // unconditionally — the service enforces "EVM requires a tx_hash".+ const body = await readJson(req).catch(() => null);+ const txHash = body?.tx_hash || body?.txHash || null;++ const service = new MonetizationService(auth);+ let result;+ try {+ result = await service.confirmPurchase(reference, { txHash });+ } catch (e) {+ if (e.status) return error(res, e.status, e.code, e.message);+ throw e;}- const result = await confirmSkillPurchase({ ...pur, reference }, { txHash });if (result.status === 'pending') {return json(res, 200, { data: { status: 'pending' } });}diff --git a/api/marketplace/set-skill-price.js b/api/marketplace/set-skill-price.jsindex 19bd01a8e..23228831e 100644--- a/api/marketplace/set-skill-price.js+++ b/api/marketplace/set-skill-price.js@@ -8,6 +8,7 @@ import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';+import { invalidateSkillPriceCache } from '../_lib/skill-price-cache.js';import { z } from 'zod';const bodySchema = z.object({@@ -71,5 +72,6 @@ export default wrap(async (req, res) => {`;}+ await invalidateSkillPriceCache(agent_id);return json(res, 200, { data: { ok: true } });});diff --git a/api/payments/prepare-skill-purchase.js b/api/payments/prepare-skill-purchase.jsdeleted file mode 100644index 729c47c71..000000000--- a/api/payments/prepare-skill-purchase.js+++ /dev/null@@ -1,222 +0,0 @@-/**- * POST /api/payments/prepare-skill-purchase- * Builds and returns a base64-serialised Solana VersionedTransaction that the- * browser wallet signs and sends. The platform pre-signs as fee-payer so the- * buyer needs no SOL — only the USDC for the skill price.- *- * Fee split: (price - platform_fee) → creator, platform_fee → treasury.- * Both legs ride in one atomic transaction alongside the reference key.- *- * Body: { agentId, skillName, buyerPublicKey }- * Returns: { transaction (base64), reference, recipient, amount, creator_amount,- * currency_mint, fee? }- */-import {- Keypair, PublicKey,- TransactionMessage, VersionedTransaction,-} from '@solana/web3.js';-import {- getAssociatedTokenAddressSync,- createTransferCheckedInstruction,- getMint,-} from '@solana/spl-token';--import { solanaConnection } from '../_lib/solana/connection.js';-import { sql } from '../_lib/db.js';-import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';-import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';-import { clientIp, limits } from '../_lib/rate-limit.js';-import { resolveMarketplaceFee } from '../_lib/marketplace-platform-fee.js';-import { decodeSecretKey } from '../_lib/solana-signers.js';-import { z } from 'zod';--const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;--const bodySchema = z.object({- agentId: z.string().uuid(),- skillName: z.string().trim().min(1).max(100),- buyerPublicKey: z.string().regex(BASE58_RE, 'invalid public key'),-});--const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';--// Load the platform payer keypair that co-signs as fee-payer (gasless UX).-// Prefers MARKETPLACE_PAYER_KEYPAIR; falls back to PLATFORM_TREASURY_KEYPAIR.-// When neither is configured the endpoint still works but the buyer pays gas.-let _payerKeypair = undefined; // undefined = not yet resolved, null = not configured-async function resolvePlatformPayer() {- if (_payerKeypair !== undefined) return _payerKeypair;- const secret =- process.env.MARKETPLACE_PAYER_KEYPAIR ||- process.env.PLATFORM_TREASURY_KEYPAIR ||- process.env.TREASURY_KEYPAIR ||- '';- if (!secret) { _payerKeypair = null; return null; }- const bytes = await decodeSecretKey(secret);- if (!bytes) { _payerKeypair = null; return null; }- try {- _payerKeypair = Keypair.fromSecretKey(bytes);- } catch {- _payerKeypair = null;- }- return _payerKeypair;-}--async function resolveAuth(req) {- const session = await getSessionUser(req);- if (session) return { userId: session.id };- const bearer = await authenticateBearer(extractBearer(req));- if (bearer) return { userId: bearer.userId };- return null;-}--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- const auth = await resolveAuth(req);- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');-- const rl = await limits.authIp(clientIp(req));- if (!rl.success) return rateLimited(res, rl);-- const body = await readJson(req).catch(() => null);- const parsed = bodySchema.safeParse(body);- if (!parsed.success) {- return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');- }-- const { agentId, skillName, buyerPublicKey } = parsed.data;-- // Fetch active price- const [price] = await sql`- SELECT amount, currency_mint, chain, mint_decimals- FROM agent_skill_prices- WHERE agent_id = ${agentId} AND skill = ${skillName} AND is_active = true- LIMIT 1- `;- if (!price) return error(res, 404, 'not_found', 'skill is not for sale');- if (price.chain !== 'solana') {- return error(res, 400, 'unsupported_chain', `chain '${price.chain}' does not support prepared transactions`);- }-- // Resolve payout wallet- const [payout] = await sql`- SELECT pw.address- FROM agent_identities a- JOIN agent_payout_wallets pw- ON pw.user_id = a.user_id- AND pw.chain = 'solana'- AND (pw.agent_id = a.id OR pw.is_default = true)- WHERE a.id = ${agentId} AND a.deleted_at IS NULL- ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC- LIMIT 1- `;- let recipient = payout?.address;- if (!recipient) {- const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`;- recipient = row?.meta?.solana_address ?? null;- }- if (!recipient) return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');-- // Platform fee- const grossAtomics = BigInt(price.amount);- const feeInfo = await resolveMarketplaceFee({ grossAtomics });- const platformFeeAtomics = feeInfo ? feeInfo.feeAtomics : 0n;- const creatorAtomics = grossAtomics - platformFeeAtomics;-- // Reference keypair for Solana Pay tracking- const referenceKeypair = Keypair.generate();- const referenceKey = referenceKeypair.publicKey;- const reference = referenceKey.toBase58();-- // Record pending purchase- await sql`- INSERT INTO skill_purchases- (user_id, agent_id, skill, status, reference, amount, currency_mint, chain,- platform_fee_amount, platform_fee_wallet)- VALUES- (${auth.userId}, ${agentId}, ${skillName}, 'pending', ${reference},- ${price.amount}, ${price.currency_mint}, 'solana',- ${platformFeeAtomics.toString()},- ${feeInfo ? feeInfo.recipient.toBase58() : null})- ON CONFLICT DO NOTHING- `;-- // Build the SPL token transfer instructions- const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');-- const mintInfo = await getMint(connection, new PublicKey(price.currency_mint));- const decimals = mintInfo.decimals;-- const buyer = new PublicKey(buyerPublicKey);- const mintKey = new PublicKey(price.currency_mint);- const fromAta = getAssociatedTokenAddressSync(mintKey, buyer);-- const creatorKey = new PublicKey(recipient);- const toAta = getAssociatedTokenAddressSync(mintKey, creatorKey);-- // Creator leg — append reference key so findReference can locate this tx- const creatorIx = createTransferCheckedInstruction(- fromAta, mintKey, toAta, buyer, creatorAtomics, decimals,- );- creatorIx.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });-- const instructions = [creatorIx];-- // Platform fee leg (same tx — atomic)- if (platformFeeAtomics > 0n && feeInfo?.recipient) {- const treasuryAta = getAssociatedTokenAddressSync(mintKey, feeInfo.recipient);- instructions.push(- createTransferCheckedInstruction(- fromAta, mintKey, treasuryAta, buyer, platformFeeAtomics, decimals,- ),- );- }-- // Platform co-signs as fee-payer (gasless for the buyer).- // Falls back to buyer-pays if no payer keypair is configured.- const platformPayer = await resolvePlatformPayer();- const feePayer = platformPayer ? platformPayer.publicKey : buyer;-- const messageV0 = new TransactionMessage({- payerKey: feePayer,- recentBlockhash: blockhash,- instructions,- }).compileToV0Message();-- const tx = new VersionedTransaction(messageV0);-- if (platformPayer) {- tx.sign([platformPayer]);- }-- const serialized = Buffer.from(tx.serialize());-- const feeBlock = platformFeeAtomics > 0n && feeInfo- ? {- fee: {- recipient: feeInfo.recipient.toBase58(),- amount: platformFeeAtomics.toString(),- bps: feeInfo.bps,- },- }- : {};-- return json(res, 200, {- data: {- transaction: serialized.toString('base64'),- reference,- recipient,- amount: String(price.amount),- creator_amount: creatorAtomics.toString(),- currency_mint: price.currency_mint,- mint_decimals: price.mint_decimals ?? decimals,- gasless: !!platformPayer,- label: `Skill: ${skillName.slice(0, 40)}`,- message: `Unlock '${skillName}' for this agent`,- ...feeBlock,- },- });-});diff --git a/api/payments/purchase-skill.js b/api/payments/purchase-skill.jsindex 978c39044..2d32f8679 100644--- a/api/payments/purchase-skill.js+++ b/api/payments/purchase-skill.js@@ -10,11 +10,14 @@ import { sql } from '../_lib/db.js';import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';+import { resolveRecipient } from '../_lib/resolve-recipient.js';import { z } from 'zod';const bodySchema = z.object({agentId: z.string().uuid(),skillName: z.string().trim().min(1).max(100),+ // Optional gift target: username, wallet address, or user id.+ recipient: z.string().trim().min(1).max(120).optional(),});async function resolveAuth(req) {@@ -41,7 +44,19 @@ export default wrap(async (req, res) => {return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');}- const { agentId, skillName } = parsed.data;+ const { agentId, skillName, recipient: recipientRaw } = parsed.data;++ // Optional gift target. The payer stays in user_id; recipient_user_id is the+ // beneficiary who receives access. Resolve server-side so a raw id is never+ // trusted from the client.+ let recipientUserId = null;+ if (recipientRaw) {+ const recipient = await resolveRecipient(recipientRaw);+ if (!recipient) return error(res, 400, 'recipient_not_found', 'no user matches that username or wallet');+ if (recipient.id === auth.userId) return error(res, 400, 'cannot_gift_self', 'you already own purchases you make for yourself');+ recipientUserId = recipient.id;+ }+ const beneficiaryId = recipientUserId ?? auth.userId;// Fetch active priceconst [price] = await sql`@@ -71,24 +86,29 @@ export default wrap(async (req, res) => {}if (!recipient) return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');- // Already purchased?+ // Already purchased by the beneficiary? (the recipient for a gift, else self)const [existing] = await sql`SELECT reference, status FROM skill_purchases- WHERE user_id = ${auth.userId} AND agent_id = ${agentId} AND skill = ${skillName}+ WHERE COALESCE(recipient_user_id, user_id) = ${beneficiaryId}+ AND agent_id = ${agentId} AND skill = ${skillName}AND status = 'confirmed'LIMIT 1`;if (existing) {- return json(res, 200, { data: { already_owned: true, reference: existing.reference } });+ return json(res, 200, {+ data: recipientUserId+ ? { already_owned: true, recipient_owns: true }+ : { already_owned: true, reference: existing.reference },+ });}// Mint a Solana Pay reference keypairconst reference = Keypair.generate().publicKey.toBase58();const [row] = await sql`- INSERT INTO skill_purchases (user_id, agent_id, skill, status, reference, amount, currency_mint, chain)+ INSERT INTO skill_purchases (user_id, agent_id, skill, status, reference, amount, currency_mint, chain, recipient_user_id)VALUES (${auth.userId}, ${agentId}, ${skillName}, 'pending', ${reference},- ${price.amount}, ${price.currency_mint}, ${price.chain})+ ${price.amount}, ${price.currency_mint}, ${price.chain}, ${recipientUserId})RETURNING reference, amount, currency_mint, chain`;diff --git a/api/skills/license-onchain.js b/api/skills/license-onchain.jsnew file mode 100644index 000000000..ea45bd9e5--- /dev/null+++ b/api/skills/license-onchain.js@@ -0,0 +1,116 @@+/**+ * GET /api/skills/license-onchain+ * --------------------------------------------------------------------------+ * Trustless, database-free verification of skill ownership: does a wallet hold+ * an active on-chain `SkillLicense` for a given skill on a given agent? Reads+ * the license PDA directly from the `skill_license` Solana program (see+ * contracts/skill-license/) and reports ownership. This is the *alternative*+ * access check described in the on-chain-licenses design — anyone can call it,+ * no auth required, because it only reads public chain state.+ *+ * Query (one of agent_mint | agent_id required, plus skill + wallet):+ * wallet — base58 Solana pubkey of the holder (required)+ * skill — skill name/slug (required)+ * agent_mint — the agent's on-chain grouping mint (base58)+ * agent_id — three.ws agent uuid; resolves to that agent's skill collection mint+ * network — 'mainnet' (default) | 'devnet'+ *+ * Response: { data: { owned, exists, revoked, deployed, license, nft_mint,+ * owner_token_account, program_id, network, explorer, record } }+ */++import { sql } from '../_lib/db.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import {+ SKILL_LICENSE_PROGRAM_ID,+ verifyOnchainSkillLicense,+} from '../_lib/skill-license-onchain.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++function explorerForLicense(license, network) {+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';+ return `https://explorer.solana.com/address/${license}${cluster}`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const wallet = (url.searchParams.get('wallet') || '').trim();+ const skill = (url.searchParams.get('skill') || '').trim();+ const agentMintParam = (url.searchParams.get('agent_mint') || '').trim();+ const agentId = (url.searchParams.get('agent_id') || '').trim();+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';++ if (!BASE58_RE.test(wallet)) {+ return error(res, 400, 'validation_error', 'wallet must be a Solana address');+ }+ if (!skill || skill.length > 100) {+ return error(res, 400, 'validation_error', 'skill is required (≤100 chars)');+ }++ // Resolve the agent grouping mint: explicit agent_mint, or the agent's+ // per-agent skill collection mint looked up from its uuid.+ let agentMint = agentMintParam;+ if (!agentMint && agentId) {+ if (!UUID_RE.test(agentId)) {+ return error(res, 400, 'validation_error', 'agent_id must be a uuid');+ }+ const [agent] = await sql`+ SELECT skill_collection_mint+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (!agent.skill_collection_mint) {+ return error(+ res,+ 409,+ 'no_collection',+ 'agent has no on-chain skill collection yet — nothing can be licensed on-chain',+ );+ }+ agentMint = agent.skill_collection_mint;+ }+ if (!BASE58_RE.test(agentMint)) {+ return error(res, 400, 'validation_error', 'agent_mint or agent_id is required');+ }++ let result;+ try {+ result = await verifyOnchainSkillLicense({ ownerWallet: wallet, agentMint, skill, network });+ } catch (e) {+ return error(res, 502, 'rpc_error', `could not read on-chain license: ${e.message}`);+ }++ return json(+ res,+ 200,+ {+ data: {+ owned: result.owned,+ exists: result.exists,+ revoked: result.revoked,+ deployed: result.deployed,+ license: result.license,+ nft_mint: result.nftMint,+ owner_token_account: result.ownerTokenAccount,+ program_id: SKILL_LICENSE_PROGRAM_ID,+ agent_mint: agentMint,+ skill,+ wallet,+ network,+ explorer: explorerForLicense(result.license, network),+ record: result.record,+ },+ },+ { 'cache-control': 'public, max-age=10' },+ );+});diff --git a/api/subscriptions/subscribe.js b/api/subscriptions/subscribe.jsnew file mode 100644index 000000000..e1abc67f9--- /dev/null+++ b/api/subscriptions/subscribe.js@@ -0,0 +1,252 @@+/**+ * POST /api/subscriptions/subscribe+ *+ * First step of the user→agent subscription flow. Takes a tier (subscription_plans+ * row) + the buyer's wallet pubkey, quotes the exact USDC split, persists a+ * pending `subscription_checkouts` row, and returns a base64 VersionedTransaction+ * the browser wallet signs and sends. The platform pre-signs as fee-payer so the+ * subscriber needs no SOL — only the USDC for the first period.+ *+ * Fee split: (price − platform_fee) → creator, platform_fee → treasury, both in+ * one atomic transaction alongside the Solana-Pay reference key.+ *+ * Body: { tierId, buyerPublicKey }+ * Returns: { data: { transaction, reference, recipient, amount, creator_amount,+ * currency_mint, mint_decimals, gasless, label, message, fee?, tier } }+ *+ * Activation happens in /api/subscriptions/verify once the tx lands.+ */++import {+ Keypair, PublicKey,+ TransactionMessage, VersionedTransaction,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync,+ createTransferCheckedInstruction,+ getMint,+} from '@solana/spl-token';+import { z } from 'zod';++import { solanaConnection } from '../_lib/solana/connection.js';+import { sql } from '../_lib/db.js';+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { requireCsrf } from '../_lib/csrf.js';+import { resolveMarketplaceFee } from '../_lib/marketplace-platform-fee.js';+import { decodeSecretKey } from '../_lib/solana-signers.js';+import {+ USDC_MAINNET_MINT,+ usdToUsdcAtomics,+ resolveSubscriptionPayout,+} from '../_lib/subscription-checkout.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';++const bodySchema = z.object({+ tierId: z.string().uuid(),+ buyerPublicKey: z.string().regex(BASE58_RE, 'invalid public key'),+});++// Platform fee-payer keypair (gasless UX). Prefers MARKETPLACE_PAYER_KEYPAIR;+// falls back to the treasury. When none is configured the buyer pays gas.+let _payerKeypair = undefined; // undefined = unresolved, null = not configured+async function resolvePlatformPayer() {+ if (_payerKeypair !== undefined) return _payerKeypair;+ const secret =+ process.env.MARKETPLACE_PAYER_KEYPAIR ||+ process.env.PLATFORM_TREASURY_KEYPAIR ||+ process.env.TREASURY_KEYPAIR ||+ '';+ if (!secret) { _payerKeypair = null; return null; }+ const bytes = await decodeSecretKey(secret);+ if (!bytes) { _payerKeypair = null; return null; }+ try {+ _payerKeypair = Keypair.fromSecretKey(bytes);+ } catch {+ _payerKeypair = null;+ }+ return _payerKeypair;+}++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ // CSRF on cookie-session requests; bearer tokens are exempt (the token proves intent).+ if (!(await requireCsrf(req, res, auth.userId))) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const parsed = bodySchema.safeParse(await readJson(req).catch(() => null));+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');+ }+ const { tierId, buyerPublicKey } = parsed.data;++ const [plan] = await sql`+ SELECT id, creator_id, agent_id, name, price_usd, interval, active+ FROM subscription_plans WHERE id = ${tierId}+ `;+ if (!plan) return error(res, 404, 'not_found', 'subscription tier not found');+ if (!plan.active) return error(res, 409, 'conflict', 'this tier is no longer available');+ if (plan.creator_id === auth.userId) {+ return error(res, 409, 'conflict', 'you cannot subscribe to your own tier');+ }++ // Already actively subscribed? Don't let them pay twice.+ const [active] = await sql`+ SELECT id, current_period_end FROM creator_subscriptions+ WHERE plan_id = ${tierId} AND subscriber_user_id = ${auth.userId}+ AND status = 'active' AND current_period_end > now()+ `;+ if (active) {+ return error(res, 409, 'already_subscribed', 'you already have an active subscription to this tier', {+ current_period_end: active.current_period_end,+ });+ }++ const recipient = await resolveSubscriptionPayout(plan);+ if (!recipient) {+ return error(res, 412, 'creator_wallet_missing', 'this creator has not configured a payout wallet');+ }++ // Quote the split. USDC at parity with the USD price (6 decimals).+ const grossAtomics = usdToUsdcAtomics(plan.price_usd);+ const feeInfo = await resolveMarketplaceFee({ grossAtomics });+ const platformFeeAtomics = feeInfo ? feeInfo.feeAtomics : 0n;+ const creatorAtomics = grossAtomics - platformFeeAtomics;+ const currencyMint = USDC_MAINNET_MINT;++ // Reuse a fresh pending checkout (idempotent retry) or mint a new reference.+ const [pending] = await sql`+ SELECT reference, amount, creator_amount, platform_fee_amount, platform_fee_wallet,+ currency_mint, recipient+ FROM subscription_checkouts+ WHERE user_id = ${auth.userId} AND plan_id = ${tierId}+ AND status = 'pending' AND expires_at > now()+ ORDER BY created_at DESC+ LIMIT 1+ `;++ let checkout;+ if (pending) {+ checkout = pending;+ } else {+ const reference = Keypair.generate().publicKey.toBase58();+ try {+ [checkout] = await sql`+ INSERT INTO subscription_checkouts (+ reference, user_id, plan_id, agent_id, amount, creator_amount,+ platform_fee_amount, platform_fee_wallet, currency_mint, chain,+ recipient, buyer_public_key, interval, expires_at+ ) VALUES (+ ${reference}, ${auth.userId}, ${tierId}, ${plan.agent_id ?? null},+ ${grossAtomics.toString()}, ${creatorAtomics.toString()},+ ${platformFeeAtomics.toString()}, ${feeInfo ? feeInfo.recipient.toBase58() : null},+ ${currencyMint}, 'solana', ${recipient}, ${buyerPublicKey}, ${plan.interval},+ now() + interval '30 minutes'+ )+ RETURNING reference, amount, creator_amount, platform_fee_amount, platform_fee_wallet,+ currency_mint, recipient+ `;+ } catch (e) {+ // Lost a race for the (user, plan) pending slot — reuse the winner.+ if (e?.code === '23505') {+ [checkout] = await sql`+ SELECT reference, amount, creator_amount, platform_fee_amount, platform_fee_wallet,+ currency_mint, recipient+ FROM subscription_checkouts+ WHERE user_id = ${auth.userId} AND plan_id = ${tierId} AND status = 'pending'+ ORDER BY created_at DESC LIMIT 1+ `;+ } else {+ throw e;+ }+ }+ }+ if (!checkout) return error(res, 500, 'checkout_failed', 'could not create the subscription checkout');++ // Build the SPL transfer (creator leg + reference, fee leg) the buyer signs.+ const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });+ const { blockhash } = await connection.getLatestBlockhash('confirmed');+ const mintKey = new PublicKey(checkout.currency_mint);+ const mintInfo = await getMint(connection, mintKey);+ const decimals = mintInfo.decimals;++ const buyer = new PublicKey(buyerPublicKey);+ const fromAta = getAssociatedTokenAddressSync(mintKey, buyer);+ const creatorKey = new PublicKey(checkout.recipient);+ const toAta = getAssociatedTokenAddressSync(mintKey, creatorKey);++ const referenceKey = new PublicKey(checkout.reference);+ const creatorLeg = BigInt(checkout.creator_amount);+ const creatorIx = createTransferCheckedInstruction(fromAta, mintKey, toAta, buyer, creatorLeg, decimals);+ creatorIx.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });+ const instructions = [creatorIx];++ const feeLeg = BigInt(checkout.platform_fee_amount || 0);+ if (feeLeg > 0n && checkout.platform_fee_wallet) {+ const treasuryAta = getAssociatedTokenAddressSync(mintKey, new PublicKey(checkout.platform_fee_wallet));+ instructions.push(+ createTransferCheckedInstruction(fromAta, mintKey, treasuryAta, buyer, feeLeg, decimals),+ );+ }++ const platformPayer = await resolvePlatformPayer();+ const feePayer = platformPayer ? platformPayer.publicKey : buyer;++ const messageV0 = new TransactionMessage({+ payerKey: feePayer,+ recentBlockhash: blockhash,+ instructions,+ }).compileToV0Message();+ const tx = new VersionedTransaction(messageV0);+ if (platformPayer) tx.sign([platformPayer]);++ const serialized = Buffer.from(tx.serialize()).toString('base64');+ const cycle = plan.interval === 'weekly' ? 'week' : 'month';+ // Derive the fee block from the PERSISTED checkout (the source of truth for the+ // tx the buyer signs), so a reused pending checkout reports its own split even+ // if the fee config changed since it was minted.+ const feeBlock = feeLeg > 0n && checkout.platform_fee_wallet+ ? {+ fee: {+ recipient: checkout.platform_fee_wallet,+ amount: feeLeg.toString(),+ bps: Number((feeLeg * 10000n) / BigInt(checkout.amount)),+ },+ }+ : {};++ return json(res, 200, {+ data: {+ transaction: serialized,+ reference: checkout.reference,+ recipient: checkout.recipient,+ amount: String(checkout.amount),+ creator_amount: String(checkout.creator_amount),+ currency_mint: checkout.currency_mint,+ mint_decimals: decimals,+ gasless: !!platformPayer,+ label: `Subscribe: ${plan.name.slice(0, 40)}`,+ message: `Subscribe to '${plan.name}' (${cycle}ly)`,+ tier: { id: plan.id, name: plan.name, price_usd: Number(plan.price_usd), interval: plan.interval },+ ...feeBlock,+ },+ });+});diff --git a/api/subscriptions/verify.js b/api/subscriptions/verify.jsnew file mode 100644index 000000000..9755249d0--- /dev/null+++ b/api/subscriptions/verify.js@@ -0,0 +1,123 @@+/**+ * POST /api/subscriptions/verify+ *+ * Second step of the user→agent subscription flow. The buyer broadcasts the+ * transaction returned by /api/subscriptions/subscribe and hands the signature+ * back here. We locate the pending `subscription_checkouts` row, validate the+ * on-chain transfer against the PERSISTED quote (never the client's numbers),+ * and — on success — activate the subscription: creator_subscriptions (active),+ * subscription_payments (first period), and the user_agent_subscriptions access+ * gate.+ *+ * Body: { transactionSignature?, tierId }+ * transactionSignature is preferred; if omitted we scan the chain by reference.+ * Returns: { data: { success, status, subscription, current_period_end } }+ * | { data: { status: 'pending' } } while the tx isn't visible yet.+ */++import { z } from 'zod';++import { sql } from '../_lib/db.js';+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { requireCsrf } from '../_lib/csrf.js';+import { verifySubscriptionPayment, activateSubscription } from '../_lib/subscription-checkout.js';++const SIG_RE = /^[1-9A-HJ-NP-Za-km-z]{32,100}$/; // base58 signature++const bodySchema = z.object({+ tierId: z.string().uuid(),+ transactionSignature: z.string().regex(SIG_RE, 'invalid signature').optional(),+});++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ if (!(await requireCsrf(req, res, auth.userId))) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const parsed = bodySchema.safeParse(await readJson(req).catch(() => null));+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');+ }+ const { tierId, transactionSignature } = parsed.data;++ const [checkout] = await sql`+ SELECT id, reference, user_id, plan_id, agent_id, status, amount, creator_amount,+ platform_fee_amount, platform_fee_wallet, currency_mint, chain, recipient,+ buyer_public_key, interval, expires_at, tx_signature, confirmed_at+ FROM subscription_checkouts+ WHERE user_id = ${auth.userId} AND plan_id = ${tierId}+ ORDER BY (status = 'pending') DESC, created_at DESC+ LIMIT 1+ `;+ if (!checkout) {+ return error(res, 404, 'no_pending_checkout', 'start a subscription before verifying it');+ }++ // Idempotent success: an already-confirmed checkout returns the live subscription.+ if (checkout.status === 'confirmed') {+ const [sub] = await sql`+ SELECT id, plan_id, status, current_period_start, current_period_end+ FROM creator_subscriptions+ WHERE plan_id = ${tierId} AND subscriber_user_id = ${auth.userId}+ `;+ return json(res, 200, {+ data: {+ success: true,+ status: sub?.status || 'active',+ subscription: sub || null,+ current_period_end: sub?.current_period_end || null,+ tx_signature: checkout.tx_signature,+ },+ });+ }++ if (checkout.status !== 'pending') {+ return error(res, 409, 'checkout_closed', `this checkout is ${checkout.status}`);+ }+ if (checkout.expires_at && new Date(checkout.expires_at) < new Date()) {+ await sql`UPDATE subscription_checkouts SET status = 'expired' WHERE id = ${checkout.id} AND status = 'pending'`;+ return error(res, 410, 'checkout_expired', 'this checkout expired — start a new subscription');+ }++ const result = await verifySubscriptionPayment(checkout, transactionSignature || null);++ if (result.status === 'pending') {+ return json(res, 200, { data: { status: 'pending' } });+ }+ if (result.status === 'mismatch') {+ // Funds may have moved but not as quoted — surface it, leave the checkout+ // pending so a corrected retry (or the by-reference scan) can still settle.+ return error(res, 409, 'transfer_mismatch', result.message || 'on-chain transfer did not match the quoted amount', {+ tx_signature: result.tx_signature,+ });+ }++ const activation = await activateSubscription(checkout, result.tx_signature, checkout.buyer_public_key);++ return json(res, 200, {+ data: {+ success: true,+ status: 'active',+ subscription: activation.subscription,+ current_period_end: activation.current_period_end || activation.subscription?.current_period_end || null,+ tx_signature: result.tx_signature,+ },+ });+});diff --git a/api/users/earnings.js b/api/users/earnings.jsindex 8eba2f5be..d7edd5e1d 100644--- a/api/users/earnings.js+++ b/api/users/earnings.js@@ -1,7 +1,7 @@-import { sql } from '../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';+import { MonetizationService } from '../_lib/services/MonetizationService.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -15,89 +15,8 @@ export default wrap(async (req, res) => {const rl = await limits.authIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const rows = await sql`- SELECT- rl.id,- rl.price_usd,- rl.status,- rl.created_at,- ms.name AS skill_name,- ai.name AS agent_name- FROM royalty_ledger rl- JOIN marketplace_skills ms ON ms.id = rl.skill_id- JOIN agent_identities ai ON ai.id = rl.agent_id- WHERE rl.author_user_id = ${userId}- ORDER BY rl.created_at DESC- LIMIT 100- `;+ const service = new MonetizationService(userId);+ const { pending_usd, settled_usd, entries } = await service.getCreatorSalesData();- // Asset sales (avatars / agents / plugins). asset_purchases stores amount- // in atomic USDC units (6 decimals on Solana mainnet) — divide to get- // price_usd for consistent reporting alongside the royalty ledger.- let assetRows = [];- try {- assetRows = await sql`- SELECT- ap.id,- ap.item_type,- ap.item_id,- ap.amount,- ap.currency_mint,- ap.confirmed_at,- ap.created_at,- ap.status,- CASE ap.item_type- WHEN 'avatar' THEN (SELECT name FROM avatars WHERE id = ap.item_id)- WHEN 'agent' THEN (SELECT name FROM agent_identities WHERE id = ap.item_id)- ELSE NULL- END AS item_name- FROM asset_purchases ap- WHERE ap.seller_user_id = ${userId}- AND ap.status = 'confirmed'- ORDER BY ap.confirmed_at DESC NULLS LAST- LIMIT 100- `;- } catch {- // asset_purchases migration hasn't run yet — leave list empty.- }-- const pending_usd = rows- .filter((r) => r.status === 'pending')- .reduce((s, r) => s + Number(r.price_usd), 0);-- const settled_usd = rows- .filter((r) => r.status === 'settled')- .reduce((s, r) => s + Number(r.price_usd), 0);-- const asset_settled_usd = assetRows.reduce(- (s, r) => s + Number(r.amount) / 1_000_000,- 0,- );-- const entries = rows.map((r) => ({- skill_name: r.skill_name,- agent_name: r.agent_name,- price_usd: Number(r.price_usd),- status: r.status,- created_at: r.created_at,- kind: 'skill',- }));- for (const r of assetRows) {- entries.push({- skill_name: `${r.item_type[0].toUpperCase()}${r.item_type.slice(1)} sale`,- agent_name: r.item_name || '(deleted)',- price_usd: Number(r.amount) / 1_000_000,- status: 'settled',- created_at: r.confirmed_at || r.created_at,- kind: r.item_type,- });- }- // Newest first, regardless of source.- entries.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));-- return json(res, 200, {- pending_usd,- settled_usd: settled_usd + asset_settled_usd,- entries,- });+ return json(res, 200, { pending_usd, settled_usd, entries });});diff --git a/api/users/lookup.js b/api/users/lookup.jsnew file mode 100644index 000000000..fea5fab77--- /dev/null+++ b/api/users/lookup.js@@ -0,0 +1,45 @@+// GET /api/users/lookup?q=<username | wallet | user id>+//+// Resolves a public identifier to a minimal public profile, so the gift flow can+// confirm "you're sending this to <name>" before the buyer pays. Auth-gated to+// keep it from becoming an anonymous scraping/enumeration surface; returns only+// public fields (id, username, display name, avatar) and never the email.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { resolveRecipient } from '../_lib/resolve-recipient.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ const callerId = session?.id ?? bearer.userId;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const q = new URL(req.url, 'http://x').searchParams.get('q');+ if (!q || !q.trim()) return error(res, 400, 'validation_error', 'q is required');++ const user = await resolveRecipient(q);+ if (!user) return error(res, 404, 'not_found', 'no user matches that username or wallet');++ return json(+ res,+ 200,+ {+ data: {+ id: user.id,+ username: user.username,+ display_name: user.display_name,+ avatar_url: user.avatar_url,+ is_self: user.id === callerId,+ },+ },+ { 'cache-control': 'no-store' },+ );+});diff --git a/api/x402/forge.js b/api/x402/forge.jsindex ad9444e83..f6b18f256 100644--- a/api/x402/forge.js+++ b/api/x402/forge.js@@ -68,6 +68,7 @@ import {priceAtomicsForTier,priceUsdcForTier,estimateEtaSeconds,+ preferFreeReconstruct,buildCatalog,} from '../_lib/forge-tiers.js';@@ -216,11 +217,98 @@ async function submitGeneration({ prompt, imageUrls, isImageMode, aspect, tier }const viaNvidia = await submitTextViaNvidia({ prompt, tier });if (viaNvidia) return viaNvidia;// NIM unconfigured / unreachable / over capacity — fall through to the- // FLUX→TRELLIS reconstruct lane so the paid call still produces a model.+ // reconstruct lanes so the paid call still produces a model.+ }+ // Free-first: prefer the free HuggingFace Spaces reconstruct lane BEFORE the+ // paid Replicate default, so a paid call never spends on — or dead-ends against+ // — the paid account while a free lane can serve it. Reversible via+ // FORGE_PREFER_FREE=false. Returns null when the lane is unavailable (no+ // HF_TOKEN) or it fails, so the call falls through to the Replicate reconstruct.+ if (preferFreeReconstruct()) {+ const viaHf = await submitViaHuggingFace({ prompt, imageUrls, isImageMode, aspect, tier });+ if (viaHf) return viaHf;}return submitViaReconstruct({ prompt, imageUrls, isImageMode, aspect, tier });}+// Free HuggingFace Spaces reconstruct lane — the free-first alternative to the+// paid Replicate reconstruct. Text→3D synthesizes a reference view first (free+// NVIDIA FLUX where configured); image→3D reconstructs the caller's views+// directly. HF blocks until the GLB is ready, so completion is synchronous — we+// persist the result to R2 (the Space file URL is ephemeral) and hand back a+// durable url with status:"done". Returns null when the lane is unavailable / it+// fails, so submitGeneration falls through to Replicate. Never throws: a free-lane+// hiccup must degrade, not fail the whole paid call.+async function submitViaHuggingFace({ prompt, imageUrls, isImageMode, aspect, tier }) {+ let provider;+ try {+ const mod = await import('../_providers/huggingface.js');+ provider = mod.createRegenProvider();+ } catch (err) {+ console.warn(`[x402/forge] free HuggingFace lane unavailable: ${err?.message || err}`);+ return null;+ }++ try {+ let referenceImageUrl;+ let views;+ if (isImageMode) {+ // Caller-supplied views are fetched by the upstream Space — SSRF-guard+ // them before forwarding, same as the reconstruct lane.+ for (const u of imageUrls) await assertSafePublicUrl(u);+ views = imageUrls;+ referenceImageUrl = imageUrls[0];+ } else {+ const synthesized = await textToImage(prompt, { aspectRatio: aspect });+ referenceImageUrl = synthesized.imageUrl;+ views = [referenceImageUrl];+ }++ const submitted = await provider.submit({+ mode: 'reconstruct',+ sourceUrl: referenceImageUrl,+ params: { images: views, prompt: prompt || undefined },+ });+ const finished = await provider.status(submitted.extJobId);+ const glbUrl = finished?.resultGlbUrl;+ if (!glbUrl) throw new Error('HuggingFace returned no GLB');++ const backend = 'huggingface';+ return {+ job_id: null,+ status: 'done',+ poll_url: null,+ glb_url: (await persistRemoteGlb(glbUrl)) || glbUrl,+ mode: isImageMode ? 'image_to_3d' : 'text_to_3d',+ tier: resolveTier(tier).id,+ backend,+ eta_seconds: estimateEtaSeconds({ backendId: BACKEND, tier }),+ price_usdc: priceUsdcForTier(tier),+ };+ } catch (err) {+ console.warn(`[x402/forge] free HuggingFace lane failed: ${err?.message || err}`);+ return null;+ }+}++// Copy a generated GLB into R2 so the buyer's url survives the Space's ephemeral+// file storage; fail-soft (returns null) so the caller can hand back the raw HF+// url rather than fail a delivered generation over a copy hiccup.+async function persistRemoteGlb(url) {+ try {+ const res = await fetch(url, { signal: AbortSignal.timeout(60_000) });+ if (!res.ok) return null;+ const buf = Buffer.from(await res.arrayBuffer());+ if (!buf.length) return null;+ const { putObject, publicUrl } = await import('../_lib/r2.js');+ const key = `forge/huggingface/${globalThis.crypto.randomUUID()}.glb`;+ await putObject({ key, body: buf, contentType: 'model/gltf-binary' });+ return publicUrl(key);+ } catch {+ return null;+ }+}+// Free NVIDIA NIM native text→3D. Returns the finished/queued response shape, or// null when the lane is unavailable so submitGeneration can fall back. Never// throws: a free-lane hiccup must degrade, not fail the whole paid call.@@ -350,9 +438,34 @@ function respondGenerationError(res, err) {{ retry_after: retryAfter },);}+ // The only reconstruct lane left was the platform's PAID vendor account and it+ // is out of credit. The vendor's raw "buy credit" message is our internal+ // billing state — never relay it to the buyer. Submit runs before settle, so+ // the payment was not taken; say so and answer with an honest unavailable state.+ if (isPaidCreditFailure(err)) {+ console.warn(`[x402/forge] paid reconstruct lane out of credit, no free lane: ${err?.message || err}`);+ res.setHeader('retry-after', '30');+ return error(+ res,+ 503,+ 'generation_unavailable',+ 'Free 3D generation is temporarily unavailable and your payment was not taken — please retry shortly.',+ { retry_after: 30 },+ );+ }return error(res, err?.status || 502, err?.code || 'generation_failed', err?.message);}+// A leaked paid-account billing/credit message from the platform's own vendor+// (e.g. Replicate "insufficient credit to run this model… purchase credit") is+// internal infra state, never shown to the buyer. The x402 forge lane is always+// platform-keyed (no BYOK), so any credit failure here is ours to absorb.+function isPaidCreditFailure(err) {+ if (err?.providerStatus === 402) return true;+ const text = `${err?.message || ''} ${err?.providerDetail || ''}`.toLowerCase();+ return /insufficient credit|purchase credit|account\/billing|out of credit|not enough credit/.test(text);+}+// GET — free price/usage discovery. No payment, no generation.function handleGet(req, res) {const url = new URL(req.url, 'http://localhost');diff --git a/contracts/idl/skill_license.json b/contracts/idl/skill_license.jsonnew file mode 100644index 000000000..bc1bcba9d--- /dev/null+++ b/contracts/idl/skill_license.json@@ -0,0 +1,210 @@+{+ "address": "EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8",+ "metadata": {+ "name": "skill_license",+ "version": "0.1.0",+ "spec": "0.1.0",+ "description": "On-chain skill-ownership licenses (1/1 NFT access keys) on Solana."+ },+ "instructions": [+ {+ "name": "initialize_marketplace",+ "discriminator": [47, 81, 64, 0, 96, 56, 105, 7],+ "accounts": [+ {+ "name": "marketplace",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "const", "value": [109, 97, 114, 107, 101, 116, 112, 108, 97, 99, 101] }+ ]+ }+ },+ { "name": "authority", "writable": true, "signer": true },+ { "name": "system_program", "address": "11111111111111111111111111111111" }+ ],+ "args": [{ "name": "minter", "type": "pubkey" }]+ },+ {+ "name": "set_minter",+ "discriminator": [13, 170, 92, 172, 137, 194, 39, 2],+ "accounts": [+ {+ "name": "marketplace",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "const", "value": [109, 97, 114, 107, 101, 116, 112, 108, 97, 99, 101] }+ ]+ }+ },+ { "name": "authority", "signer": true }+ ],+ "args": [{ "name": "new_minter", "type": "pubkey" }]+ },+ {+ "name": "mint_skill_license",+ "discriminator": [179, 127, 15, 8, 180, 22, 10, 122],+ "docs": [+ "skill_license, nft_mint, and owner_token_account are PDAs/ATAs derived from",+ "(owner, agent_mint, sha256(skill_name)); the client derives and passes them."+ ],+ "accounts": [+ {+ "name": "marketplace",+ "writable": true,+ "pda": {+ "seeds": [+ { "kind": "const", "value": [109, 97, 114, 107, 101, 116, 112, 108, 97, 99, 101] }+ ]+ }+ },+ { "name": "minter", "writable": true, "signer": true },+ { "name": "owner" },+ { "name": "agent_mint" },+ { "name": "skill_license", "writable": true },+ { "name": "nft_mint", "writable": true },+ { "name": "owner_token_account", "writable": true },+ { "name": "token_program", "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" },+ {+ "name": "associated_token_program",+ "address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"+ },+ { "name": "system_program", "address": "11111111111111111111111111111111" },+ { "name": "rent", "address": "SysvarRent111111111111111111111111111111111" }+ ],+ "args": [{ "name": "skill_name", "type": "string" }]+ },+ {+ "name": "burn_skill_license",+ "discriminator": [208, 75, 132, 30, 218, 53, 153, 225],+ "accounts": [+ { "name": "skill_license", "writable": true },+ { "name": "authority", "writable": true, "signer": true },+ { "name": "nft_mint", "writable": true },+ { "name": "owner_token_account", "writable": true },+ { "name": "token_program", "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" }+ ],+ "args": []+ },+ {+ "name": "revoke_skill_license",+ "discriminator": [126, 201, 251, 1, 207, 219, 170, 31],+ "accounts": [+ {+ "name": "marketplace",+ "pda": {+ "seeds": [+ { "kind": "const", "value": [109, 97, 114, 107, 101, 116, 112, 108, 97, 99, 101] }+ ]+ }+ },+ { "name": "minter", "signer": true },+ { "name": "owner" },+ { "name": "skill_license", "writable": true },+ { "name": "nft_mint", "writable": true },+ { "name": "owner_token_account", "writable": true },+ { "name": "token_program", "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" }+ ],+ "args": []+ }+ ],+ "accounts": [+ { "name": "Marketplace", "discriminator": [70, 222, 41, 62, 78, 3, 32, 174] },+ { "name": "SkillLicense", "discriminator": [212, 242, 220, 5, 112, 253, 200, 97] }+ ],+ "events": [+ { "name": "SkillLicenseMinted", "discriminator": [139, 57, 198, 225, 48, 35, 207, 177] },+ { "name": "SkillLicenseBurned", "discriminator": [91, 36, 61, 129, 31, 152, 96, 100] },+ { "name": "SkillLicenseRevoked", "discriminator": [24, 244, 206, 252, 213, 29, 50, 23] }+ ],+ "errors": [+ { "code": 6000, "name": "EmptySkillName", "msg": "skill_name must not be empty" },+ { "code": 6001, "name": "SkillNameTooLong", "msg": "skill_name exceeds the maximum allowed length" },+ {+ "code": 6002,+ "name": "UnauthorizedAdmin",+ "msg": "only the marketplace admin authority may perform this action"+ },+ {+ "code": 6003,+ "name": "UnauthorizedMinter",+ "msg": "only the authorized minter may mint or revoke licenses"+ },+ { "code": 6004, "name": "NotLicenseOwner", "msg": "signer is not the owner of this license" },+ {+ "code": 6005,+ "name": "MintMismatch",+ "msg": "nft_mint does not match the one recorded on the license"+ },+ { "code": 6006, "name": "AlreadyRevoked", "msg": "license is already revoked" },+ { "code": 6007, "name": "Overflow", "msg": "arithmetic overflow" }+ ],+ "types": [+ {+ "name": "Marketplace",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "authority", "type": "pubkey" },+ { "name": "minter", "type": "pubkey" },+ { "name": "licenses_minted", "type": "u64" },+ { "name": "bump", "type": "u8" }+ ]+ }+ },+ {+ "name": "SkillLicense",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "authority", "type": "pubkey" },+ { "name": "agent_mint", "type": "pubkey" },+ { "name": "nft_mint", "type": "pubkey" },+ { "name": "skill_hash", "type": { "array": ["u8", 32] } },+ { "name": "purchase_date", "type": "i64" },+ { "name": "revoked_at", "type": "i64" },+ { "name": "bump", "type": "u8" },+ { "name": "skill_name", "type": "string" }+ ]+ }+ },+ {+ "name": "SkillLicenseMinted",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "license", "type": "pubkey" },+ { "name": "owner", "type": "pubkey" },+ { "name": "agent_mint", "type": "pubkey" },+ { "name": "nft_mint", "type": "pubkey" },+ { "name": "skill_name", "type": "string" },+ { "name": "purchase_date", "type": "i64" }+ ]+ }+ },+ {+ "name": "SkillLicenseBurned",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "license", "type": "pubkey" },+ { "name": "owner", "type": "pubkey" },+ { "name": "nft_mint", "type": "pubkey" }+ ]+ }+ },+ {+ "name": "SkillLicenseRevoked",+ "type": {+ "kind": "struct",+ "fields": [+ { "name": "license", "type": "pubkey" },+ { "name": "owner", "type": "pubkey" },+ { "name": "nft_mint", "type": "pubkey" },+ { "name": "revoked_at", "type": "i64" }+ ]+ }+ }+ ]+}diff --git a/contracts/skill-license/.gitignore b/contracts/skill-license/.gitignorenew file mode 100644index 000000000..6d06502f0--- /dev/null+++ b/contracts/skill-license/.gitignore@@ -0,0 +1,12 @@+# Build output+/target+.anchor+test-ledger++# Local deploy keypairs / authority secrets. The program + deploy-authority+# keypairs live in ~/.config/solana and a secret manager — see DEPLOYMENT.md.+/.deploy+*-keypair.json+*program*.json+*deployer*.json+*authority*.jsondiff --git a/contracts/skill-license/Anchor.toml b/contracts/skill-license/Anchor.tomlnew file mode 100644index 000000000..4550e4602--- /dev/null+++ b/contracts/skill-license/Anchor.toml@@ -0,0 +1,30 @@+[toolchain]++[features]+resolver = "2"++# Same program id on every cluster — it is the program keypair's pubkey, baked+# into `declare_id!`. See DEPLOYMENT.md for deploy signatures + upgrade authority.+[programs.localnet]+skill_license = "EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8"++[programs.devnet]+skill_license = "EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8"++[programs.mainnet]+skill_license = "EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8"++[registry]+url = "https://api.apr.dev"++[provider]+cluster = "devnet"+# Deploy/upgrade authority keypair — kept OUT of the repo (~/.config/solana,+# mirrored to the secret manager as SKILL_LICENSE_DEPLOY_AUTHORITY).+wallet = "~/.config/solana/skill-license-deployer.json"++[workspace]+members = ["."]++[scripts]+smoke = "node ../../scripts/skill-license-smoke.mjs"diff --git a/contracts/skill-license/Cargo.toml b/contracts/skill-license/Cargo.tomlnew file mode 100644index 000000000..ec264bbf5--- /dev/null+++ b/contracts/skill-license/Cargo.toml@@ -0,0 +1,37 @@+# Self-contained workspace so `cargo build-sbf` / `anchor build` here never walks+# up into an unrelated parent workspace.+[workspace]++[package]+name = "skill-license"+version = "0.1.0"+description = "On-chain skill-ownership licenses (1/1 NFT access keys) on Solana."+edition = "2021"+license = "Apache-2.0"+repository = "https://github.com/nirholas/three.ws"++[lib]+crate-type = ["cdylib", "lib"]+name = "skill_license"++[features]+default = []+cpi = ["no-entrypoint"]+no-entrypoint = []+no-idl = []+no-log-ix-name = []+idl-build = ["anchor-lang/idl-build", "anchor-spl/idl-build"]++[dependencies]+anchor-lang = "0.31.1"+anchor-spl = "0.31.1"++[profile.release]+overflow-checks = true+lto = "fat"+codegen-units = 1++[profile.release.build-override]+opt-level = 3+incremental = false+codegen-units = 1diff --git a/contracts/skill-license/DEPLOYMENT.md b/contracts/skill-license/DEPLOYMENT.mdnew file mode 100644index 000000000..b93aea413--- /dev/null+++ b/contracts/skill-license/DEPLOYMENT.md@@ -0,0 +1,90 @@+# Deploying `skill_license`++The program id is the program keypair's pubkey, baked into `declare_id!` and+`Anchor.toml`: **`EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8`**. The same id is+used on localnet, devnet, and mainnet.++## Keys (never commit)++| Key | Purpose | Storage |+|---|---|---|+| Program keypair | Its pubkey is the program id; signs the initial deploy. | `contracts/skill-license/.deploy/skill_license-keypair.json` (gitignored) → secret manager as `SKILL_LICENSE_PROGRAM_KEYPAIR`. |+| Deploy/upgrade authority | Pays for + upgrades the program. | `~/.config/solana/skill-license-deployer.json` → `SKILL_LICENSE_DEPLOY_AUTHORITY`. |+| Minter | The backend wallet authorized to call `mint_skill_license` / `revoke_skill_license`. | `SKILL_LICENSE_MINTER_KEY` (base58 secret) in the server secret manager — never on the client. |++The program keypair generated for this id already lives at the gitignored+`.deploy/` path. If you need to regenerate (new id), update `declare_id!`,+`Anchor.toml`, `contracts/idl/skill_license.json`, and the default in+`api/_lib/skill-license-onchain.js`.++## 1. Build++```bash+cd contracts/skill-license+anchor build # → target/deploy/skill_license.so + refreshed IDL+```++`anchor build` regenerates the IDL from `src/lib.rs`. Diff it against+`../idl/skill_license.json` and reconcile any drift (the JSON is the version the+backend + smoke test consume).++## 2. Deploy++```bash+# point the program keypair into place first+cp .deploy/skill_license-keypair.json target/deploy/skill_license-keypair.json++anchor deploy \+ --provider.cluster devnet \+ --provider.wallet ~/.config/solana/skill-license-deployer.json \+ --program-keypair target/deploy/skill_license-keypair.json+```++Repeat with `--provider.cluster mainnet` for production.++## 3. Initialize the marketplace (one-time)++The singleton `Marketplace` config must exist before any license can be minted.+Set `SKILL_LICENSE_MINTER_KEY` to the backend minter wallet and run:++```bash+SKILL_LICENSE_MINTER_KEY=<base58-secret> \+SOLANA_RPC_URL_DEVNET=https://api.devnet.solana.com \+node scripts/skill-license-smoke.mjs+```++On first run the smoke test initializes the marketplace (admin = minter), mints+a license to a fresh synthetic owner, verifies the on-chain record, and asserts+the buyer holds exactly 1 NFT. It is re-runnable and exits non-zero on failure.++To initialize with a **separate** admin authority (recommended for production —+so the minter key can be rotated by a cold admin key), call+`buildInitializeMarketplaceIx({ authority, minter })` from+`api/_lib/skill-license-onchain.js` with distinct keys and submit it signed by+the admin.++## 4. Wire the backend++Set on the server (Vercel):++| Env | Value |+|---|---|+| `SKILL_LICENSE_PROGRAM_ID` | the deployed program id (optional; defaults to the baked id) |+| `SKILL_LICENSE_MINTER_KEY` | base58 secret of the authorized minter |+| `SOLANA_RPC_URL` / `SOLANA_RPC_URL_DEVNET` | RPC endpoints (already configured) |++Verification (`GET /api/skills/license-onchain`) needs only the RPC + program id.+Minting (`mintSkillLicenseOnchain`) also needs `SKILL_LICENSE_MINTER_KEY`. If the+minter key is absent, verification still works and minting is simply disabled —+no crash.++## Upgrade authority++Keep the upgrade authority on a hardware/cold key in production. Transfer it+after the first deploy:++```bash+solana program set-upgrade-authority \+ EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8 \+ --new-upgrade-authority <COLD_AUTHORITY_PUBKEY>+```diff --git a/contracts/skill-license/README.md b/contracts/skill-license/README.mdnew file mode 100644index 000000000..cbf6b57f7--- /dev/null+++ b/contracts/skill-license/README.md@@ -0,0 +1,77 @@+# skill_license — on-chain skill-ownership NFTs (Solana / Anchor)++Purchasing a skill on three.ws can mint the buyer an **on-chain access key**: a+1-of-1 SPL NFT held in their wallet, plus a deterministic `SkillLicense` account+that anyone can read to verify ownership **without trusting our database**.++```+buy skill ──▶ backend verifies payment ──▶ mint_skill_license (minter-signed)+ │+ ├─ SkillLicense PDA (the queryable record)+ └─ 1/1 SPL NFT ────▶ buyer's wallet+```++This is the trustless alternative to the database-backed+[`hasSkillAccess`](../../api/_lib/skill-access.js) check: a license PDA that+exists with `revoked_at == 0` means the wallet owns the skill. The platform's+read path is [`api/skills/license-onchain.js`](../../api/skills/license-onchain.js),+backed by [`api/_lib/skill-license-onchain.js`](../../api/_lib/skill-license-onchain.js).++Program id (same on every cluster): **`EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8`**++## State++| Account | Seeds | Holds |+|---|---|---|+| `Marketplace` | `["marketplace"]` (singleton) | `authority` (admin), `minter` (authorized minting wallet), `licenses_minted`, `bump` |+| `SkillLicense` | `["skill_license", owner, agent_mint, sha256(skill_name)]` | `authority` (owner), `agent_mint`, `nft_mint`, `skill_hash`, `purchase_date`, `revoked_at`, `bump`, `skill_name` |+| NFT mint (PDA) | `["skill_mint", owner, agent_mint, sha256(skill_name)]` | the 1/1 mint (0 decimals, supply locked at 1) |++`skill_name` can be up to 64 bytes — longer than Solana's 32-byte per-seed+limit — so it is hashed with SHA-256 to form the third seed. The JS client+([`skillSeed`](../../api/_lib/skill-license-onchain.js)) computes the identical+hash, so both sides derive the same license/mint/ATA addresses.++## Instructions++| Instruction | Signer | Effect |+|---|---|---|+| `initialize_marketplace(minter)` | admin | Create the singleton config. Signer becomes `authority`; `minter` is the wallet allowed to mint. One-time. |+| `set_minter(new_minter)` | admin | Rotate the authorized minter (key rotation). |+| `mint_skill_license(skill_name)` | `minter` | Create the `SkillLicense` PDA, mint 1 NFT to the owner's ATA, then remove the mint authority so supply is permanently 1. Owner does **not** sign — the backend mints on their behalf after payment is verified, so a user can't self-mint a free license. |+| `burn_skill_license()` | owner | Burn the NFT, close the token account, and close the license PDA — all rent back to the owner. For holder-initiated disposal / pre-transfer teardown. |+| `revoke_skill_license()` | `minter` | Refund path: freeze the holder's token account (via the freeze authority retained at mint) and stamp `revoked_at`. The PDA stays readable so verifiers see the revoked state. |++The `mint`/`license`/`ata` accounts are all PDAs derived from the same triple,+so a second mint for the same `(owner, agent_mint, skill_name)` fails — the+purchase is idempotent on-chain.++## Why both a PDA and an NFT?++- The **NFT** is what shows up in the user's wallet and is transferable — *true+ ownership* of the skill license.+- The **`SkillLicense` PDA** is the cheap, deterministic, strongly-typed record+ the platform reads to answer "does this wallet own skill X on agent Y?" in a+ single `getAccountInfo`, with no token-account enumeration.++## Build, test, deploy++See [DEPLOYMENT.md](./DEPLOYMENT.md). In short:++```bash+anchor build # compile + regenerate the IDL+anchor deploy --provider.cluster devnet # deploy (program keypair = declare_id)+node scripts/skill-license-smoke.mjs # end-to-end devnet smoke test+```++The hand-maintained IDL lives at [`../idl/skill_license.json`](../idl/skill_license.json)+(kept in sync with `src/lib.rs`, mirroring the `agent_invocation` convention).++## Relationship to the Metaplex Core skill collections++The existing [`api/_lib/skill-nft.js`](../../api/_lib/skill-nft.js) pipeline mints+a Metaplex **Core** asset into a per-agent collection as the purchase receipt.+This program is the **program-owned** alternative: a custom on-chain access key+the platform controls end-to-end (mint, lock, revoke) and verifies by PDA. The+`agent_mint` seed is the agent's on-chain grouping mint (its skill-collection+mint), so a license cleanly ties back to the agent that sold the skill.diff --git a/contracts/skill-license/Xargo.toml b/contracts/skill-license/Xargo.tomlnew file mode 100644index 000000000..1ce1cf9e6--- /dev/null+++ b/contracts/skill-license/Xargo.toml@@ -0,0 +1,2 @@+[target.sbf-solana-solana.dependencies.std]+features = []diff --git a/contracts/skill-license/src/lib.rs b/contracts/skill-license/src/lib.rsnew file mode 100644index 000000000..054e371b8--- /dev/null+++ b/contracts/skill-license/src/lib.rs@@ -0,0 +1,464 @@+use anchor_lang::prelude::*;+use anchor_lang::solana_program::hash::hash as sha256;+use anchor_spl::associated_token::AssociatedToken;+use anchor_spl::token::spl_token::instruction::AuthorityType;+use anchor_spl::token::{+ self, Burn, CloseAccount, FreezeAccount, Mint, MintTo, SetAuthority, Token, TokenAccount,+};++declare_id!("EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8");++/// Max accepted length (bytes) for `skill_name`. Bounds the `SkillLicense`+/// account size and the work spent hashing/recording the name.+const MAX_SKILL_NAME_LEN: usize = 64;++/// PDA seed for the singleton marketplace config.+const MARKETPLACE_SEED: &[u8] = b"marketplace";+/// PDA seed prefix for a per-(owner, agent, skill) license record.+const SKILL_LICENSE_SEED: &[u8] = b"skill_license";+/// PDA seed prefix for the 1/1 NFT mint that backs a license.+const SKILL_MINT_SEED: &[u8] = b"skill_mint";++/// SHA-256 of a skill name, used as the third PDA seed. A raw skill name can be+/// up to 64 bytes — longer than the 32-byte per-seed limit — so we hash it to a+/// fixed 32 bytes. Matches `crypto.createHash('sha256')` on the client, so both+/// sides derive the identical license/mint PDAs.+fn skill_seed(skill_name: &str) -> [u8; 32] {+ sha256(skill_name.as_bytes()).to_bytes()+}++#[program]+pub mod skill_license {+ use super::*;++ /// Create the singleton marketplace config. The signer becomes the admin+ /// `authority` (can rotate the minter); `minter` is the backend wallet+ /// authorized to mint licenses after a payment is verified off-chain.+ pub fn initialize_marketplace(ctx: Context<InitializeMarketplace>, minter: Pubkey) -> Result<()> {+ let marketplace = &mut ctx.accounts.marketplace;+ marketplace.authority = ctx.accounts.authority.key();+ marketplace.minter = minter;+ marketplace.licenses_minted = 0;+ marketplace.bump = ctx.bumps.marketplace;+ msg!("marketplace initialized; minter {}", minter);+ Ok(())+ }++ /// Rotate the authorized minter. Admin-only — used for key rotation if the+ /// backend minter wallet is ever compromised or replaced.+ pub fn set_minter(ctx: Context<SetMinter>, new_minter: Pubkey) -> Result<()> {+ ctx.accounts.marketplace.minter = new_minter;+ msg!("minter rotated to {}", new_minter);+ Ok(())+ }++ /// Mint a skill license to `owner`: create the canonical [`SkillLicense`]+ /// PDA and a real 1-of-1 SPL NFT held by the owner's associated token+ /// account, then permanently lock supply at 1. Backend-signed (`minter`),+ /// so a user cannot self-mint a free license — the on-chain access key only+ /// exists once payment has been verified.+ ///+ /// Deterministic: the license PDA, the NFT mint PDA, and the owner's ATA are+ /// all derived from `(owner, agent_mint, sha256(skill_name))`, so the same+ /// purchase can never mint two licenses (the second `init` fails).+ pub fn mint_skill_license(ctx: Context<MintSkillLicense>, skill_name: String) -> Result<()> {+ require!(!skill_name.is_empty(), SkillLicenseError::EmptySkillName);+ require!(+ skill_name.len() <= MAX_SKILL_NAME_LEN,+ SkillLicenseError::SkillNameTooLong+ );++ let marketplace_bump = ctx.accounts.marketplace.bump;+ let signer_seeds: &[&[&[u8]]] = &[&[MARKETPLACE_SEED, &[marketplace_bump]]];++ // Issue the single token to the owner's ATA, signed by the marketplace PDA.+ token::mint_to(+ CpiContext::new_with_signer(+ ctx.accounts.token_program.to_account_info(),+ MintTo {+ mint: ctx.accounts.nft_mint.to_account_info(),+ to: ctx.accounts.owner_token_account.to_account_info(),+ authority: ctx.accounts.marketplace.to_account_info(),+ },+ signer_seeds,+ ),+ 1,+ )?;++ // Permanently lock supply at 1 by removing the mint authority. Freeze+ // authority is intentionally retained by the marketplace so a license can+ // be revoked (frozen) on refund without the holder's signature.+ token::set_authority(+ CpiContext::new_with_signer(+ ctx.accounts.token_program.to_account_info(),+ SetAuthority {+ current_authority: ctx.accounts.marketplace.to_account_info(),+ account_or_mint: ctx.accounts.nft_mint.to_account_info(),+ },+ signer_seeds,+ ),+ AuthorityType::MintTokens,+ None,+ )?;++ let now = Clock::get()?.unix_timestamp;+ let license = &mut ctx.accounts.skill_license;+ license.authority = ctx.accounts.owner.key();+ license.agent_mint = ctx.accounts.agent_mint.key();+ license.nft_mint = ctx.accounts.nft_mint.key();+ license.skill_hash = skill_seed(&skill_name);+ license.purchase_date = now;+ license.revoked_at = 0;+ license.bump = ctx.bumps.skill_license;+ license.skill_name = skill_name.clone();++ let marketplace = &mut ctx.accounts.marketplace;+ marketplace.licenses_minted = marketplace+ .licenses_minted+ .checked_add(1)+ .ok_or(SkillLicenseError::Overflow)?;++ emit!(SkillLicenseMinted {+ license: ctx.accounts.skill_license.key(),+ owner: ctx.accounts.owner.key(),+ agent_mint: ctx.accounts.agent_mint.key(),+ nft_mint: ctx.accounts.nft_mint.key(),+ skill_name,+ purchase_date: now,+ });+ Ok(())+ }++ /// Burn a license the caller owns: burn the 1/1 NFT, close the empty token+ /// account, and close the [`SkillLicense`] PDA — reclaiming all rent to the+ /// owner. Used for holder-initiated disposal / pre-transfer teardown.+ pub fn burn_skill_license(ctx: Context<BurnSkillLicense>) -> Result<()> {+ token::burn(+ CpiContext::new(+ ctx.accounts.token_program.to_account_info(),+ Burn {+ mint: ctx.accounts.nft_mint.to_account_info(),+ from: ctx.accounts.owner_token_account.to_account_info(),+ authority: ctx.accounts.authority.to_account_info(),+ },+ ),+ 1,+ )?;++ token::close_account(CpiContext::new(+ ctx.accounts.token_program.to_account_info(),+ CloseAccount {+ account: ctx.accounts.owner_token_account.to_account_info(),+ destination: ctx.accounts.authority.to_account_info(),+ authority: ctx.accounts.authority.to_account_info(),+ },+ ))?;++ emit!(SkillLicenseBurned {+ license: ctx.accounts.skill_license.key(),+ owner: ctx.accounts.authority.key(),+ nft_mint: ctx.accounts.nft_mint.key(),+ });+ Ok(())+ }++ /// Revoke a license on refund. Minter-only. Freezes the holder's token+ /// account (using the marketplace freeze authority retained at mint) so the+ /// NFT can no longer be transferred, and stamps `revoked_at`. The PDA is+ /// kept so off-chain verifiers can read the revoked state; the license is no+ /// longer access-bearing.+ pub fn revoke_skill_license(ctx: Context<RevokeSkillLicense>) -> Result<()> {+ require!(+ ctx.accounts.skill_license.revoked_at == 0,+ SkillLicenseError::AlreadyRevoked+ );++ let marketplace_bump = ctx.accounts.marketplace.bump;+ let signer_seeds: &[&[&[u8]]] = &[&[MARKETPLACE_SEED, &[marketplace_bump]]];++ token::freeze_account(CpiContext::new_with_signer(+ ctx.accounts.token_program.to_account_info(),+ FreezeAccount {+ account: ctx.accounts.owner_token_account.to_account_info(),+ mint: ctx.accounts.nft_mint.to_account_info(),+ authority: ctx.accounts.marketplace.to_account_info(),+ },+ signer_seeds,+ ))?;++ let now = Clock::get()?.unix_timestamp;+ ctx.accounts.skill_license.revoked_at = now;++ emit!(SkillLicenseRevoked {+ license: ctx.accounts.skill_license.key(),+ owner: ctx.accounts.skill_license.authority,+ nft_mint: ctx.accounts.nft_mint.key(),+ revoked_at: now,+ });+ Ok(())+ }+}++#[derive(Accounts)]+pub struct InitializeMarketplace<'info> {+ #[account(+ init,+ payer = authority,+ space = Marketplace::SPACE,+ seeds = [MARKETPLACE_SEED],+ bump,+ )]+ pub marketplace: Account<'info, Marketplace>,++ #[account(mut)]+ pub authority: Signer<'info>,++ pub system_program: Program<'info, System>,+}++#[derive(Accounts)]+pub struct SetMinter<'info> {+ #[account(+ mut,+ seeds = [MARKETPLACE_SEED],+ bump = marketplace.bump,+ has_one = authority @ SkillLicenseError::UnauthorizedAdmin,+ )]+ pub marketplace: Account<'info, Marketplace>,++ pub authority: Signer<'info>,+}++#[derive(Accounts)]+#[instruction(skill_name: String)]+pub struct MintSkillLicense<'info> {+ #[account(+ mut,+ seeds = [MARKETPLACE_SEED],+ bump = marketplace.bump,+ )]+ pub marketplace: Account<'info, Marketplace>,++ /// The authorized backend minter. Must equal `marketplace.minter`; pays rent+ /// + fees for the new accounts.+ #[account(+ mut,+ constraint = minter.key() == marketplace.minter @ SkillLicenseError::UnauthorizedMinter,+ )]+ pub minter: Signer<'info>,++ /// The license recipient. Does not sign — the backend mints on their behalf.+ /// CHECK: only its key is used, to own the ATA and as the license authority.+ pub owner: UncheckedAccount<'info>,++ /// The agent this skill belongs to (its on-chain identity / collection mint).+ /// CHECK: only its key is used, in the PDA seeds and recorded on the license.+ pub agent_mint: UncheckedAccount<'info>,++ #[account(+ init,+ payer = minter,+ space = SkillLicense::SPACE,+ seeds = [+ SKILL_LICENSE_SEED,+ owner.key().as_ref(),+ agent_mint.key().as_ref(),+ &skill_seed(&skill_name),+ ],+ bump,+ )]+ pub skill_license: Account<'info, SkillLicense>,++ #[account(+ init,+ payer = minter,+ seeds = [+ SKILL_MINT_SEED,+ owner.key().as_ref(),+ agent_mint.key().as_ref(),+ &skill_seed(&skill_name),+ ],+ bump,+ mint::decimals = 0,+ mint::authority = marketplace,+ mint::freeze_authority = marketplace,+ )]+ pub nft_mint: Account<'info, Mint>,++ #[account(+ init,+ payer = minter,+ associated_token::mint = nft_mint,+ associated_token::authority = owner,+ )]+ pub owner_token_account: Account<'info, TokenAccount>,++ pub token_program: Program<'info, Token>,+ pub associated_token_program: Program<'info, AssociatedToken>,+ pub system_program: Program<'info, System>,+ pub rent: Sysvar<'info, Rent>,+}++#[derive(Accounts)]+pub struct BurnSkillLicense<'info> {+ #[account(+ mut,+ close = authority,+ has_one = authority @ SkillLicenseError::NotLicenseOwner,+ seeds = [+ SKILL_LICENSE_SEED,+ authority.key().as_ref(),+ skill_license.agent_mint.as_ref(),+ skill_license.skill_hash.as_ref(),+ ],+ bump = skill_license.bump,+ )]+ pub skill_license: Account<'info, SkillLicense>,++ #[account(mut)]+ pub authority: Signer<'info>,++ #[account(mut, address = skill_license.nft_mint @ SkillLicenseError::MintMismatch)]+ pub nft_mint: Account<'info, Mint>,++ #[account(+ mut,+ associated_token::mint = nft_mint,+ associated_token::authority = authority,+ )]+ pub owner_token_account: Account<'info, TokenAccount>,++ pub token_program: Program<'info, Token>,+}++#[derive(Accounts)]+pub struct RevokeSkillLicense<'info> {+ #[account(+ seeds = [MARKETPLACE_SEED],+ bump = marketplace.bump,+ )]+ pub marketplace: Account<'info, Marketplace>,++ #[account(+ constraint = minter.key() == marketplace.minter @ SkillLicenseError::UnauthorizedMinter,+ )]+ pub minter: Signer<'info>,++ /// The license holder. CHECK: only its key is used, to locate the ATA and+ /// re-derive the license PDA; it does not sign a revocation.+ pub owner: UncheckedAccount<'info>,++ #[account(+ mut,+ constraint = skill_license.authority == owner.key() @ SkillLicenseError::NotLicenseOwner,+ seeds = [+ SKILL_LICENSE_SEED,+ owner.key().as_ref(),+ skill_license.agent_mint.as_ref(),+ skill_license.skill_hash.as_ref(),+ ],+ bump = skill_license.bump,+ )]+ pub skill_license: Account<'info, SkillLicense>,++ // Read-only for a freeze: only the holder's token account changes state.+ #[account(address = skill_license.nft_mint @ SkillLicenseError::MintMismatch)]+ pub nft_mint: Account<'info, Mint>,++ #[account(+ mut,+ associated_token::mint = nft_mint,+ associated_token::authority = owner,+ )]+ pub owner_token_account: Account<'info, TokenAccount>,++ pub token_program: Program<'info, Token>,+}++/// Singleton config: the platform's admin + the wallet authorized to mint+/// licenses, and a lifetime counter of licenses issued.+#[account]+pub struct Marketplace {+ pub authority: Pubkey,+ pub minter: Pubkey,+ pub licenses_minted: u64,+ pub bump: u8,+}++impl Marketplace {+ // discriminator + authority + minter + licenses_minted + bump+ pub const SPACE: usize = 8 + 32 + 32 + 8 + 1;+}++/// On-chain ownership record for one purchased skill. Its mere existence (with+/// `revoked_at == 0`) is the access key off-chain verifiers check.+#[account]+pub struct SkillLicense {+ /// Wallet that owns the license (and holds the NFT).+ pub authority: Pubkey,+ /// Agent the skill belongs to, for grouping.+ pub agent_mint: Pubkey,+ /// The 1/1 NFT mint that backs this license.+ pub nft_mint: Pubkey,+ /// SHA-256 of `skill_name`, the third PDA seed.+ pub skill_hash: [u8; 32],+ /// Unix seconds when the license was minted.+ pub purchase_date: i64,+ /// Unix seconds when revoked, or 0 while active.+ pub revoked_at: i64,+ /// PDA bump.+ pub bump: u8,+ /// Human-readable skill identifier (≤ 64 bytes).+ pub skill_name: String,+}++impl SkillLicense {+ // discriminator + authority + agent_mint + nft_mint + skill_hash+ // + purchase_date + revoked_at + bump + (4-byte len prefix + max name).+ pub const SPACE: usize = 8 + 32 + 32 + 32 + 32 + 8 + 8 + 1 + 4 + MAX_SKILL_NAME_LEN;+}++#[event]+pub struct SkillLicenseMinted {+ pub license: Pubkey,+ pub owner: Pubkey,+ pub agent_mint: Pubkey,+ pub nft_mint: Pubkey,+ pub skill_name: String,+ pub purchase_date: i64,+}++#[event]+pub struct SkillLicenseBurned {+ pub license: Pubkey,+ pub owner: Pubkey,+ pub nft_mint: Pubkey,+}++#[event]+pub struct SkillLicenseRevoked {+ pub license: Pubkey,+ pub owner: Pubkey,+ pub nft_mint: Pubkey,+ pub revoked_at: i64,+}++#[error_code]+pub enum SkillLicenseError {+ #[msg("skill_name must not be empty")]+ EmptySkillName,+ #[msg("skill_name exceeds the maximum allowed length")]+ SkillNameTooLong,+ #[msg("only the marketplace admin authority may perform this action")]+ UnauthorizedAdmin,+ #[msg("only the authorized minter may mint or revoke licenses")]+ UnauthorizedMinter,+ #[msg("signer is not the owner of this license")]+ NotLicenseOwner,+ #[msg("nft_mint does not match the one recorded on the license")]+ MintMismatch,+ #[msg("license is already revoked")]+ AlreadyRevoked,+ #[msg("arithmetic overflow")]+ Overflow,+}diff --git a/data/changelog.json b/data/changelog.jsonindex ed2d58b74..4c61ab247 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,25 @@{"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-18",+ "title": "Forge always reaches for a free 3D engine first",+ "summary": "Text-to-3D and image-to-3D generation now exhaust the free engines before any paid one. A prompt is rendered on the free NVIDIA lane; if that's busy, the reference image is reconstructed into a mesh on a free engine too — the platform only reaches for a paid engine as a genuine last resort. And if every engine is briefly out of reach, you now get an honest \"temporarily unavailable, try again shortly\" instead of a confusing technical billing message. Same Forge, fewer dead ends, no surprise costs.",+ "tags": [+ "improvement",+ "fix"+ ],+ "link": "/forge"+ },+ {+ "date": "2026-06-18",+ "title": "Subscribe to an agent in one click — pay once, unlock every paid skill",+ "summary": "Agent pages now show the creator's subscription tiers right under skills & pricing, each with a Subscribe button. Pick a tier, confirm the price and billing cycle in the checkout, and approve a single USDC payment in your wallet — the platform covers the network fee, so you don't need any SOL. Once the payment confirms on-chain your subscription goes live instantly and unlocks all of that agent's paid skills for the period; the page marks tiers you're already on so you never pay twice. Built on the same verified on-chain settlement as one-off skill purchases.",+ "tags": [+ "feature"+ ],+ "link": "/marketplace"+ },{"date": "2026-06-18","title": "Faster marketplace — agent pages load skill prices from cache",diff --git a/pages/agent-detail.html b/pages/agent-detail.htmlindex f9d38cf89..4fb1edd20 100644--- a/pages/agent-detail.html+++ b/pages/agent-detail.html@@ -425,6 +425,15 @@<div id="ad-pricing-library" hidden></div></section>+ <section class="ad-card ad-tiers-card" id="ad-tiers-card" hidden>+ <div class="ad-card-head">+ <span class="ad-bullet ad-bullet-violet"></span>+ <h2>SUBSCRIPTION TIERS</h2>+ </div>+ <p class="ad-tiers-sub" id="ad-tiers-sub" hidden></p>+ <div class="ad-tiers-body" id="ad-tiers-body"></div>+ </section>+<section class="ad-card"><div class="ad-card-head"><span class="ad-bullet"></span>diff --git a/pages/marketplace.html b/pages/marketplace.htmlindex 1fe719cf2..bbd028210 100644--- a/pages/marketplace.html+++ b/pages/marketplace.html@@ -1947,6 +1947,11 @@border-color: rgba(253, 224, 71, 0.3);color: #fde68a;}+ .payment-modal-badge.info {+ background: rgba(87, 199, 255, 0.08);+ border-color: rgba(87, 199, 255, 0.3);+ color: #bfe6ff;+ }/* Persistent post-purchase success card. Replaces the modal body sothe user sees what they bought + a one-click path to use it,@@ -3045,6 +3050,29 @@<p id="d-overview">—</p></div>+ <!-- Subscription tiers — recurring plans the creator+ offers. Populated by renderSubscriptionTiers(); the+ section stays hidden when the agent has no active+ plans so the overview never shows an empty shell. -->+ <section+ class="market-card d-subs-card"+ id="subscription-tiers-section"+ aria-label="Subscription plans"+ hidden+ >+ <div class="d-subs-head">+ <h3>Subscribe for exclusive perks</h3>+ <p class="d-subs-sub" id="d-subs-sub"></p>+ </div>+ <div class="tiers-grid" id="tiers-grid" role="list"></div>+ <p+ class="d-subs-status"+ id="d-subs-status"+ role="status"+ aria-live="polite"+ ></p>+ </section>+<!-- Ratings & reviews --><sectionclass="d-rating-widget"diff --git a/prompts/monetization/14-subscription-tiers-ui-creator.md b/prompts/monetization/14-subscription-tiers-ui-creator.mddeleted file mode 100644index e863f3e68..000000000--- a/prompts/monetization/14-subscription-tiers-ui-creator.md+++ /dev/null@@ -1,141 +0,0 @@-----status: not-started------# Prompt 14: Subscription Tiers UI for Creators--## Objective-Create a user interface in the agent edit page for creators to define and manage their subscription tiers.--## Explanation-Creators need a way to create, view, edit, and delete subscription tiers for their agents. This UI will allow them to set up their monetization strategy directly from the agent management dashboard.--## Instructions-1. **Add a New UI Section in `agent-edit.html`:**- * Create a new section titled "Subscription Tiers".- * This section should have a button to "Create New Tier".- * It should also contain a list or table to display existing tiers for the agent.--2. **Create a Tier Editor Modal:**- * Clicking "Create New Tier" (or "Edit" on an existing tier) should open a modal dialog.- * The modal form should contain input fields for all the properties of a subscription tier:- * Tier Name (text input)- * Description (textarea)- * Price (number input)- * Currency (select, e.g., USDC)- * Billing Interval (e.g., a select dropdown with "Monthly", "Yearly").- * Active (a checkbox/toggle)--3. **Implement Frontend Logic:**- * Write JavaScript to fetch the agent's existing tiers and render them in the list.- * Each rendered tier should have "Edit" and "Delete" buttons.- * Implement the logic to show the modal and populate it with data when editing an existing tier, or show it empty for a new tier.- * The "Save" button in the modal will be wired up to the backend API in the next step.- * The "Delete" button should trigger a confirmation prompt before proceeding.--## Code Example (HTML in `agent-edit.html`)--```html-<div class="form-section">- <h2>Subscription Tiers</h2>- <div id="existing-tiers-list">- <!-- Existing tiers will be rendered here -->- </div>- <button type="button" id="create-tier-btn" class="cta-button">+ Create New Tier</button>-</div>--<!-- Tier Editor Modal (hidden by default) -->-<div id="tier-editor-modal" class="modal-backdrop">- <div class="modal-content">- <div class="modal-header">- <h3 id="tier-modal-title">Create Tier</h3>- </div>- <div class="modal-body">- <input type="hidden" id="tier-id-input">- <div class="form-group">- <label for="tier-name">Tier Name</label>- <input type="text" id="tier-name" placeholder="e.g., Supporter">- </div>- <div class="form-group">- <label for="tier-description">Description</label>- <textarea id="tier-description" placeholder="e.g., Access to exclusive content..."></textarea>- </div>- <div class="form-row">- <div class="form-group">- <label for="tier-price">Price</label>- <input type="number" id="tier-price" placeholder="0.00">- </div>- <div class="form-group">- <label for="tier-currency">Currency</label>- <select id="tier-currency">- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7uP3">USDC</option>- </select>- </div>- <div class="form-group">- <label for="tier-interval">Interval</label>- <select id="tier-interval">- <option value="month">Monthly</option>- <option value="year">Yearly</option>- </select>- </div>- </div>- </div>- <div class="modal-actions">- <button id="cancel-tier-btn" type="button">Cancel</button>- <button id="save-tier-btn" type="button" class="cta-button">Save Tier</button>- </div>- </div>-</div>-```--## Code Example (JavaScript Logic)--```javascript-// Renders the list of existing tiers-async function renderTiersList(agentId) {- const response = await fetch(`/api/agents/${agentId}/tiers`);- const tiers = await response.json();- const container = document.getElementById('existing-tiers-list');-- container.innerHTML = tiers.map(tier => `- <div class="tier-summary-row">- <span>${escapeHtml(tier.name)} - ${(tier.price_amount / 1e6).toFixed(2)} USDC / ${tier.interval}</span>- <div>- <button onclick="openTierModal(${JSON.stringify(tier)})">Edit</button>- <button onclick="deleteTier('${tier.id}')">Delete</button>- </div>- </div>- `).join('');-}--// Opens the modal for creating or editing a tier-function openTierModal(tier = null) {- const modal = document.getElementById('tier-editor-modal');- if (tier) {- // Populate form with existing tier data for editing- document.getElementById('tier-modal-title').textContent = 'Edit Tier';- document.getElementById('tier-id-input').value = tier.id;- // ... set other input values- } else {- // Clear form for creating a new tier- document.getElementById('tier-modal-title').textContent = 'Create Tier';- document.getElementById('tier-id-input').value = '';- // ... clear other input values- }- modal.style.display = 'flex';-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/14-subscription-tiers-ui-creator.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/15-caching-skill-prices.md b/prompts/monetization/15-caching-skill-prices.mddeleted file mode 100644index 883436310..000000000--- a/prompts/monetization/15-caching-skill-prices.md+++ /dev/null@@ -1,37 +0,0 @@-----status: not-started------# Prompt 15: Caching Skill Prices--## Objective-Implement a caching layer to reduce database load and improve the performance of fetching skill prices.--## Explanation-Skill prices are unlikely to change frequently. Caching this data will improve the responsiveness of the marketplace and reduce the number of queries to the database.--## Instructions-1. **Choose a Caching Strategy:**- * Decide on a caching solution, such as Redis or an in-memory cache.--2. **Implement Caching Logic:**- * When fetching agent details, first check the cache for the skill prices.- * If the prices are in the cache, return them directly.- * If not, fetch them from the database and store them in the cache with an expiration time (e.g., 1 hour).--3. **Cache Invalidation:**- * When a creator updates their skill prices, invalidate the corresponding cache entry to ensure the new prices are displayed.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/15-caching-skill-prices.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/15-save-subscription-tiers-api.md b/prompts/monetization/15-save-subscription-tiers-api.mddeleted file mode 100644index c20bddfdd..000000000--- a/prompts/monetization/15-save-subscription-tiers-api.md+++ /dev/null@@ -1,108 +0,0 @@-----status: not-started------# Prompt 15: Save and Manage Subscription Tiers API--## Objective-Implement the backend API endpoints for creating, updating, and deleting subscription tiers.--## Explanation-This prompt provides the backend support for the creator-facing UI built in the previous step. It involves creating a set of CRUD (Create, Read, Update, Delete) APIs to manage the `agent_subscription_tiers` table.--## Instructions-1. **Create API Routes:**- * Set up the following authenticated routes, ensuring that only the agent owner can perform these actions.- * `POST /api/agents/:id/tiers`: Create a new subscription tier.- * `GET /api/agents/:id/tiers`: Get all tiers for a specific agent.- * `PUT /api/agents/:id/tiers/:tierId`: Update an existing tier.- * `DELETE /api/agents/:id/tiers/:tierId`: Delete a tier.--2. **Implement Create Logic (`POST`):**- * The endpoint receives tier details in the request body.- * Validate the input (e.g., price must be a non-negative number).- * Insert a new record into the `agent_subscription_tiers` table.- * Return the newly created tier object.--3. **Implement Read Logic (`GET`):**- * This endpoint can be public or owner-only, depending on whether you want users to see tiers before the UI is ready.- * Query the database for all tiers associated with the `agent_id`.- * Return the list of tiers.--4. **Implement Update Logic (`PUT`):**- * Receive updated tier details in the request body.- * Validate the input.- * Update the corresponding record in the `agent_subscription_tiers` table where the `id` and `agent_id` match.- * Return the updated tier object.--5. **Implement Delete Logic (`DELETE`):**- * This is a critical action. Before deleting, check if there are any active subscribers to this tier in the `user_subscriptions` table.- * Decide on a policy: either prevent deletion of tiers with active subscribers, or mark the tier as inactive (`active = false`) instead of a hard delete. Marking as inactive is generally safer.- * Perform the delete or update operation.- * Return a success status.--## Code Example (Backend - Express.js style routes)--```javascript-// Middleware to verify agent ownership for all tier routes-const verifyAgentOwner = async (req, res, next) => {- const agentId = req.params.id;- const userId = await getUserIdFromRequest(req);- const agent = await db.query('SELECT owner_id FROM agents WHERE id = $1', [agentId]);- if (!agent || agent.owner_id !== userId) {- return res.status(403).json({ error: 'Forbidden' });- }- next();-};--const tierRoutes = express.Router({ mergeParams: true });-tierRoutes.use(verifyAgentOwner);--// GET /api/agents/:id/tiers-tierRoutes.get('/', async (req, res) => {- const tiers = await db.query('SELECT * FROM agent_subscription_tiers WHERE agent_id = $1 ORDER BY price_amount', [req.params.id]);- res.json(tiers.rows);-});--// POST /api/agents/:id/tiers-tierRoutes.post('/', async (req, res) => {- const { name, description, price, currency, interval } = req.body;- // Convert price to integer lamports, validate inputs...- const amount = Math.round(price * 1e6);- const result = await db.query(- 'INSERT INTO agent_subscription_tiers (agent_id, name, description, price_amount, price_currency_mint, interval) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',- [req.params.id, name, description, amount, currency, interval]- );- res.status(201).json(result.rows[0]);-});--// PUT /api/agents/:id/tiers/:tierId-tierRoutes.put('/:tierId', async (req, res) => {- // ... similar logic to POST for updating ...-});--// DELETE /api/agents/:id/tiers/:tierId-tierRoutes.delete('/:tierId', async (req, res) => {- const { tierId } = req.params;- // SAFER: Mark as inactive instead of deleting- await db.query('UPDATE agent_subscription_tiers SET active = false WHERE id = $1', [tierId]);- res.status(204).send();-});--// Mount the routes in your main app file-// app.use('/api/agents/:id/tiers', tierRoutes);-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/15-save-subscription-tiers-api.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/15_gasless_transactions.md b/prompts/monetization/15_gasless_transactions.mddeleted file mode 100644index 31e61ebea..000000000--- a/prompts/monetization/15_gasless_transactions.md+++ /dev/null@@ -1,88 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 15: Gasless Transactions (Payer Sponsorship)--## Objective-Implement a "gasless" transaction system where the platform sponsors the Solana network fees for skill purchases, improving the user experience.--## Explanation-Users often don't have SOL in their wallets, even if they have USDC. Forcing them to acquire SOL just to pay for a minor gas fee is a major point of friction. We can sponsor these transactions. The user still signs the token transfer, but our backend pays the associated SOL fee. This is done using Solana's "Versioned Transactions" with a Payer.--## Instructions-1. **Platform Payer Keypair:**- * Create a dedicated Solana keypair for the platform, which will be used to pay for transaction fees.- * Store this keypair's secret key securely in the backend environment (e.g., in a secrets manager).- * This wallet must be funded with SOL.--2. **Modify Purchase Preparation API (`purchase-prep`):**- * Instead of creating a "Legacy" `Transaction`, you will now create a `VersionedTransaction`.- * The `feePayer` of the transaction will now be the **platform's payer public key**.- * The user's public key is still the one signing the token transfer instruction itself.- * After adding the transfer instructions, the transaction is **partially signed by the platform's payer keypair on the backend**.- * The serialized transaction sent to the frontend is now a partially signed `VersionedTransaction`.--3. **Modify Frontend Signing Logic:**- * The frontend will receive the partially signed, versioned transaction.- * The `wallet.signTransaction` method works the same way for the user; they are just signing a transaction where they are not the fee payer.- * The rest of the flow (send, confirm) remains largely the same.--## Code Example (Backend `purchase-prep` API)--```javascript-import {- Connection,- PublicKey,- TransactionMessage,- VersionedTransaction,- Keypair-} from '@solana/web3.js';-// ...--// Load your platform's payer keypair securely-const platformPayer = Keypair.fromSecretKey(Buffer.from(process.env.PAYER_SECRET_KEY, 'base64'));--// ... Inside the endpoint logic-export default wrap(async (req, res) => {- // ...- // The buyer is still the authority for the transfer, but not the fee payer- const buyerPublicKey = new PublicKey(user.wallet_address);-- const instructions = [- // ... createTransferInstruction for creator payout- // ... createTransferInstruction for platform fee- ];-- const { blockhash } = await connection.getLatestBlockhash();- const messageV0 = new TransactionMessage({- payerKey: platformPayer.publicKey, // PLATFORM pays the fee- recentBlockhash: blockhash,- instructions,- }).compileToV0Message();-- const tx = new VersionedTransaction(messageV0);-- // The user's wallet will provide the signature for the token transfer- // We sign it with our payer key to cover the fees- tx.sign([platformPayer]);-- const serializedTx = Buffer.from(tx.serialize()).toString('base64');-- return json(res, 200, { transaction: serializedTx });-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/15_gasless_transactions.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/16-user-facing-subscription-ui.md b/prompts/monetization/16-user-facing-subscription-ui.mddeleted file mode 100644index 0cabaf27d..000000000--- a/prompts/monetization/16-user-facing-subscription-ui.md+++ /dev/null@@ -1,142 +0,0 @@-----status: not-started------# Prompt 16: User-Facing Subscription UI--## Objective-Display available subscription tiers on the agent detail page and provide a UI for users to initiate a subscription.--## Explanation-Now that creators can define tiers, we need to show them to potential subscribers. This involves fetching the tiers for an agent and displaying them in a clear, compelling way, with a "Subscribe" button for each.--## Instructions-1. **Update Agent Detail API:**- * Modify the main agent detail API endpoint (`/api/marketplace/agents/:id`).- * In addition to the agent's details, also fetch its *active* subscription tiers from the `agent_subscription_tiers` table.- * Include these tiers in the response, e.g., in an `agent.subscription_tiers` array.--2. **Create Subscription Tiers Section in UI:**- * On the `marketplace.html` page (or its detail view template), add a new section for "Subscriptions".- * This section will contain a grid or list to display the tier cards.--3. **Implement Frontend Rendering Logic:**- * In the `renderDetail` function, check if `agent.subscription_tiers` exists and is not empty.- * If it is, iterate over the tiers and render a card for each one.- * Each card should display:- * Tier Name- * Price (e.g., "5.00 USDC / month")- * Description / list of perks- * A "Subscribe" button.--4. **Handle User Subscription Status:**- * You will need to know if the user is already subscribed to the agent (at any tier).- * You can fetch this information along with the user's other data (like unlocked skills).- * If the user is already subscribed to a tier, the UI should reflect this. For example, highlight the current tier and change the button to "Manage Subscription", while disabling the buttons for other tiers.--## Code Example (HTML Structure for Tiers)--```html-<!-- In agent detail view -->-<div id="subscription-tiers-section" style="display: none;">- <h3>Subscribe for Exclusive Perks</h3>- <div id="tiers-grid" class="tiers-grid">- <!-- Tier cards will be rendered here -->- </div>-</div>-```--## CSS Example for Tier Cards--```css-.tiers-grid {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));- gap: 16px;- margin-top: 16px;-}-.tier-card {- border: 1px solid var(--border);- border-radius: var(--radius);- padding: 20px;- text-align: center;-}-.tier-card.subscribed {- border-color: var(--accent);- box-shadow: 0 0 10px rgba(0, 255, 65, 0.2);-}-.tier-card .name {- font-size: 18px;- font-weight: bold;- color: var(--text-bright);-}-.tier-card .price {- font-size: 22px;- color: var(--accent);- margin: 8px 0;-}-.tier-card .price .interval {- font-size: 12px;- color: #888;-}-.tier-card .description {- font-size: 12px;- color: #888;- min-height: 50px;-}-.tier-card .subscribe-btn {- margin-top: 16px;- width: 100%;-}-```--## Code Example (Frontend Rendering Logic)--```javascript-function renderSubscriptionTiers(agent, userSubscription) {- const container = document.getElementById('subscription-tiers-section');- const grid = document.getElementById('tiers-grid');- const tiers = agent.subscription_tiers || [];-- if (tiers.length === 0) {- container.style.display = 'none';- return;- }- container.style.display = 'block';-- grid.innerHTML = tiers.map(tier => {- const isSubscribed = userSubscription && userSubscription.tier_id === tier.id;- const buttonText = isSubscribed ? 'Current Plan' : 'Subscribe';- const isDisabled = userSubscription && !isSubscribed; // Disable other tiers if already subbed-- return `- <div class="tier-card ${isSubscribed ? 'subscribed' : ''}">- <div class="name">${escapeHtml(tier.name)}</div>- <div class="price">- ${(tier.price_amount / 1e6).toFixed(2)} USDC- <span class="interval">/ ${tier.interval}</span>- </div>- <div class="description">${escapeHtml(tier.description)}</div>- <button class="subscribe-btn" ${isDisabled || isSubscribed ? 'disabled' : ''}- onclick="initiateSubscription('${tier.id}')">- ${buttonText}- </button>- </div>- `;- }).join('');-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/16-user-facing-subscription-ui.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/16-user-subscription-flow.md b/prompts/monetization/16-user-subscription-flow.mddeleted file mode 100644index ad1bbd571..000000000--- a/prompts/monetization/16-user-subscription-flow.md+++ /dev/null@@ -1,96 +0,0 @@-# Prompt 16: User Subscription Flow--## Objective-Implement the frontend and backend logic for users to subscribe to an agent's subscription tier.--## Explanation-This task combines previous concepts (wallet connection, transaction creation, verification) into a subscription context. The user will select a subscription tier, approve a transaction for the first payment, and the backend will create a record in the `user_subscriptions` table to mark the subscription as active. This prompt will not cover recurring payments, but will set up the initial subscription.--## Instructions-1. **Update Marketplace UI:**- * In `src/marketplace.js`, when rendering the agent detail page, fetch and display the available subscription tiers.- * Each tier should have a "Subscribe" button.--2. **Subscription Confirmation Modal:**- * Clicking "Subscribe" should open a confirmation modal, similar to the one-time purchase, showing the tier name, price, and billing cycle.--3. **Backend Subscription Endpoint:**- * Create an endpoint `/api/subscriptions/subscribe`.- * It takes `tierId` and the user's public key.- * It constructs and returns a transaction for the first payment, just like the one-time purchase.--4. **Frontend Transaction Handling:**- * The frontend gets the transaction, has the user sign and send it.--5. **Backend Verification and Activation Endpoint:**- * Create an endpoint `/api/subscriptions/verify`.- * It takes a `transactionSignature` and `tierId`.- * It verifies the transaction on-chain.- * If valid, it creates a new record in the `user_subscriptions` table with a status of 'active'. It calculates `current_period_start` (now) and `current_period_end` (e.g., now + 1 month).--## Code Example (`api/subscriptions/verify.js`)--```javascript-import { supabase } from '../../_lib/supabase';-import { json, error } from '../../_lib/http';-import { getAuthUser } from '../../_lib/auth';--export default async function handler(req, res) {- const { transactionSignature, tierId } = req.body;- const user = await getAuthUser(req);-- if (!user) return error(res, 401, 'Unauthorized');-- // 1. Verify transaction on-chain (similar to prompt #6)- const isTxValid = await verifySubscriptionPayment(transactionSignature, tierId, user.id);- if (!isTxValid) {- return error(res, 400, 'Invalid transaction.');- }-- // 2. Get tier details to calculate the period end- const { data: tier } = await supabase.from('agent_subscription_tiers').select('billing_interval').eq('id', tierId).single();- if (!tier) {- return error(res, 404, 'Subscription tier not found.');- }-- // 3. Create the subscription record- const startDate = new Date();- const endDate = new Date(startDate);- if (tier.billing_interval === 'month') {- endDate.setMonth(startDate.getMonth() + 1);- } else if (tier.billing_interval === 'year') {- endDate.setFullYear(startDate.getFullYear() + 1);- }-- const { error: insertError } = await supabase- .from('user_subscriptions')- .insert({- user_id: user.id,- tier_id: tierId,- status: 'active',- current_period_start: startDate.toISOString(),- current_period_end: endDate.toISOString(),- // `transaction_signature` might be stored on a related `payments` table- });-- if (insertError) {- return error(res, 500, 'Failed to activate subscription.');- }-- return json(res, { success: true, message: 'Subscription activated!' });-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/16-user-subscription-flow.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/16_refactor_service_class.md b/prompts/monetization/16_refactor_service_class.mddeleted file mode 100644index cf65b2e2c..000000000--- a/prompts/monetization/16_refactor_service_class.md+++ /dev/null@@ -1,105 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 16: Refactor Monetization Logic into a Service Class--## Objective-To improve code organization and reusability, refactor the scattered monetization logic (database queries, transaction building) into a dedicated `MonetizationService` class.--## Explanation-As the monetization feature grows, the logic becomes more complex. Keeping it directly inside API handlers makes it hard to maintain, test, and reuse. A service class will encapsulate all the business logic related to skill pricing, purchases, and payouts, providing a clean interface for the API layer.--## Instructions-1. **Create a New Service File:**- * Create a file at `api/_lib/services/MonetizationService.js`.--2. **Design the `MonetizationService` Class:**- * The constructor can take a database connection object (`sql`) and the current user's session as arguments.- * Create methods that map to the core operations we've built:- * `getSkillPricesForAgent(agentId)`- * `setSkillPrices(agentId, prices)`- * `preparePurchaseTransaction(agentId, skillName)`- * `confirmPurchase(agentId, skillName, signature)`- * `checkSkillOwnership(agentId, skillName)`- * `getCreatorSalesData()`--3. **Migrate Logic into the Service:**- * Move the database queries and transaction-building logic from the API handlers (`api/marketplace/[action].js`, `api/skills/purchase-prep.js`, etc.) into the corresponding methods of the new service class.- * The API handlers should become much thinner; their primary role will be handling HTTP requests/responses, validating input, and calling the service methods.--4. **Refactor API Handlers:**- * Update all relevant API handlers to instantiate and use the `MonetizationService`.--## Code Example (`MonetizationService.js`)--```javascript-import { sql } from '../db.js';-import { Connection, ... } from '@solana/web3.js';-// ... other imports--export class MonetizationService {- constructor(user) {- this.user = user;- }-- async setSkillPrices(agentId, prices) {- if (!this.user) throw new Error('Authentication required.');-- // Verify ownership- const [agent] = await sql`...`;- if (!agent) throw new Error('Agent not found or permission denied.');-- // Perform the database upsert logic here...- }-- async preparePurchaseTransaction(agentId, skillName) {- if (!this.user) throw new Error('Authentication required.');-- // All the logic for fetching prices, wallets, and building- // the VersionedTransaction goes here...- // Returns the serialized transaction.- }-- // ... other methods-}-```--## Code Example (Refactored API Handler)--```javascript-// api/skills/purchase-prep.js-import { MonetizationService } from '../../_lib/services/MonetizationService.js';-// ...--export default wrap(async (req, res) => {- const user = await getSessionUser(req);- // ... input validation-- try {- const monetizationService = new MonetizationService(user);- const { transaction } = await monetizationService.preparePurchaseTransaction(- req.body.agent_id,- req.body.skill_name- );- return json(res, 200, { transaction });- } catch (e) {- // Handle specific errors from the service for better status codes- return error(res, 500, 'prep_failed', e.message);- }-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/16_refactor_service_class.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/17-access-control-for-skills.md b/prompts/monetization/17-access-control-for-skills.mddeleted file mode 100644index 0c31ce86c..000000000--- a/prompts/monetization/17-access-control-for-skills.md+++ /dev/null@@ -1,93 +0,0 @@-# Prompt 17: Access Control for Skills--## Objective-Implement a robust access control layer on the backend to check if a user is permitted to use a specific skill before execution.--## Explanation-Now that users can buy skills or subscribe to tiers, we need to enforce access. Before executing any skill via the API, the backend must check if the skill is free or, if it's paid, whether the user has the right to use it. This is a critical security measure to protect creators' intellectual property.--## Instructions-1. **Create an Access Control Middleware/Function:**- * It's best to centralize this logic. Create a helper function, e.g., `hasSkillAccess(userId, agentId, skillName)`.--2. **Implement Access Logic:**- * The `hasSkillAccess` function will perform the following checks in order:- 1. Check if the skill is priced in `agent_skill_prices`. If not, it's a free skill, so return `true`.- 2. If the skill is priced, check if the user has a one-time purchase record for it in `user_purchased_skills`. If yes, return `true`.- 3. If not purchased individually, check if the user has an active subscription (`user_subscriptions` table).- 4. If they have a subscription, check if the `skillName` is in the `included_skills` array of their subscribed `agent_subscription_tiers`. If yes, return `true`.- 5. If none of the above are true, return `false`.--3. **Integrate into Skill Execution Endpoint:**- * Locate the main API endpoint responsible for executing agent skills (e.g., `/api/chat` or `/api/agent-actions.js`).- * Before running the skill logic, call your new `hasSkillAccess` function.- * If it returns `false`, the endpoint should immediately stop and return a 403 Forbidden error with a message like "You do not have access to this skill. Please purchase it from the marketplace."--## Code Example (Access Control Logic)--```javascript-// In a helper file, e.g., /api/_lib/access-control.js-import { supabase } from './supabase';--export async function hasSkillAccess(userId, agentId, skillName) {- // 1. Check if the skill is free- const { data: price, error: priceError } = await supabase- .from('agent_skill_prices')- .select('amount')- .eq('agent_id', agentId)- .eq('skill_name', skillName)- .single();-- // If there's no price entry, it's considered free- if (!price) return true;-- // User must be logged in to access priced skills- if (!userId) return false;-- // 2. Check for a one-time purchase- const { data: purchase, error: purchaseError } = await supabase- .from('user_purchased_skills')- .select('id')- .eq('user_id', userId)- .eq('agent_id', agentId)- .eq('skill_name', skillName)- .single();-- if (purchase) return true;-- // 3. Check for an active subscription that includes this skill- const { data: subscription, error: subError } = await supabase- .from('user_subscriptions')- .select(`- status,- agent_subscription_tiers ( included_skills )- `)- .eq('user_id', userId)- .eq('status', 'active')- // We need to join through tiers to filter by agent- // This query is simplified; a real one might need an RPC function- // or a more complex join to link user_subscriptions -> tiers -> agents.- .single(); // Assuming one active sub per user/agent for now-- if (subscription && subscription.agent_subscription_tiers.included_skills.includes(skillName)) {- return true;- }-- // 4. If all checks fail- return false;-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/17-access-control-for-skills.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/18-on-chain-program-for-skill-nfts.md b/prompts/monetization/18-on-chain-program-for-skill-nfts.mddeleted file mode 100644index 0a4db64b4..000000000--- a/prompts/monetization/18-on-chain-program-for-skill-nfts.md+++ /dev/null@@ -1,101 +0,0 @@-# Prompt 18: On-Chain Program for Skill NFTs--## Objective-Design and outline the structure of a Solana program (smart contract) that represents ownership of a purchased skill as a Non-Fungible Token (NFT).--## Explanation-To fully embrace decentralization and give users true ownership, purchasing a skill should mint them an NFT that acts as an on-chain access key. This is a significant architectural step. The NFT would be tied to the user's wallet, the agent, and the specific skill. Our backend could then check for the presence of this NFT in a user's wallet as an alternative way to verify access. This prompt focuses on the design of the on-chain program using Anchor.--## Instructions-1. **Define the Program's State:**- * What data needs to be stored on-chain?- * We'll need an account to represent the skill license. Let's call it `SkillLicense`.- * The `SkillLicense` account should store:- * `authority` (the user's wallet that owns it).- * `agent_mint` (the public key of an NFT representing the agent itself, for grouping).- * `skill_name` (a string identifying the skill).- * `purchase_date`.--2. **Define the Program's Instructions:**- * What actions can users take?- * The primary instruction will be `mint_skill_license`.- * This instruction will be called by our backend (acting as a minter authority) after a payment is verified.- * It will create a new `SkillLicense` account and a corresponding NFT for the user.- * We might also need a `burn_skill_license` for refunds or transfers.--3. **Set up an Anchor Project:**- * If not already present, set up a new Anchor project in the `/contracts` directory.- * Define the `SkillLicense` account struct in `lib.rs`.- * Define the `mint_skill_license` instruction handler.--## Anchor (Rust) Code Example (`contracts/src/lib.rs`)--```rust-use anchor_lang::prelude::*;-// We would also use anchor_spl::token for NFT minting--declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");--#[program]-pub mod skill_marketplace {- use super::*;- pub fn mint_skill_license(- ctx: Context<MintSkillLicense>,- skill_name: String- ) -> Result<()> {- let license = &mut ctx.accounts.skill_license;- license.authority = *ctx.accounts.user.key;- license.agent_id = *ctx.accounts.agent.key; // Simplified: agent is an account- license.skill_name = skill_name;- license.purchase_date = Clock::get()?.unix_timestamp;-- // Here, we would also add the logic to mint a Metaplex NFT- // to the user's wallet, using this license account as a basis.- // This is a complex step involving CPIs to the Token and Metaplex programs.-- msg!("Skill license created for skill: {}", license.skill_name);- Ok(())- }-}--#[derive(Accounts)]-pub struct MintSkillLicense<'info> {- #[account(init, payer = minter, space = 8 + 32 + 32 + 32 + 8)]- pub skill_license: Account<'info, SkillLicense>,-- /// CHECK: The agent this skill belongs to- pub agent: AccountInfo<'info>,-- /// CHECK: The user who is receiving the license- #[account(mut)]- pub user: Signer<'info>,-- // The backend's wallet, which has authority to mint licenses- #[account(mut)]- pub minter: Signer<'info>,-- pub system_program: Program<'info, System>,-}--#[account]-pub struct SkillLicense {- pub authority: Pubkey, // User who owns the skill- pub agent_id: Pubkey, // Agent the skill is for- pub skill_name: String,- pub purchase_date: i64,-}-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/18-on-chain-program-for-skill-nfts.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/prompts/monetization/18_testing_the_service.md b/prompts/monetization/18_testing_the_service.mddeleted file mode 100644index a1cee1a6e..000000000--- a/prompts/monetization/18_testing_the_service.md+++ /dev/null@@ -1,86 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 18: Unit and Integration Tests for Monetization Service--## Objective-Write a suite of tests for the `MonetizationService` to ensure its logic is correct, robust, and reliable.--## Explanation-The monetization logic is critical and involves financial transactions, so it must be thoroughly tested. We need to create both unit tests (testing individual methods in isolation) and integration tests (testing the service's interaction with a real or mock database).--## Instructions-1. **Set Up a Testing Framework:**- * Ensure a testing framework like Jest or Vitest is configured for the backend.- * Set up a separate test database or a mechanism to run tests in a transaction that can be rolled back, to avoid polluting the development database.--2. **Write Unit Tests:**- * **Mock Dependencies:** Mock the `sql` database client and any external APIs.- * **Test Cases:**- * `setSkillPrices`: Test that it correctly formats the SQL query for upserting prices. Test that it throws an error if the user is not the agent owner.- * `preparePurchaseTransaction`: Mock the database calls for price/wallet lookups. Verify that the created transaction has the correct instructions, amounts, and public keys. Test the platform fee calculation.- * `checkSkillOwnership`: Mock database calls to simulate a user owning a skill, not owning it, and the skill being free. Test that it returns the correct access decision.--3. **Write Integration Tests:**- * **Use a Test Database:** Connect to a real test database.- * **Test Scenarios:**- * Create a test user and agent.- * Call `setSkillPrices` and then immediately query the database to verify the price was written correctly.- * Simulate a purchase confirmation by first inserting a record into `user_purchased_skills` and then calling `checkSkillOwnership` to ensure it returns true.- * Test the `getCreatorSalesData` method by seeding some purchase data and verifying that the aggregation (total revenue, counts) is correct.--## Code Example (Jest - Unit Test Snippet)--```javascript-// In tests/services/MonetizationService.test.js-import { MonetizationService } from '../../api/_lib/services/MonetizationService';-import { sql } from '../../api/_lib/db'; // Mock this--// Mock the database-jest.mock('../../api/_lib/db', () => ({- sql: jest.fn().mockResolvedValue([- // mock return values here- ]),-}));--describe('MonetizationService', () => {- let service;- const mockUser = { id: 'user-123' };-- beforeEach(() => {- service = new MonetizationService(mockUser);- sql.mockClear();- });-- it('should block price setting if user is not the owner', async () => {- // Mock the agent ownership check to return no agent- sql.mockResolvedValueOnce([]);- await expect(service.setSkillPrices('agent-abc', {})).rejects.toThrow('permission denied');- });-- it('should correctly calculate platform fee in transaction prep', async () => {- // Mock DB calls to return a price of 1,000,000 lamports- // Mock web3.js calls- // ...- const { transaction } = await service.preparePurchaseTransaction(...);- // Inspect the deserialized transaction to check instruction amounts- // expect(creatorInstruction.amount).toBe(950000); // 95%- // expect(platformFeeInstruction.amount).toBe(50000); // 5%- });-});-```--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "prompts/monetization/18_testing_the_service.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/public/changelog.json b/public/changelog.jsonindex 40ccf07fb..4eb0c83af 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T07:40:04.896Z",+ "generated_at": "2026-06-18T08:03:07.735Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -59,6 +59,17 @@"infra"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Forge always reaches for a free 3D engine first",+ "summary": "Text-to-3D and image-to-3D generation now exhaust the free engines before any paid one. A prompt is rendered on the free NVIDIA lane; if that's busy, the reference image is reconstructed into a mesh on a free engine too — the platform only reaches for a paid engine as a genuine last resort. And if every engine is briefly out of reach, you now get an honest \"temporarily unavailable, try again shortly\" instead of a confusing technical billing message. Same Forge, fewer dead ends, no surprise costs.",+ "link": "/forge",+ "tags": [+ "improvement",+ "fix"+ ]+ },{"date": "2026-06-18","type": "update",@@ -247,6 +258,16 @@"infra"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Subscribe to an agent in one click — pay once, unlock every paid skill",+ "summary": "Agent pages now show the creator's subscription tiers right under skills & pricing, each with a Subscribe button. Pick a tier, confirm the price and billing cycle in the checkout, and approve a single USDC payment in your wallet — the platform covers the network fee, so you don't need any SOL. Once the payment confirms on-chain your subscription goes live instantly and unlocks all of that agent's paid skills for the period; the page marks tiers you're already on so you never pay twice. Built on the same verified on-chain settlement as one-off skill purchases.",+ "link": "/marketplace",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-18","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex c89c2d43e..cf901aace 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -46,6 +46,14 @@<category>improvement</category><description>Agent and marketplace pages now feel snappier. A creator's skill prices are cached for an hour and shared across our servers instead of being re-read from the database on every single page view, so opening an agent, browsing the marketplace, or checking what a skill costs returns faster — especially for popular agents. The cache stays honest: the moment a creator changes a price the old value is cleared everywhere, so you always see the current price, and a purchase is still quoted against the exact price at checkout time.</description></item>+ <item>+ <title>Forge always reaches for a free 3D engine first</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-18:Forge always reaches for a free 3D engine first</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Text-to-3D and image-to-3D generation now exhaust the free engines before any paid one. A prompt is rendered on the free NVIDIA lane; if that's busy, the reference image is reconstructed into a mesh on a free engine too — the platform only reaches for a paid engine as a genuine last resort. And if every engine is briefly out of reach, you now get an honest "temporarily unavailable, try again shortly" instead of a confusing technical billing message. Same Forge, fewer dead ends, no surprise costs.</description>+ </item><item><title>Forge checkout no longer dead-ends when generation is briefly busy</title><link>https://three.ws/forge</link>@@ -190,6 +198,14 @@<category>fix</category><description>Live bonding-curve prices, market caps, and trade quotes now stay accurate even when a Solana data provider hits its rate limit: the platform transparently rotates to a healthy provider and parks the busy one, instead of repeatedly retrying a maxed-out endpoint and showing stale numbers. The free text-to-3D forge also rides out a cold or briefly-unavailable generation node by retrying once before falling back, so a momentary upstream hiccup no longer turns into a failed generation.</description></item>+ <item>+ <title>Subscribe to an agent in one click — pay once, unlock every paid skill</title>+ <link>https://three.ws/marketplace</link>+ <guid isPermaLink="false">2026-06-18:Subscribe to an agent in one click — pay once, unlock every paid skill</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Agent pages now show the creator's subscription tiers right under skills & pricing, each with a Subscribe button. Pick a tier, confirm the price and billing cycle in the checkout, and approve a single USDC payment in your wallet — the platform covers the network fee, so you don't need any SOL. Once the payment confirms on-chain your subscription goes live instantly and unlocks all of that agent's paid skills for the period; the page marks tiers you're already on so you never pay twice. Built on the same verified on-chain settlement as one-off skill purchases.</description>+ </item><item><title>The $THREE page now shows a live price chart</title><link>https://three.ws/three-token</link>diff --git a/public/features.json b/public/features.jsonindex 5affed2be..3f6a31fc3 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T07:40:04.878Z",+ "generated_at": "2026-06-18T08:03:07.716Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/marketplace.css b/public/marketplace.cssindex f36d1720e..faa528214 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -1411,6 +1411,171 @@ body.market-page > header {flex-shrink: 0;}+/* ── Subscription tiers (agent detail) ───────────────────────────────────── */++.d-subs-head {+ margin-bottom: var(--space-md);+}+.d-subs-head h3 {+ margin: 0;+}+.d-subs-sub {+ margin: var(--space-2xs) 0 0;+ font-size: 13px;+ color: var(--ink-dim);+}+.tiers-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: var(--space-md);+}+.tier-card {+ position: relative;+ display: flex;+ flex-direction: column;+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ background: var(--surface-1);+ padding: var(--space-lg) var(--space-md) var(--space-md);+ transition:+ border-color 0.18s ease,+ transform 0.18s ease,+ box-shadow 0.18s ease;+}+.tier-card:hover {+ border-color: var(--stroke-strong);+ transform: translateY(-2px);+}+.tier-card.subscribed {+ border-color: var(--success);+ box-shadow: 0 0 0 1px var(--success) inset, 0 8px 28px rgba(74, 222, 128, 0.12);+}+.tier-badge {+ position: absolute;+ top: calc(-1 * var(--space-sm));+ left: 50%;+ transform: translateX(-50%);+ padding: 2px var(--space-sm);+ border-radius: 999px;+ background: var(--success);+ color: #04130a;+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ white-space: nowrap;+}+.tier-name {+ font-size: 16px;+ font-weight: 600;+ color: var(--ink);+}+.tier-price {+ margin: var(--space-2xs) 0 var(--space-sm);+ font-family: var(--font-display);+ font-size: 26px;+ font-weight: 700;+ color: var(--ink);+ line-height: 1.1;+}+.tier-interval {+ margin-left: 4px;+ font-family: var(--font-mono);+ font-size: 12px;+ font-weight: 500;+ color: var(--ink-dim);+}+.tier-skills {+ margin-bottom: var(--space-sm);+ font-size: 12px;+ font-weight: 600;+ color: var(--success);+}+.tier-perks {+ margin: 0 0 var(--space-md);+ padding: 0;+ list-style: none;+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: var(--space-2xs);+}+.tier-perks li {+ position: relative;+ padding-left: 18px;+ font-size: 13px;+ color: var(--ink-dim);+ line-height: 1.4;+}+.tier-perks li::before {+ content: '✓';+ position: absolute;+ left: 0;+ top: 0;+ color: var(--success);+ font-weight: 700;+}+.tier-perks-empty {+ margin: 0 0 var(--space-md);+ flex: 1;+ font-size: 13px;+ color: var(--ink-dim);+}+.tier-btn {+ margin-top: auto;+ width: 100%;+ padding: var(--space-sm) var(--space-md);+ border-radius: var(--radius-md);+ border: 1px solid var(--stroke-strong);+ background: var(--surface-2);+ color: var(--ink);+ font-size: 14px;+ font-weight: 600;+ cursor: pointer;+ transition:+ background 0.18s ease,+ border-color 0.18s ease,+ opacity 0.18s ease;+}+.tier-btn:hover:not(:disabled) {+ border-color: var(--stroke-strong);+ background: var(--surface-1);+}+.tier-btn.primary {+ background: #fafafa;+ border-color: #fafafa;+ color: #000;+}+.tier-btn.primary:hover:not(:disabled) {+ background: #fff;+ border-color: #fff;+}+.tier-btn.current {+ background: transparent;+ border-color: var(--success);+ color: var(--success);+}+.tier-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}+.tier-btn:focus-visible {+ outline: var(--focus-ring-width, 2px) solid var(--focus-ring-color, var(--accent));+ outline-offset: var(--focus-ring-offset, 2px);+}+.d-subs-status {+ margin: var(--space-md) 0 0;+ min-height: 1em;+ font-size: 13px;+ color: var(--ink-dim);+}+.d-subs-status.err {+ color: var(--danger);+}+.d-subs-status.ok {+ color: var(--success);+}+.purchase-btn {margin-left: var(--space-xs);padding: var(--space-2xs) var(--space-sm);diff --git a/scripts/skill-license-smoke.mjs b/scripts/skill-license-smoke.mjsnew file mode 100644index 000000000..aed6ea86a--- /dev/null+++ b/scripts/skill-license-smoke.mjs@@ -0,0 +1,193 @@+#!/usr/bin/env node+/**+ * Devnet smoke test for the deployed `skill_license` Solana program.+ *+ * Exercises the real program end-to-end against the LIVE deployment:+ * 1. confirms the program id is deployed + executable on the target cluster,+ * 2. ensures the singleton marketplace config exists (initializes it on first+ * run, with the minter key as both admin authority and minter),+ * 3. mints a license to a fresh synthetic owner for a fresh synthetic agent+ * mint (never a real third-party wallet/mint),+ * 4. verifies the on-chain SkillLicense PDA reads back as owned + active,+ * 5. asserts the buyer's associated token account holds exactly 1 NFT.+ *+ * Re-runnable: fresh owner + agent mint each run, so the derived license/mint+ * PDAs never collide with a previous run. Exits non-zero on any failure.+ *+ * Env:+ * SOLANA_RPC_URL_DEVNET RPC endpoint (default https://api.devnet.solana.com)+ * SKILL_LICENSE_PROGRAM_ID override the program id (defaults to the baked id)+ * SKILL_LICENSE_MINTER_KEY base58 secret of the authorized minter (required).+ * On devnet it is funded via faucet; elsewhere it+ * must already hold SOL.+ */+import {+ Connection,+ Keypair,+ PublicKey,+ LAMPORTS_PER_SOL,+ Transaction,+ sendAndConfirmTransaction,+} from '@solana/web3.js';+import bs58 from 'bs58';++import {+ SKILL_LICENSE_PROGRAM_ID,+ buildInitializeMarketplaceIx,+ buildMintSkillLicenseIx,+ deriveMarketplacePda,+ verifyOnchainSkillLicense,+} from '../api/_lib/skill-license-onchain.js';++const RPC = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';+const PROGRAM_ID = new PublicKey(process.env.SKILL_LICENSE_PROGRAM_ID || SKILL_LICENSE_PROGRAM_ID);+const SKILL = 'summarize';++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++function loadMinter() {+ const secret = process.env.SKILL_LICENSE_MINTER_KEY;+ if (!secret) {+ throw new Error(+ 'SKILL_LICENSE_MINTER_KEY is required (base58 secret of the authorized minter).',+ );+ }+ return Keypair.fromSecretKey(bs58.decode(secret.trim()));+}++async function ensureFunded(connection, wallet) {+ const balance = await connection.getBalance(wallet.publicKey);+ if (balance >= 0.05 * LAMPORTS_PER_SOL) return;+ if (!RPC.includes('devnet')) {+ throw new Error(+ `minter ${wallet.publicKey.toBase58()} has insufficient SOL (${balance / LAMPORTS_PER_SOL}). ` ++ 'Fund it and re-run.',+ );+ }+ let lastErr;+ for (let attempt = 1; attempt <= 5; attempt++) {+ try {+ const sig = await connection.requestAirdrop(wallet.publicKey, 0.2 * LAMPORTS_PER_SOL);+ const bh = await connection.getLatestBlockhash();+ await connection.confirmTransaction({ signature: sig, ...bh }, 'confirmed');+ return;+ } catch (err) {+ lastErr = err;+ console.warn(` airdrop attempt ${attempt} failed: ${err.message}; retrying…`);+ await sleep(2000 * attempt);+ }+ }+ throw new Error(`could not fund minter via devnet faucet after retries (${lastErr?.message}).`);+}++function decodeMarketplaceMinter(data) {+ // 8-byte discriminator + authority(32) + minter(32)+ return new PublicKey(Buffer.from(data).subarray(40, 72));+}++async function ensureMarketplace(connection, minter) {+ const [marketplace] = deriveMarketplacePda(PROGRAM_ID);+ const info = await connection.getAccountInfo(marketplace);+ if (info) {+ const configured = decodeMarketplaceMinter(info.data);+ if (!configured.equals(minter.publicKey)) {+ throw new Error(+ `marketplace minter is ${configured.toBase58()}, but SKILL_LICENSE_MINTER_KEY is ` ++ `${minter.publicKey.toBase58()}. Use the configured minter key.`,+ );+ }+ console.log(` marketplace already initialized (minter ✓)`);+ return marketplace;+ }+ console.log(` initializing marketplace (authority + minter = ${minter.publicKey.toBase58()})…`);+ const { instruction } = buildInitializeMarketplaceIx({+ authority: minter.publicKey,+ minter: minter.publicKey,+ programId: PROGRAM_ID,+ });+ const sig = await sendAndConfirmTransaction(connection, new Transaction().add(instruction), [+ minter,+ ], { commitment: 'confirmed' });+ console.log(` marketplace initialized: ${sig}`);+ return marketplace;+}++async function main() {+ console.log(`skill_license smoke test`);+ console.log(` rpc: ${RPC}`);+ console.log(` program: ${PROGRAM_ID.toBase58()}`);++ const connection = new Connection(RPC, 'confirmed');++ const programAccount = await connection.getAccountInfo(PROGRAM_ID);+ if (!programAccount || !programAccount.executable) {+ throw new Error(+ `program ${PROGRAM_ID.toBase58()} is not deployed/executable on ${RPC}. Deploy it first.`,+ );+ }+ console.log(` program is deployed + executable ✓`);++ const minter = loadMinter();+ console.log(` minter: ${minter.publicKey.toBase58()}`);+ await ensureFunded(connection, minter);+ await ensureMarketplace(connection, minter);++ // Fresh synthetic recipient + agent grouping mint each run.+ const owner = Keypair.generate();+ const agentMint = Keypair.generate().publicKey;+ console.log(` owner: ${owner.publicKey.toBase58()}`);+ console.log(` agent mint: ${agentMint.toBase58()}`);++ console.log(` minting skill license '${SKILL}'…`);+ const { instruction, accounts } = buildMintSkillLicenseIx({+ minter: minter.publicKey,+ owner: owner.publicKey,+ agentMint,+ skillName: SKILL,+ programId: PROGRAM_ID,+ });+ const signature = await sendAndConfirmTransaction(connection, new Transaction().add(instruction), [+ minter,+ ], { commitment: 'confirmed' });+ console.log(` tx confirmed: ${signature}`);+ console.log(` license: ${accounts.skillLicense}`);+ console.log(` nft: ${accounts.nftMint}`);++ const result = await verifyOnchainSkillLicense({+ connection,+ ownerWallet: owner.publicKey.toBase58(),+ agentMint: agentMint.toBase58(),+ skill: SKILL,+ network: RPC.includes('devnet') ? 'devnet' : 'mainnet',+ programId: PROGRAM_ID,+ });+ const checks = [+ ['deployed', result.deployed, true],+ ['exists', result.exists, true],+ ['owned', result.owned, true],+ ['revoked', result.revoked, false],+ ['record.authority', result.record?.authority, owner.publicKey.toBase58()],+ ['record.agentMint', result.record?.agentMint, agentMint.toBase58()],+ ['record.nftMint', result.record?.nftMint, accounts.nftMint],+ ['record.skillName', result.record?.skillName, SKILL],+ ];+ for (const [name, got, want] of checks) {+ if (got !== want) throw new Error(`${name} mismatch: got ${got}, expected ${want}`);+ console.log(` ${name} ✓`);+ }++ const bal = await connection.getTokenAccountBalance(new PublicKey(accounts.ownerTokenAccount));+ if (bal.value.amount !== '1' || bal.value.decimals !== 0) {+ throw new Error(`expected exactly 1 NFT (0 decimals), got ${JSON.stringify(bal.value)}`);+ }+ console.log(` owner holds exactly 1 NFT ✓`);++ const cluster = RPC.includes('devnet') ? '?cluster=devnet' : '';+ console.log(`\n✅ SkillLicense minted + verified on-chain.`);+ console.log(` https://explorer.solana.com/address/${accounts.skillLicense}${cluster}`);+}++main().catch((err) => {+ console.error(`\n❌ smoke test failed: ${err.message}`);+ process.exit(1);+});diff --git a/src/agent-detail-market.js b/src/agent-detail-market.jsindex 493a14e77..b3eb4e3a7 100644--- a/src/agent-detail-market.js+++ b/src/agent-detail-market.js@@ -30,6 +30,7 @@ import {openPurchaseFlow,openTrialFlow,openTimePassFlow,+ openSubscribeFlow,openAssetPurchaseFlow,formatAssetPrice,apiPostWithCsrf,@@ -109,6 +110,7 @@ export async function enrichAgentDetail(baseAgent) {renderHeroActions(baseAgent, market);renderSalePanel(baseAgent, market);renderPricing(market);+ renderSubscriptionTiers(market).catch((e) => log.warn('[agent-detail-market] tiers', e?.message));renderEmbed(market);startPreviewSession(market);const preview = $('ad-preview-card');@@ -142,6 +144,7 @@ async function reloadPurchases(agentId) {purchasedSkills.clear();(fresh.purchased_skills || []).forEach((s) => purchasedSkills.add(s));renderPricing(fresh);+ renderSubscriptionTiers(fresh).catch(() => {});} catch (e) {log.warn('[agent-detail-market] reloadPurchases failed:', e.message);}@@ -554,6 +557,105 @@ function bindPurchaseDelegation() {});}+// ── Subscription tiers ─────────────────────────────────────────────────────────++let marketTiers = [];+let subscribedPlanIds = new Set();++async function renderSubscriptionTiers(a) {+ const card = $('ad-tiers-card');+ const body = $('ad-tiers-body');+ const sub = $('ad-tiers-sub');+ if (!card || !body) return;++ let tiers = [];+ try {+ const r = await fetch(`${API}/agents/${encodeURIComponent(a.id)}/tiers`, { credentials: 'include' });+ if (r.ok) {+ const j = await r.json();+ tiers = Array.isArray(j.tiers) ? j.tiers : [];+ }+ } catch (e) {+ log.warn('[agent-detail-market] tiers fetch failed:', e.message);+ }++ if (!tiers.length) { card.hidden = true; return; }+ marketTiers = tiers;+ card.hidden = false;++ // Highlight tiers the signed-in user already subscribes to.+ subscribedPlanIds = await fetchActiveSubscriptionIds();++ if (sub) {+ sub.textContent = isOwner+ ? 'Subscribers get access to all of this agent’s paid skills.'+ : 'Subscribe for full access to this agent’s paid skills.';+ sub.hidden = false;+ }++ body.innerHTML = tiers+ .map((t) => {+ const cycle = t.interval === 'weekly' ? 'week' : 'month';+ const price = Number(t.price_usd).toFixed(2);+ const perks = Array.isArray(t.perks) ? t.perks.filter(Boolean) : [];+ const perksHtml = perks.length+ ? `<ul class="ad-tier-perks">${perks.map((p) => `<li>${escapeHtml(p)}</li>`).join('')}</ul>`+ : '';+ let action;+ if (isOwner) {+ action = `<span class="ad-tier-note">Your tier</span>`;+ } else if (subscribedPlanIds.has(t.id)) {+ action = `<span class="ad-price-badge owned">✓ Subscribed</span>`;+ } else {+ action = `<button class="ad-tier-btn ad-subscribe-btn" data-tier-id="${escapeHtml(t.id)}" data-agent-id="${escapeHtml(a.id)}">Subscribe</button>`;+ }+ return `+ <div class="ad-tier">+ <div class="ad-tier-head">+ <span class="ad-tier-name">${escapeHtml(t.name)}</span>+ <span class="ad-tier-price">$${escapeHtml(price)}<span class="ad-tier-cycle">/${cycle}</span></span>+ </div>+ ${perksHtml}+ <div class="ad-tier-foot">${action}</div>+ </div>`;+ })+ .join('');++ bindTierDelegation();+}++// Active subscription plan_ids for the signed-in user (empty when anonymous).+async function fetchActiveSubscriptionIds() {+ try {+ const r = await fetch(`${API}/subscriptions/mine`, { credentials: 'include' });+ if (!r.ok) return new Set();+ const j = await r.json();+ return new Set(+ (j.subscriptions || []).filter((s) => s.status === 'active').map((s) => s.plan_id),+ );+ } catch {+ return new Set();+ }+}++let tierDelegationBound = false;+function bindTierDelegation() {+ if (tierDelegationBound) return;+ tierDelegationBound = true;+ const body = $('ad-tiers-body');+ if (!body) return;+ body.addEventListener('click', (e) => {+ const btn = e.target.closest?.('.ad-subscribe-btn');+ if (!btn) return;+ const tierId = btn.dataset.tierId;+ const agentId = btn.dataset.agentId;+ if (!tierId || !agentId) return;+ const tier = marketTiers.find((t) => t.id === tierId);+ if (!tier) return;+ openSubscribeFlow(agentId, tier).catch((err) => log.error('[agent-detail-market] subscribe', err));+ });+}+// ── Embed snippets ────────────────────────────────────────────────────────────export function renderEmbed(a) {diff --git a/src/agent-detail.css b/src/agent-detail.cssindex 7fc57ffc8..6244af940 100644--- a/src/agent-detail.css+++ b/src/agent-detail.css@@ -1416,6 +1416,114 @@ model-viewer.ad-hero-avatar {margin-top: 14px;}+/* ── Subscription tiers ────────────────────────────────────────────────── */+.ad-bullet-violet {+ background: #a78bfa;+}+.ad-tiers-sub {+ font-size: 13px;+ color: var(--ad-muted);+ margin: 0 0 14px;+}+.ad-tiers-body {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(190px, 1fr));+ gap: 12px;+}+.ad-tier {+ display: flex;+ flex-direction: column;+ gap: 10px;+ padding: 14px;+ border: 1px solid var(--ad-line-2);+ border-radius: 12px;+ background: var(--ad-bg-2);+ transition:+ border-color 0.15s,+ transform 0.15s;+}+.ad-tier:hover {+ border-color: rgba(167, 139, 250, 0.5);+ transform: translateY(-1px);+}+.ad-tier-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 8px;+}+.ad-tier-name {+ font-size: 14px;+ font-weight: 600;+ color: var(--ad-text);+}+.ad-tier-price {+ font-size: 18px;+ font-weight: 700;+ color: var(--ad-text);+ white-space: nowrap;+}+.ad-tier-cycle {+ font-size: 12px;+ font-weight: 500;+ color: var(--ad-muted);+}+.ad-tier-perks {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 6px;+}+.ad-tier-perks li {+ position: relative;+ padding-left: 18px;+ font-size: 12.5px;+ color: var(--ad-muted);+ line-height: 1.4;+}+.ad-tier-perks li::before {+ content: "✓";+ position: absolute;+ left: 0;+ color: #a78bfa;+ font-weight: 700;+}+.ad-tier-foot {+ margin-top: auto;+}+.ad-tier-btn {+ width: 100%;+ padding: 8px 12px;+ border-radius: 9px;+ border: 1px solid transparent;+ background: #a78bfa;+ color: #14101f;+ font: inherit;+ font-size: 13px;+ font-weight: 700;+ cursor: pointer;+ transition:+ background 0.15s,+ transform 0.1s;+}+.ad-tier-btn:hover {+ background: #b9a4fb;+}+.ad-tier-btn:active {+ transform: translateY(1px);+}+.ad-tier-btn:focus-visible {+ outline: 2px solid #c4b5fd;+ outline-offset: 2px;+}+.ad-tier-note {+ font-size: 12px;+ color: var(--ad-muted);+ font-style: italic;+}+/* ── Sale / ownership panel ────────────────────────────────────────────── */.ad-sale-eyebrow {font-size: 12px;@@ -1868,6 +1976,11 @@ model-viewer.ad-hero-avatar {border-color: rgba(245, 165, 36, 0.25);color: var(--ad-text);}+.payment-modal-badge.info {+ background: rgba(87, 199, 255, 0.08);+ border-color: rgba(87, 199, 255, 0.25);+ color: var(--ad-text);+}#payment-modal-lede {font-size: 13px;color: var(--ad-muted);diff --git a/src/marketplace.js b/src/marketplace.jsindex 35f65fa83..2ee7a8310 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -1721,6 +1721,216 @@ function renderDetailPricingSummary(agent) {overview.insertAdjacentElement('afterend', strip);}+// ── Subscription tiers ────────────────────────────────────────────────────+//+// Renders the creator's recurring plans on the agent detail page. The detail+// API (api/marketplace/[action].js → handleDetail) returns active tiers in+// `agent.subscription_tiers` and the viewer's active plan in+// `agent.user_subscription`. The current plan is highlighted and switched to a+// "Manage subscription" action; the other tiers are disabled while subscribed+// so a viewer can't accidentally stack two plans on one agent.+function renderSubscriptionTiers(agent) {+ const section = $('subscription-tiers-section');+ const grid = $('tiers-grid');+ if (!section || !grid) return;++ const status = $('d-subs-status');+ if (status) {+ status.textContent = '';+ status.className = 'd-subs-status';+ }++ const tiers = Array.isArray(agent.subscription_tiers) ? agent.subscription_tiers : [];+ if (!tiers.length) {+ section.hidden = true;+ grid.innerHTML = '';+ return;+ }+ section.hidden = false;++ const userSub = agent.user_subscription || null;+ const isOwner = !!(currentUserId && agent.author_id && currentUserId === agent.author_id);++ const sub = $('d-subs-sub');+ if (sub) {+ sub.textContent = isOwner+ ? 'These are the plans subscribers see. Edit them from the agent editor.'+ : userSub+ ? 'You are subscribed — manage your plan below.'+ : 'Back this creator with a recurring plan and unlock everything it includes.';+ }++ grid.innerHTML = tiers+ .map((tier) => {+ const isCurrent = !!(userSub && userSub.plan_id === tier.id);+ const subscribedElsewhere = !!(userSub && !isCurrent);+ const intervalLabel = tier.interval === 'weekly' ? 'week' : 'month';+ const price = Number(tier.price_usd || 0).toFixed(2);+ const perks = Array.isArray(tier.perks) ? tier.perks.filter(Boolean) : [];+ const skillCount = Array.isArray(tier.included_skills) ? tier.included_skills.length : 0;++ const perksHtml = perks.length+ ? `<ul class="tier-perks">${perks.map((p) => `<li>${escapeHtml(p)}</li>`).join('')}</ul>`+ : '<p class="tier-perks-empty">Recurring support for this creator.</p>';++ const skillLine = skillCount+ ? `<div class="tier-skills">Unlocks ${skillCount} included skill${skillCount === 1 ? '' : 's'}</div>`+ : '';++ let btn;+ if (isOwner) {+ btn = '<button class="tier-btn" type="button" disabled>Your plan</button>';+ } else if (isCurrent) {+ btn = `<button class="tier-btn current" type="button" data-sub-manage="${escapeHtml(userSub.id)}">Manage subscription</button>`;+ } else if (subscribedElsewhere) {+ btn = '<button class="tier-btn" type="button" disabled title="Cancel your current plan to switch tiers">Subscribe</button>';+ } else {+ btn = `<button class="tier-btn primary" type="button" data-sub-plan="${escapeHtml(tier.id)}">Subscribe</button>`;+ }++ return `<div class="tier-card${isCurrent ? ' subscribed' : ''}" role="listitem">+ ${isCurrent ? '<div class="tier-badge">Current plan</div>' : ''}+ <div class="tier-name">${escapeHtml(tier.name)}</div>+ <div class="tier-price">$${escapeHtml(price)}<span class="tier-interval">/ ${intervalLabel}</span></div>+ ${skillLine}+ ${perksHtml}+ ${btn}+ </div>`;+ })+ .join('');+}++async function initiateSubscription(planId, btn) {+ if (!currentUserId) {+ location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;+ return;+ }+ if (!detailState?.agent) return;+ const agent = detailState.agent;+ const tier = (agent.subscription_tiers || []).find((t) => t.id === planId);+ if (!tier) return;++ const intervalLabel = tier.interval === 'weekly' ? 'week' : 'month';+ const price = Number(tier.price_usd || 0).toFixed(2);+ const status = $('d-subs-status');++ const confirmed = window.confirm(+ `Subscribe to "${tier.name}" for $${price} per ${intervalLabel}? You'll pay in USDC each ${intervalLabel} and can cancel anytime.`,+ );+ if (!confirmed) return;++ if (btn) {+ btn.disabled = true;+ btn.textContent = 'Subscribing…';+ }+ if (status) {+ status.textContent = '';+ status.className = 'd-subs-status';+ }++ try {+ const r = await apiPostWithCsrf('/api/subscriptions', { plan_id: planId });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) {+ const msg = j.error_description || j.error || 'Could not start subscription. Try again.';+ if (status) {+ status.textContent = msg;+ status.className = 'd-subs-status err';+ }+ if (btn) {+ btn.disabled = false;+ btn.textContent = 'Subscribe';+ }+ return;+ }++ const payUrl = j?.payment?.payUrl || null;+ // Refresh detail so the tier flips to "Current plan" and the others lock.+ await loadDetail(agent.id);++ // Reuse the polished payment success card for the confirmation + the+ // real first-payment link (server builds an x402 checkout intent).+ const overlay = $('payment-modal-overlay');+ if (overlay) overlay.hidden = false;+ renderPaymentSuccess({+ title: 'Subscription started',+ message: payUrl+ ? `You're subscribed to ${tier.name}. Complete your first ${intervalLabel}'s payment to activate every perk.`+ : `You're subscribed to ${tier.name}.`,+ primaryHref: payUrl,+ primaryLabel: payUrl ? 'Complete payment' : null,+ secondaryLabel: 'Done',+ });+ } catch (err) {+ if (status) {+ status.textContent = err.message || 'Network error — try again.';+ status.className = 'd-subs-status err';+ }+ if (btn) {+ btn.disabled = false;+ btn.textContent = 'Subscribe';+ }+ }+}++async function manageSubscription(subId, btn) {+ if (!detailState?.agent) return;+ const agent = detailState.agent;+ const tier = (agent.subscription_tiers || []).find(+ (t) => t.id === agent.user_subscription?.plan_id,+ );+ const tierName = tier?.name || 'this plan';+ const status = $('d-subs-status');++ const confirmed = window.confirm(+ `Cancel your subscription to "${tierName}"? Access to its perks ends right away and you won't be billed again.`,+ );+ if (!confirmed) return;++ if (btn) {+ btn.disabled = true;+ btn.textContent = 'Cancelling…';+ }++ try {+ const token = await getCsrfToken();+ _csrf = null;+ const r = await fetch(`/api/subscriptions/${encodeURIComponent(subId)}`, {+ method: 'DELETE',+ headers: { 'X-CSRF-Token': token },+ credentials: 'include',+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) {+ const msg = j.error_description || j.error || 'Could not cancel. Try again.';+ if (status) {+ status.textContent = msg;+ status.className = 'd-subs-status err';+ }+ if (btn) {+ btn.disabled = false;+ btn.textContent = 'Manage subscription';+ }+ return;+ }+ await loadDetail(agent.id);+ const after = $('d-subs-status');+ if (after) {+ after.textContent = `Your subscription to ${tierName} has been cancelled.`;+ after.className = 'd-subs-status ok';+ }+ } catch (err) {+ if (status) {+ status.textContent = err.message || 'Network error — try again.';+ status.className = 'd-subs-status err';+ }+ if (btn) {+ btn.disabled = false;+ btn.textContent = 'Manage subscription';+ }+ }+}+// editor, non-owner with active price sees a Buy button. Free agents for// non-owners get nothing.function renderAgentSalePanel(agent) {@@ -4780,6 +4990,9 @@ function renderDetail(a, bookmarked) {// Render pricing summary if agent has skill pricesrenderDetailPricingSummary(a);+ // Recurring subscription plans (cards + current-plan state)+ renderSubscriptionTiers(a);+renderAgentSalePanel(a);$('d-profile').textContent = a.system_prompt || a.prompt || '(No profile yet.)';startPreviewSession(a);@@ -5506,6 +5719,16 @@ function bindEvents() {const duration = Number(e.target.dataset.duration);if (agentId && skillName && duration) openTimePassFlow(agentId, skillName, duration, e.target).catch((err) => log.error('[marketplace] time-pass flow', err));}+ const subPlanBtn = e.target.closest('[data-sub-plan]');+ if (subPlanBtn) {+ initiateSubscription(subPlanBtn.dataset.subPlan, subPlanBtn).catch((err) => log.error('[marketplace] subscribe flow', err));+ return;+ }+ const subManageBtn = e.target.closest('[data-sub-manage]');+ if (subManageBtn) {+ manageSubscription(subManageBtn.dataset.subManage, subManageBtn).catch((err) => log.error('[marketplace] manage subscription', err));+ return;+ }});$('payment-modal-close')?.addEventListener('click', closePaymentModal);diff --git a/src/shared/skill-purchase.js b/src/shared/skill-purchase.jsindex f4127c0c5..cc580d067 100644--- a/src/shared/skill-purchase.js+++ b/src/shared/skill-purchase.js@@ -70,6 +70,19 @@ const MODAL_HTML = `<span>Total</span><strong id="payment-price-display"></strong></div>+ <div class="payment-gift" id="payment-gift-area" hidden>+ <label class="payment-gift-toggle">+ <input type="checkbox" id="payment-gift-toggle-input" />+ <span class="payment-gift-toggle-text"><span aria-hidden="true">🎁</span> Gift this skill to someone</span>+ </label>+ <div class="payment-gift-recipient" id="payment-gift-recipient" hidden>+ <input type="text" id="payment-gift-input" class="payment-gift-input"+ placeholder="Recipient username or wallet address"+ autocomplete="off" autocapitalize="off" spellcheck="false"+ aria-label="Recipient username or wallet address" />+ <div class="payment-gift-status" id="payment-gift-status" role="status" aria-live="polite"></div>+ </div>+ </div><div class="payment-wallet-area" id="payment-wallet-area"></div><button class="btn-primary payment-confirm-btn" id="payment-confirm-btn" disabled>Confirm purchase</button><div class="payment-qr" id="payment-qr" aria-live="polite"></div>@@ -90,6 +103,8 @@ function ensureModal() {}$('payment-modal-close')?.addEventListener('click', closePaymentModal);$('payment-confirm-btn')?.addEventListener('click', handlePurchase);+ $('payment-gift-toggle-input')?.addEventListener('change', onGiftToggle);+ $('payment-gift-input')?.addEventListener('input', onGiftInput);$('payment-modal-overlay')?.addEventListener('click', (e) => {if (e.target.id === 'payment-modal-overlay') closePaymentModal();});@@ -189,6 +204,131 @@ function renderPaymentVerifyAgain({ txid, message, retryFn }) {status.querySelector('[data-retry-close]')?.addEventListener('click', closePaymentModal);}+// ── Gift recipient ──────────────────────────────────────────────────────────+//+// Skill purchases can be bought for another user. When the gift toggle is on we+// resolve the typed username / wallet to a real account via /api/users/lookup+// (debounced), gate the confirm button on a valid recipient, and send the+// resolved user id to the server, which re-resolves and records it as the+// purchase's recipient.++let giftState = { enabled: false, active: false, recipient: null, resolving: false, seq: 0 };+let giftLookupTimer = null;++function setGiftStatus(text, kind) {+ const el = $('payment-gift-status');+ if (!el) return;+ el.textContent = text || '';+ el.className = 'payment-gift-status' + (kind ? ' ' + kind : '');+}++function giftLabel(recipient) {+ if (!recipient) return 'They';+ if (recipient.username) return '@' + recipient.username;+ return recipient.display_name || 'They';+}++// The active gift recipient at confirm time, or null for a self-purchase.+function activeGiftRecipient() {+ return giftState.active && giftState.recipient ? giftState.recipient : null;+}++// Single source of truth for whether the confirm button is clickable. All modes+// require a connected wallet; skill gifting additionally requires a resolved,+// non-self recipient.+function refreshConfirmEnabled() {+ const btn = $('payment-confirm-btn');+ if (!btn) return;+ let enabled = !!connectedWallet;+ if (giftState.active && (!giftState.recipient || giftState.resolving)) enabled = false;+ btn.disabled = !enabled;+}++// Reset + show/hide the gift controls. Enabled only for skill flows; assets and+// subscriptions pass enabled:false so the section stays hidden.+function setupGiftUI({ enabled }) {+ clearTimeout(giftLookupTimer);+ giftState = { enabled, active: false, recipient: null, resolving: false, seq: giftState.seq + 1 };+ const area = $('payment-gift-area');+ const toggle = $('payment-gift-toggle-input');+ const recip = $('payment-gift-recipient');+ const input = $('payment-gift-input');+ if (toggle) toggle.checked = false;+ if (input) input.value = '';+ if (recip) recip.hidden = true;+ if (area) area.hidden = !enabled;+ setGiftStatus('');+}++function onGiftToggle() {+ const toggle = $('payment-gift-toggle-input');+ const recip = $('payment-gift-recipient');+ const input = $('payment-gift-input');+ giftState.active = !!toggle?.checked;+ giftState.recipient = null;+ giftState.resolving = false;+ giftState.seq++;+ clearTimeout(giftLookupTimer);+ if (recip) recip.hidden = !giftState.active;+ setGiftStatus('');+ if (giftState.active) {+ if (input) input.value = '';+ input?.focus();+ }+ refreshConfirmEnabled();+}++function onGiftInput() {+ const q = ($('payment-gift-input')?.value || '').trim();+ giftState.recipient = null;+ clearTimeout(giftLookupTimer);+ const seq = ++giftState.seq;+ if (!q) {+ giftState.resolving = false;+ setGiftStatus('');+ refreshConfirmEnabled();+ return;+ }+ giftState.resolving = true;+ setGiftStatus('Looking up…');+ refreshConfirmEnabled();+ giftLookupTimer = setTimeout(() => resolveGiftRecipient(q, seq), 400);+}++async function resolveGiftRecipient(q, seq) {+ let resp, j;+ try {+ resp = await fetch(`/api/users/lookup?q=${encodeURIComponent(q)}`, { credentials: 'include' });+ j = await resp.json().catch(() => ({}));+ } catch {+ if (seq !== giftState.seq) return;+ giftState.resolving = false;+ giftState.recipient = null;+ setGiftStatus('Lookup failed — check your connection.', 'err');+ refreshConfirmEnabled();+ return;+ }+ if (seq !== giftState.seq) return; // a newer keystroke superseded this lookup+ giftState.resolving = false;+ if (!resp.ok) {+ giftState.recipient = null;+ if (resp.status === 404) setGiftStatus('No user found with that username or wallet.', 'err');+ else if (resp.status === 401) setGiftStatus('Sign in to send a gift.', 'err');+ else setGiftStatus(j?.error_description || 'Lookup failed.', 'err');+ refreshConfirmEnabled();+ return;+ }+ const user = j?.data;+ if (!user || user.is_self) {+ giftState.recipient = null;+ setGiftStatus("That's your own account — pick someone else to gift to.", 'err');+ } else {+ giftState.recipient = user;+ setGiftStatus(`🎁 Gifting to ${giftLabel(user)}`, 'ok');+ }+ refreshConfirmEnabled();+}+function closePaymentModal() {const overlay = $('payment-modal-overlay');if (overlay) overlay.hidden = true;@@ -206,7 +346,9 @@ function closePaymentModal() {if (success) { success.hidden = true; success.innerHTML = ''; }setPaymentBadge('');setStatus('');+ setupGiftUI({ enabled: false });pendingAssetPurchase = null;+ pendingSubscription = null;}// ── Wallet plumbing ─────────────────────────────────────────────────────────@@ -265,7 +407,6 @@ function disconnectWallet() {function updateWalletUI() {const walletArea = $('payment-wallet-area');- const confirmBtn = $('payment-confirm-btn');if (!walletArea) return;if (connectedWallet) {@@ -274,7 +415,7 @@ function updateWalletUI() {<p>Connected via <strong>${escapeHtml(connectedWallet.name)}</strong>: ${pk.slice(0, 4)}…${pk.slice(-4)}</p><button class="btn-secondary" id="payment-disconnect-btn">Disconnect</button>`;$('payment-disconnect-btn').addEventListener('click', disconnectWallet);- if (confirmBtn) confirmBtn.disabled = false;+ refreshConfirmEnabled();return;}@@ -308,7 +449,7 @@ function updateWalletUI() {});}$('payment-show-qr')?.addEventListener('click', startQrPurchase);- if (confirmBtn) confirmBtn.disabled = true;+ refreshConfirmEnabled();}// ── CSRF ────────────────────────────────────────────────────────────────────@@ -353,11 +494,62 @@ async function buildSplTransferWithReference({ payer, recipient, mint, amount, rreturn tx;}+function base64ToBytes(b64) {+ const bin = atob(b64);+ const bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ return bytes;+}++// Sign + send a platform-prepared, gasless VersionedTransaction. The platform+// payer is the fee-payer and has already partially signed it server-side, so+// the wallet only adds the buyer's authority signature — the buyer needs no SOL.+async function signAndSendPreparedTx(base64Tx) {+ const { web3 } = await loadSolanaModules();+ const tx = web3.VersionedTransaction.deserialize(base64ToBytes(base64Tx));+ const provider = connectedWallet.provider;+ if (typeof provider.signAndSendTransaction === 'function') {+ const result = await provider.signAndSendTransaction(tx);+ return result?.signature ?? result;+ }+ if (typeof provider.signTransaction === 'function') {+ const signed = await provider.signTransaction(tx);+ return (await getSolanaConnection()).sendRawTransaction(signed.serialize());+ }+ throw new Error('Your wallet cannot sign this transaction.');+}++// Submit the purchase. Prefers the server-prepared gasless transaction (fee+// sponsored by three.ws); falls back to a buyer-pays transfer built client-side+// when no sponsorship is available. Returns the on-chain signature.+async function sendPurchaseTransaction(purchase) {+ if (purchase.transaction) return signAndSendPreparedTx(purchase.transaction);++ const tx = await buildSplTransferWithReference({+ payer: connectedWallet.publicKey,+ recipient: purchase.recipient,+ mint: purchase.currency_mint,+ amount: BigInt(purchase.amount),+ reference: purchase.reference,+ });+ const provider = connectedWallet.provider;+ if (typeof provider.signAndSendTransaction === 'function') {+ const result = await provider.signAndSendTransaction(tx);+ return result?.signature ?? result;+ }+ return provider.sendTransaction(tx, await getSolanaConnection());+}+// ── Server purchase records ─────────────────────────────────────────────────-async function createPendingPurchase(agentId, skill, durationHours = null) {+async function createPendingPurchase(agentId, skill, durationHours = null, buyerPublicKey = null, recipient = null) {const body = { agent_id: agentId, skill };if (durationHours) body.duration_hours = durationHours;+ // Hand the server our wallet pubkey so it can return a gasless, pre-signed+ // transaction (network fee sponsored by the platform).+ if (buyerPublicKey) body.buyer_public_key = buyerPublicKey;+ // Gift: the resolved recipient's user id; the server re-resolves + validates.+ if (recipient) body.recipient = recipient;const r = await apiPostWithCsrf('/api/marketplace/purchase', body);const j = await r.json();if (!r.ok) throw new Error(j.error_description || j.error || 'Failed to create purchase');@@ -403,6 +595,7 @@ export async function openPurchaseFlow(agentId, skill) {if (confirmBtn) confirmBtn.textContent = 'Confirm purchase';const qr = $('payment-qr'); if (qr) qr.innerHTML = '';setStatus('');+ setupGiftUI({ enabled: true });$('payment-modal-overlay').hidden = false;updateWalletUI();}@@ -431,6 +624,7 @@ export async function openTimePassFlow(agentId, skill, durationHours, btn) {$('payment-price-display').textContent = `${human} ${shortMintLabel(price.currency_mint)}`;const qr = $('payment-qr'); if (qr) qr.innerHTML = '';setStatus('');+ setupGiftUI({ enabled: true });$('payment-modal-overlay').hidden = false;updateWalletUI();@@ -497,12 +691,15 @@ export function openAssetPurchaseFlow(asset) {const qr = $('payment-qr'); if (qr) qr.innerHTML = '';setStatus('');+ setupGiftUI({ enabled: false });$('payment-modal-overlay').hidden = false;updateWalletUI();}-async function createPendingAssetPurchase(itemType, itemId) {- const r = await apiPostWithCsrf('/api/marketplace/buy-asset', { item_type: itemType, item_id: itemId });+async function createPendingAssetPurchase(itemType, itemId, buyerPublicKey = null) {+ const body = { item_type: itemType, item_id: itemId };+ if (buyerPublicKey) body.buyer_public_key = buyerPublicKey;+ const r = await apiPostWithCsrf('/api/marketplace/buy-asset', body);const j = await r.json();if (!r.ok) throw new Error(j.error_description || j.error || 'Failed to create purchase');return j.data;@@ -534,6 +731,7 @@ function assetViewTarget(asset) {async function handlePurchase() {const confirmBtn = $('payment-confirm-btn');if (confirmBtn?.dataset.mode === 'asset') return handleAssetPurchase();+ if (confirmBtn?.dataset.mode === 'subscription') return handleSubscription();if (!connectedWallet) { setStatus('Connect a wallet first.', 'err'); return; }const agent = cfg.getAgent();if (!agent) return;@@ -544,9 +742,23 @@ async function handlePurchase() {const agentId = agent.id;const skill = $('payment-skill-name').textContent;const durationHours = confirmBtn.dataset.durationHours ? Number(confirmBtn.dataset.durationHours) : null;+ // Snapshot the gift recipient at click time so a late keystroke can't change+ // who the in-flight purchase is for.+ const giftRecipient = activeGiftRecipient();const onUnlocked = async () => {await cfg.onPurchased(agentId);+ if (giftRecipient) {+ renderPaymentSuccess({+ title: 'Gift sent 🎁',+ message: durationHours+ ? `${giftLabel(giftRecipient)} now has ${durationHours}h access to ${skill} on ${agent.name}. We've let them know.`+ : `${giftLabel(giftRecipient)} now has access to ${skill} on ${agent.name}. We've let them know.`,+ primaryHref: null,+ secondaryLabel: 'Done',+ });+ return;+ }renderPaymentSuccess({title: durationHours ? `${durationHours}h access unlocked` : 'Skill unlocked',message: durationHours@@ -559,12 +771,14 @@ async function handlePurchase() {let purchase;try {- purchase = await createPendingPurchase(agentId, skill, durationHours);+ purchase = await createPendingPurchase(agentId, skill, durationHours, connectedWallet.publicKey.toBase58(), giftRecipient?.id || null);if (purchase.already_owned) {await cfg.onPurchased(agentId);renderPaymentSuccess({- title: 'Already unlocked',- message: `You already have access to ${skill}.`,+ title: giftRecipient ? 'Already owned' : 'Already unlocked',+ message: giftRecipient+ ? `${giftLabel(giftRecipient)} already has access to ${skill}, so there's nothing to gift.`+ : `You already have access to ${skill}.`,primaryHref: null,secondaryLabel: 'Continue',});@@ -578,22 +792,8 @@ async function handlePurchase() {let txid;try {- setStatus('Building transfer…');- const tx = await buildSplTransferWithReference({- payer: connectedWallet.publicKey,- recipient: purchase.recipient,- mint: purchase.currency_mint,- amount: BigInt(purchase.amount),- reference: purchase.reference,- });-- setStatus('Approve in wallet…');- if (typeof connectedWallet.provider.signAndSendTransaction === 'function') {- const result = await connectedWallet.provider.signAndSendTransaction(tx);- txid = result?.signature ?? result;- } else {- txid = await connectedWallet.provider.sendTransaction(tx, await getSolanaConnection());- }+ setStatus(purchase.gasless ? 'Approve in wallet — gas is on us…' : 'Approve in wallet…');+ txid = await sendPurchaseTransaction(purchase);setStatus('Waiting for on-chain confirmation…');await (await getSolanaConnection()).confirmTransaction(txid, 'confirmed');@@ -643,7 +843,7 @@ async function handleAssetPurchase() {let purchase;try {- purchase = await createPendingAssetPurchase(asset.item_type, asset.item_id);+ purchase = await createPendingAssetPurchase(asset.item_type, asset.item_id, connectedWallet.publicKey.toBase58());if (purchase.already_owned) {const target = assetViewTarget(asset);renderPaymentSuccess({@@ -662,22 +862,8 @@ async function handleAssetPurchase() {let txid;try {- setStatus('Building transfer…');- const tx = await buildSplTransferWithReference({- payer: connectedWallet.publicKey,- recipient: purchase.recipient,- mint: purchase.currency_mint,- amount: BigInt(purchase.amount),- reference: purchase.reference,- });-- setStatus('Approve in wallet…');- if (typeof connectedWallet.provider.signAndSendTransaction === 'function') {- const result = await connectedWallet.provider.signAndSendTransaction(tx);- txid = result?.signature ?? result;- } else {- txid = await connectedWallet.provider.sendTransaction(tx, await getSolanaConnection());- }+ setStatus(purchase.gasless ? 'Approve in wallet — gas is on us…' : 'Approve in wallet…');+ txid = await sendPurchaseTransaction(purchase);setStatus('Waiting for on-chain confirmation…');await (await getSolanaConnection()).confirmTransaction(txid, 'confirmed');@@ -732,22 +918,187 @@ async function handleAssetPurchase() {}}+// ── Subscription (agent tier) ───────────────────────────────────────────────+//+// Unlike skills/assets — where the browser builds a single-leg transfer — the+// subscription server returns a fully-built VersionedTransaction (creator + fee+// split, platform pre-signed as fee-payer for gasless UX). The wallet just adds+// the buyer's signature and broadcasts; we then activate via /verify.++let pendingSubscription = null;++/**+ * Open the confirmation modal for subscribing to an agent tier.+ * @param {string} agentId+ * @param {{ id: string, name: string, price_usd: number, interval: string, perks?: string[] }} tier+ */+export async function openSubscribeFlow(agentId, tier) {+ ensureModal();+ const agent = cfg.getAgent();+ if (!agent || agent.id !== agentId) { alert('Agent not loaded; refresh and try again.'); return; }+ if (!tier?.id) { alert('Tier unavailable; refresh and try again.'); return; }++ pendingSubscription = { agentId, tier };+ const cycle = tier.interval === 'weekly' ? 'week' : 'month';+ const price = Number(tier.price_usd);++ setPaymentTitle('Subscribe');+ setPaymentLede('You are starting a subscription to this tier:');+ setPaymentFromLabel('tier on');+ setPaymentBadge(+ `<span class="payment-modal-badge-icon" aria-hidden="true">↻</span><span>Recurring ${cycle}ly billing. The first ${cycle} is charged now; you can cancel anytime.</span>`,+ 'info',+ );+ $('payment-skill-name').textContent = tier.name;+ $('payment-agent-name').textContent = agent.name;+ $('payment-price-display').textContent = `$${price.toFixed(2)} / ${cycle}`;++ const confirmBtn = $('payment-confirm-btn');+ if (confirmBtn) {+ confirmBtn.dataset.mode = 'subscription';+ confirmBtn.textContent = `Subscribe · $${price.toFixed(2)}/${cycle === 'week' ? 'wk' : 'mo'}`;+ confirmBtn.hidden = false;+ }+ const qr = $('payment-qr'); if (qr) qr.innerHTML = '';+ setStatus('');+ setupGiftUI({ enabled: false });+ $('payment-modal-overlay').hidden = false;+ updateWalletUI();+}++async function createSubscriptionCheckout(tierId, buyerPublicKey) {+ const r = await apiPostWithCsrf('/api/subscriptions/subscribe', { tierId, buyerPublicKey });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) {+ if (j.error === 'already_subscribed') throw new Error('You already have an active subscription to this tier.');+ if (j.error === 'creator_wallet_missing') throw new Error('This creator has not set up a payout wallet yet.');+ if (r.status === 401) { location.href = `/login?next=${encodeURIComponent(location.pathname)}`; throw new Error('Sign in to subscribe.'); }+ throw new Error(j.error_description || j.error || 'Failed to start subscription');+ }+ return j.data;+}++// Sign + broadcast a server-built base64 VersionedTransaction with the connected+// wallet, returning the tx signature.+async function signAndSendServerTx(base64) {+ const { web3 } = await loadSolanaModules();+ const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));+ const vtx = web3.VersionedTransaction.deserialize(bytes);+ const provider = connectedWallet.provider;+ if (typeof provider.signAndSendTransaction === 'function') {+ const result = await provider.signAndSendTransaction(vtx);+ return result?.signature ?? result;+ }+ const signed = await provider.signTransaction(vtx);+ return (await getSolanaConnection()).sendRawTransaction(signed.serialize());+}++async function pollSubscriptionVerify(tierId, signature, windowMs = 60_000) {+ const deadline = Date.now() + windowMs;+ while (Date.now() < deadline) {+ const r = await apiPostWithCsrf('/api/subscriptions/verify', { tierId, transactionSignature: signature });+ const j = await r.json().catch(() => ({}));+ if (r.ok && j.data?.success) return true;+ if (r.ok && j.data?.status === 'pending') { await new Promise((res) => setTimeout(res, 2500)); continue; }+ if (r.status === 410) throw new Error('Checkout expired. Please start the subscription again.');+ if (r.status === 409) throw new Error(j.error_description || 'On-chain transfer did not match the quoted amount.');+ throw new Error(j.error_description || j.error || 'Could not activate subscription');+ }+ return false;+}++async function handleSubscription() {+ const confirmBtn = $('payment-confirm-btn');+ const ctx = pendingSubscription;+ if (!ctx) { setStatus('No tier selected.', 'err'); return; }+ if (!connectedWallet) { setStatus('Connect a wallet first.', 'err'); return; }++ const { agentId, tier } = ctx;+ const agent = cfg.getAgent();+ const cycle = tier.interval === 'weekly' ? 'week' : 'month';+ confirmBtn.disabled = true;++ const succeed = () => {+ cfg.onPurchased(agentId).catch(() => {});+ renderPaymentSuccess({+ title: `Subscribed to ${tier.name}`,+ message: `You now have access to ${agent?.name || 'this agent'}'s paid skills. Billed every ${cycle}.`,+ primaryHref: null,+ secondaryLabel: 'Done',+ });+ };++ let checkout;+ try {+ setStatus('Preparing subscription…');+ checkout = await createSubscriptionCheckout(tier.id, connectedWallet.publicKey.toBase58());+ } catch (e) {+ setStatus(e.message, 'err');+ confirmBtn.disabled = false;+ return;+ }++ let txid;+ try {+ setStatus('Approve in wallet…');+ txid = await signAndSendServerTx(checkout.transaction);++ setStatus('Waiting for on-chain confirmation…');+ await (await getSolanaConnection()).confirmTransaction(txid, 'confirmed');++ setStatus('Activating subscription…');+ const ok = await pollSubscriptionVerify(tier.id, txid, 60_000);+ if (!ok) {+ renderPaymentVerifyAgain({+ txid,+ message: "Payment is on-chain but the server hasn't seen it yet. Re-verify below.",+ retryFn: async () => {+ const ok2 = await pollSubscriptionVerify(tier.id, txid, 60_000);+ if (!ok2) throw new Error('Still not confirmed — wait a few seconds and try again.');+ succeed();+ },+ });+ return;+ }+ succeed();+ } catch (e) {+ log.error('[skill-purchase] subscription failed', e);+ if (txid) {+ renderPaymentVerifyAgain({+ txid,+ message: e.message || 'Payment sent but activation failed — re-verify below.',+ retryFn: async () => {+ const ok2 = await pollSubscriptionVerify(tier.id, txid, 60_000);+ if (!ok2) throw new Error('Still not confirmed — wait a few seconds and try again.');+ succeed();+ },+ });+ return;+ }+ setStatus(e.message || 'Subscription failed', 'err');+ confirmBtn.disabled = false;+ }+}+// Mobile-wallet path: render a Solana Pay QR. Buyer scans + signs on phone.async function startQrPurchase() {const agent = cfg.getAgent();if (!agent) return;const agentId = agent.id;const skill = $('payment-skill-name').textContent;+ const giftRecipient = activeGiftRecipient();setStatus('Creating purchase…');let purchase;try {- purchase = await createPendingPurchase(agentId, skill);+ purchase = await createPendingPurchase(agentId, skill, null, null, giftRecipient?.id || null);if (purchase.already_owned) {await cfg.onPurchased(agentId);renderPaymentSuccess({- title: 'Already unlocked',- message: `You already have access to ${skill}.`,+ title: giftRecipient ? 'Already owned' : 'Already unlocked',+ message: giftRecipient+ ? `${giftLabel(giftRecipient)} already has access to ${skill}, so there's nothing to gift.`+ : `You already have access to ${skill}.`,primaryHref: null,secondaryLabel: 'Continue',});@@ -775,16 +1126,22 @@ async function startQrPurchase() {await (QRCode.default ?? QRCode).toCanvas(document.getElementById('payment-qr-canvas'), url.toString(), { width: 240 });}- setStatus('Waiting for payment on your phone…');- const ok = await pollConfirm(purchase.reference, 300_000);- if (ok) {+ const qrSuccess = async () => {await cfg.onPurchased(agentId);renderPaymentSuccess({- title: 'Skill unlocked',- message: `${skill} is now part of your library on ${agent.name}.`,+ title: giftRecipient ? 'Gift sent 🎁' : 'Skill unlocked',+ message: giftRecipient+ ? `${giftLabel(giftRecipient)} now has access to ${skill} on ${agent.name}. We've let them know.`+ : `${skill} is now part of your library on ${agent.name}.`,primaryHref: null,secondaryLabel: 'Done',});+ };++ setStatus('Waiting for payment on your phone…');+ const ok = await pollConfirm(purchase.reference, 300_000);+ if (ok) {+ await qrSuccess();} else {renderPaymentVerifyAgain({txid: null,@@ -792,13 +1149,7 @@ async function startQrPurchase() {retryFn: async () => {const ok2 = await pollConfirm(purchase.reference, 60_000);if (!ok2) throw new Error('Still no confirmation — give it another minute.');- await cfg.onPurchased(agentId);- renderPaymentSuccess({- title: 'Skill unlocked',- message: `${skill} is now part of your library on ${agent.name}.`,- primaryHref: null,- secondaryLabel: 'Done',- });+ await qrSuccess();},});}diff --git a/tasks/onchain-deployment/SOLANA-SIGNERS.md b/tasks/onchain-deployment/SOLANA-SIGNERS.mdindex e3802600d..374b57080 100644--- a/tasks/onchain-deployment/SOLANA-SIGNERS.md+++ b/tasks/onchain-deployment/SOLANA-SIGNERS.md@@ -27,6 +27,7 @@ inventory, the watchdog, the scripts, the cron registration) is done and shipped| coin-treasury | `COIN_TREASURY_SECRET_KEY_B64` | mainnet | base64 (64 bytes) | 0.05 | lottery / reflection distribution txs for launched coins || club-treasury | `CLUB_SOLANA_TREASURY_SECRET_KEY_B64` | mainnet | base64 (64 bytes) | 0.05 | USDC tip-sweep transfers + recipient ATA rent (club-payouts) || platform-treasury | `PLATFORM_TREASURY_KEYPAIR` (`TREASURY_KEYPAIR`) | mainnet | base58 / JSON | 0.05 | SPL withdrawal gas (process-withdrawals cron) |+| marketplace-payer | `MARKETPLACE_PAYER_KEYPAIR` (`PLATFORM_TREASURY_KEYPAIR`) | mainnet | base64 / base58 / JSON | 0.05 | sponsors network fees for **gasless** skill/asset checkout (fee-payer on prepared VersionedTransactions) || a2a-payer | `A2A_PAYER_SOLANA_SECRET` (`A2A_PAYER_SOLANA_PRIVATE_KEY`) | mainnet | base58 | 0.02 | co-signs SPL TransferChecked for A2A mandate settlements || collection-authority | `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` | mainnet + devnet | base58 | 0.02 | creates/manages the three.ws agent NFT collection |diff --git a/tests/agent-monetization.test.js b/tests/agent-monetization.test.jsindex b52d0489d..68014fe18 100644--- a/tests/agent-monetization.test.js+++ b/tests/agent-monetization.test.js@@ -270,6 +270,8 @@ describe('Revenue Attribution', () => {sqlState.queue.push([agent]);// priceFor: agent_skill_prices lookup → no explicit price, falls back to metasqlState.queue.push([]);+ // hasSkillAccess: echo has no canonical agent_skill_prices row → paid:false, x402 path+ sqlState.queue.push([]);// verifyPaid: intent is paid, amount matches default_pricesqlState.queue.push([{@@ -311,6 +313,7 @@ describe('Revenue Attribution', () => {sqlState.queue.push([agent]); // agent lookupsqlState.queue.push([]); // priceFor: agent_skill_prices → no row, use meta+ sqlState.queue.push([]); // hasSkillAccess: no canonical price → paid:false, x402 pathconst { status } = await invoke(x402Handler, {method: 'POST',@@ -330,6 +333,7 @@ describe('Revenue Attribution', () => {// First invoke: intent is paid → succeedssqlState.queue.push([agent]);sqlState.queue.push([]); // priceFor: agent_skill_prices → no row, use meta+ sqlState.queue.push([]); // hasSkillAccess: no canonical price → paid:false, x402 pathsqlState.queue.push([{id: intentId,agent_id: agent.id,@@ -352,6 +356,7 @@ describe('Revenue Attribution', () => {// Second invoke: intent is consumed → verifyPaid finds no 'paid' row → 402sqlState.queue.push([agent]);sqlState.queue.push([]); // priceFor: agent_skill_prices → no row, use meta+ sqlState.queue.push([]); // hasSkillAccess: no canonical price → paid:false, x402 pathsqlState.queue.push([]); // empty result: no 'paid' intent → verifyPaid returns nullconst { status: second } = await invoke(x402Handler, {diff --git a/tests/api/agent-subscription-tiers.test.js b/tests/api/agent-subscription-tiers.test.jsnew file mode 100644index 000000000..1169574ec--- /dev/null+++ b/tests/api/agent-subscription-tiers.test.js@@ -0,0 +1,332 @@+// Prompt 15 — Save & manage subscription tiers API.+//+// /api/agents/:id/tiers is the agent-addressed REST view of the creator's+// subscription tiers (rows in `subscription_plans` scoped to one agent):+//+// GET /api/agents/:id/tiers list active tiers (public)+// POST /api/agents/:id/tiers create tier (owner)+// PUT /api/agents/:id/tiers/:tierId update tier (owner)+// PATCH /api/agents/:id/tiers/:tierId update tier (owner, alias of PUT)+// DELETE /api/agents/:id/tiers/:tierId deactivate tier (owner, soft-delete)+//+// The server is the trust boundary: ownership is checked against+// agent_identities (never the caller), cookie-session mutations require CSRF,+// the body is validated, and a delete is a soft-delete (active=false) that first+// counts active subscribers so paid fans keep access until their period ends.+// DB / auth / CSRF / limiter are mocked so the suite stays offline.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { invoke } from '../_helpers/monetization.js';++// ── Content-addressed SQL mock ───────────────────────────────────────────────+// Classify each query by its text so call order never matters. Handles both the+// tagged-template form sql`…` and the dynamic function form sql(text, params)+// used by the UPDATE path. Every call is recorded for write-path assertions.+let agentRow = null; // agent_identities ownership lookup → { user_id } | null+let tierRows = []; // rows the GET list returns+let existingTier = null; // update/delete existence lookup → { id } | null+let capCount = 0; // active-tier count for the create cap+let subCount = 0; // active subscriber count for delete+let calls = []; // { q, values } for every query, in order++const sqlMock = vi.fn((strings, ...values) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ calls.push({ q, values });++ if (/FROM agent_identities/i.test(q)) {+ return Promise.resolve(agentRow ? [agentRow] : []);+ }+ // Subscriber count joins creator_subscriptions — check before the generic+ // subscription_plans count so it wins.+ if (/count\(\*\)[\s\S]*creator_subscriptions/i.test(q)) {+ return Promise.resolve([{ count: subCount }]);+ }+ if (/count\(\*\)[\s\S]*subscription_plans/i.test(q)) {+ return Promise.resolve([{ count: capCount }]);+ }+ if (/INSERT INTO subscription_plans/i.test(q)) {+ return Promise.resolve([{ id: 'new-tier-id', name: 'Supporter', active: true }]);+ }+ if (/UPDATE subscription_plans SET active = false/i.test(q)) {+ return Promise.resolve(existingTier ? [{ id: existingTier.id }] : []);+ }+ if (/UPDATE subscription_plans SET/i.test(q)) {+ return Promise.resolve(existingTier ? [{ ...existingTier, name: 'Updated' }] : []);+ }+ // Existence probe: selects exactly `id` (the list selects `id, name, …`).+ if (/SELECT id\s+FROM subscription_plans/i.test(q)) {+ return Promise.resolve(existingTier ? [existingTier] : []);+ }+ if (/FROM subscription_plans/i.test(q)) {+ return Promise.resolve(tierRows);+ }+ return Promise.resolve([]);+});+sqlMock.transaction = (queries) => Promise.all(queries);+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));++let sessionUser = null;+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++// CSRF passes by default; flip `csrfOk=false` to exercise the gate. On failure+// the real requireCsrf writes the 403 itself, so the mock does too.+let csrfOk = true;+vi.mock('../../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async (req, res) => {+ if (csrfOk) return true;+ res.statusCode = 403;+ res.end(JSON.stringify({ error: 'csrf_invalid' }));+ return false;+ }),+}));++let rlSuccess = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: rlSuccess, reset: Date.now() + 1000, limit: 60, remaining: 0 })) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const { default: tiers } = await import('../../api/agents/[id]/tiers.js');++const AGENT_ID = '00000000-0000-4000-8000-000000000abc';+const TIER_ID = '00000000-0000-4000-8000-000000000def';+const OWNER = 'owner-uuid';+const base = `/api/agents/${AGENT_ID}/tiers`;+const findCall = (re) => calls.find((c) => re.test(c.q));++beforeEach(() => {+ sqlMock.mockClear();+ calls = [];+ agentRow = { user_id: OWNER };+ tierRows = [];+ existingTier = { id: TIER_ID, active: true };+ capCount = 0;+ subCount = 0;+ sessionUser = null;+ csrfOk = true;+ rlSuccess = true;+});++// ── Path / method guards ──────────────────────────────────────────────────────+describe('routing guards', () => {+ it('400s on a non-UUID agent id', async () => {+ const { status, body } = await invoke(tiers, { method: 'GET', url: '/api/agents/not-a-uuid/tiers' });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('400s on a non-UUID tier id', async () => {+ sessionUser = { id: OWNER };+ const { status, body } = await invoke(tiers, {+ method: 'PUT', url: `${base}/not-a-uuid`, body: { name: 'X' },+ });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('405s on POST with a tier id', async () => {+ sessionUser = { id: OWNER };+ const { status } = await invoke(tiers, { method: 'POST', url: `${base}/${TIER_ID}`, body: {} });+ expect(status).toBe(405);+ });+});++// ── GET — public list ──────────────────────────────────────────────────────────+describe('GET /api/agents/:id/tiers', () => {+ it('returns active tiers without auth', async () => {+ tierRows = [+ { id: TIER_ID, name: 'Supporter', price_usd: '5.00', interval: 'monthly', perks: [], included_skills: ['web-search'], active: true },+ ];+ const { status, body } = await invoke(tiers, { method: 'GET', url: base });+ expect(status).toBe(200);+ expect(body.tiers).toHaveLength(1);+ expect(body.tiers[0].name).toBe('Supporter');+ expect(body.tiers[0].included_skills).toEqual(['web-search']);+ // Only active tiers are queried.+ expect(findCall(/FROM subscription_plans[\s\S]*active = true/i)).toBeDefined();+ });++ it('returns an empty list when the agent has no tiers', async () => {+ const { status, body } = await invoke(tiers, { method: 'GET', url: base });+ expect(status).toBe(200);+ expect(body.tiers).toEqual([]);+ });++ it('429s when rate-limited', async () => {+ rlSuccess = false;+ const { status } = await invoke(tiers, { method: 'GET', url: base });+ expect(status).toBe(429);+ });+});++// ── POST — create ───────────────────────────────────────────────────────────────+describe('POST /api/agents/:id/tiers', () => {+ const body = { name: 'Supporter', price_usd: 5, interval: 'monthly', included_skills: ['web-search'] };++ it('401s when unauthenticated', async () => {+ const { status, body: out } = await invoke(tiers, { method: 'POST', url: base, body });+ expect(status).toBe(401);+ expect(out.error).toBe('unauthorized');+ });++ it('403s when the agent belongs to another user', async () => {+ sessionUser = { id: 'not-the-owner' };+ agentRow = null; // ownership query (scoped to user_id) returns nothing+ const { status, body: out } = await invoke(tiers, { method: 'POST', url: base, body });+ expect(status).toBe(403);+ expect(out.error).toBe('forbidden');+ expect(findCall(/INSERT INTO subscription_plans/i)).toBeUndefined();+ });++ it('403s when the CSRF token is missing/invalid', async () => {+ sessionUser = { id: OWNER };+ csrfOk = false;+ const { status, body: out } = await invoke(tiers, { method: 'POST', url: base, body });+ expect(status).toBe(403);+ expect(out.error).toBe('csrf_invalid');+ });++ it('400s when the price is below the $0.99 minimum', async () => {+ sessionUser = { id: OWNER };+ const { status, body: out } = await invoke(tiers, {+ method: 'POST', url: base, body: { name: 'Cheap', price_usd: 0.5 },+ });+ expect(status).toBe(400);+ expect(out.error).toBe('validation_error');+ expect(findCall(/INSERT INTO subscription_plans/i)).toBeUndefined();+ });++ it('409s when the creator already has 3 active tiers', async () => {+ sessionUser = { id: OWNER };+ capCount = 3;+ const { status, body: out } = await invoke(tiers, { method: 'POST', url: base, body });+ expect(status).toBe(409);+ expect(out.error).toBe('conflict');+ expect(findCall(/INSERT INTO subscription_plans/i)).toBeUndefined();+ });++ it('creates the tier with included_skills for the owner', async () => {+ sessionUser = { id: OWNER };+ const { status, body: out } = await invoke(tiers, { method: 'POST', url: base, body });+ expect(status).toBe(201);+ expect(out.tier).toBeDefined();+ const ins = findCall(/INSERT INTO subscription_plans/i);+ expect(ins).toBeDefined();+ // VALUES (creator_id, agent_id, name, price_usd, interval, perks, included_skills)+ expect(ins.values[0]).toBe(OWNER);+ expect(ins.values[1]).toBe(AGENT_ID);+ expect(ins.values[2]).toBe('Supporter');+ expect(ins.values[3]).toBe(5);+ expect(ins.values[6]).toEqual(['web-search']);+ });++ it('429s when rate-limited', async () => {+ sessionUser = { id: OWNER };+ rlSuccess = false;+ const { status } = await invoke(tiers, { method: 'POST', url: base, body });+ expect(status).toBe(429);+ });+});++// ── PUT / PATCH — update ────────────────────────────────────────────────────────+describe('PUT/PATCH /api/agents/:id/tiers/:tierId', () => {+ const url = `${base}/${TIER_ID}`;++ it('401s when unauthenticated', async () => {+ const { status } = await invoke(tiers, { method: 'PUT', url, body: { price_usd: 9 } });+ expect(status).toBe(401);+ });++ it('404s when the tier does not exist for this agent', async () => {+ sessionUser = { id: OWNER };+ existingTier = null;+ const { status, body: out } = await invoke(tiers, { method: 'PUT', url, body: { price_usd: 9 } });+ expect(status).toBe(404);+ expect(out.error).toBe('not_found');+ });++ it('403s when the CSRF token is missing/invalid', async () => {+ sessionUser = { id: OWNER };+ csrfOk = false;+ const { status } = await invoke(tiers, { method: 'PUT', url, body: { price_usd: 9 } });+ expect(status).toBe(403);+ });++ it('400s when no updatable fields are provided', async () => {+ sessionUser = { id: OWNER };+ const { status, body: out } = await invoke(tiers, { method: 'PUT', url, body: {} });+ expect(status).toBe(400);+ expect(out.error).toBe('validation_error');+ });++ it('updates the tier via PUT', async () => {+ sessionUser = { id: OWNER };+ const { status, body: out } = await invoke(tiers, {+ method: 'PUT', url, body: { name: 'Updated', price_usd: 9, included_skills: ['summarize'] },+ });+ expect(status).toBe(200);+ expect(out.tier).toBeDefined();+ const upd = findCall(/UPDATE subscription_plans SET/i);+ expect(upd).toBeDefined();+ // Dynamic params end with [tierId, creatorId] (see handler).+ expect(upd.values[0]).toContain(TIER_ID);+ expect(upd.values[0]).toContain(OWNER);+ });++ it('also accepts PATCH as an alias', async () => {+ sessionUser = { id: OWNER };+ const { status } = await invoke(tiers, { method: 'PATCH', url, body: { active: false } });+ expect(status).toBe(200);+ expect(findCall(/UPDATE subscription_plans SET/i)).toBeDefined();+ });+});++// ── DELETE — soft-delete ────────────────────────────────────────────────────────+describe('DELETE /api/agents/:id/tiers/:tierId', () => {+ const url = `${base}/${TIER_ID}`;++ it('401s when unauthenticated', async () => {+ const { status } = await invoke(tiers, { method: 'DELETE', url });+ expect(status).toBe(401);+ });++ it('403s for a non-owner', async () => {+ sessionUser = { id: 'not-the-owner' };+ agentRow = null;+ const { status, body: out } = await invoke(tiers, { method: 'DELETE', url });+ expect(status).toBe(403);+ expect(out.error).toBe('forbidden');+ expect(findCall(/UPDATE subscription_plans SET active = false/i)).toBeUndefined();+ });++ it('soft-deletes (active=false), never a hard delete', async () => {+ sessionUser = { id: OWNER };+ const { status, body: out } = await invoke(tiers, { method: 'DELETE', url });+ expect(status).toBe(200);+ expect(out.ok).toBe(true);+ expect(out.active_subscribers).toBe(0);+ expect(findCall(/UPDATE subscription_plans SET active = false/i)).toBeDefined();+ expect(findCall(/DELETE FROM subscription_plans/i)).toBeUndefined();+ });++ it('reports active subscribers who keep access until period end', async () => {+ sessionUser = { id: OWNER };+ subCount = 4;+ const { status, body: out } = await invoke(tiers, { method: 'DELETE', url });+ expect(status).toBe(200);+ expect(out.active_subscribers).toBe(4);+ expect(out.message).toMatch(/4 subscriber/);+ });++ it('404s when the tier does not exist for this agent', async () => {+ sessionUser = { id: OWNER };+ existingTier = null; // soft-delete UPDATE returns nothing+ const { status, body: out } = await invoke(tiers, { method: 'DELETE', url });+ expect(status).toBe(404);+ expect(out.error).toBe('not_found');+ });+});diff --git a/tests/api/dance-tip.test.js b/tests/api/dance-tip.test.jsindex d3cd2af2f..7adfd4119 100644--- a/tests/api/dance-tip.test.js+++ b/tests/api/dance-tip.test.js@@ -248,6 +248,50 @@ describe('buildTicket', () => {expect(ticket.amountAtomics).toBe(null);expect(ticket.asset).toBe(null);});++ it('flags pole styles so the stage turns the dancer into the pole', () => {+ const ticket = buildTicket({+ dancer: '1',+ style: pickStyle('twerk'),+ ticketId: 'tkt-4',+ });+ expect(ticket.dance).toBe('twerk');+ expect(ticket.clip).toBe('twerk');+ expect(ticket.pole).toBe(true);+ // Single-clip pole style — no choreographed chain.+ expect(ticket.sequence).toBeUndefined();+ });++ it('omits the pole flag entirely for free-floor styles', () => {+ const ticket = buildTicket({+ dancer: '1',+ style: pickStyle('rumba'),+ ticketId: 'tkt-5',+ });+ expect(ticket.pole).toBeUndefined();+ });+});++describe('twerk — pole style', () => {+ it('is a single-clip, looping pole style on a real manifest clip', () => {+ const style = STYLES.twerk;+ expect(style).toBeTruthy();+ expect(style.clip).toBe('twerk');+ expect(style.loop).toBe(true);+ expect(style.pole).toBe(true);+ expect(style.sequence).toBeUndefined();+ });++ it('pickStyle surfaces the pole flag', () => {+ expect(pickStyle('twerk').pole).toBe(true);+ // Free-floor + sequence styles report pole: false.+ expect(pickStyle('rumba').pole).toBe(false);+ expect(pickStyle('spin').pole).toBe(false);+ });++ it('is advertised in the input `dance` enum', () => {+ expect(JSON.stringify(BAZAAR_SCHEMA.schema)).toContain('"twerk"');+ });});describe('Bazaar discovery schema', () => {diff --git a/tests/api/forge-free-first.test.js b/tests/api/forge-free-first.test.jsnew file mode 100644index 000000000..f7a059cf1--- /dev/null+++ b/tests/api/forge-free-first.test.js@@ -0,0 +1,231 @@+/**+ * Free-first reconstruct ordering for api/forge.js.+ *+ * Platform stance: a generation must prefer the FREE reconstruct lane over the+ * paid Replicate default — so a forge call never spends on, nor dead-ends+ * against, the paid account while a free lane can serve it. Concretely:+ *+ * • When the native free NVIDIA NIM text→3D lane fails, the request reconstructs+ * the FLUX-synthesized view on the FREE HuggingFace Spaces lane BEFORE ever+ * touching the paid Replicate reconstruct (FORGE_PREFER_FREE, default on).+ * • When every free lane is unavailable and the only one left is the platform's+ * own paid account out of credit, the buyer NEVER sees the vendor's raw+ * "purchase credit / replicate.com/billing" message — that internal billing+ * state is sanitized into an honest "temporarily unavailable".+ *+ * The provider boundaries are stubbed; these assert the endpoint's routing and+ * its error hygiene, with provenance reporting the lane that actually ran.+ */++import { describe, it, expect, vi, beforeAll } from 'vitest';++beforeAll(() => {+ Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ REPLICATE_API_TOKEN: 'test-token',+ NVIDIA_API_KEY: 'test-nvidia-key',+ JWT_SECRET: 'test-jwt-secret-at-least-32-characters-long',+ });+ // No Hunyuan3D worker wired here — keep the reconstruct fallback to HF/Replicate+ // only, so the free-first ordering is the single variable under test.+ delete process.env.GCP_HUNYUAN3D_URL;+ delete process.env.GCP_RECONSTRUCTION_KEY;+ delete process.env.FORGE_PREFER_FREE; // default ON+});++// Free NVIDIA NIM text→3D lane is DOWN this whole suite (mirrors the prod failure+// that started this work: auth ok, invoke errors). Every text prompt therefore+// reaches the reconstruct step, which is what free-first governs.+const nvidiaTextTo3d = vi.fn(async () => {+ throw Object.assign(new Error('TRELLIS completed but returned no GLB artifact'), {+ code: 'provider_error',+ status: 502,+ });+});+vi.mock('../../api/_providers/nvidia.js', () => ({+ createNvidiaProvider: () => ({ textTo3d: nvidiaTextTo3d }),+}));++// FLUX text-to-image (the free reference view) succeeds — the variable under test+// is which RECONSTRUCT lane runs, not image synthesis.+vi.mock('../../api/_mcp3d/text-to-image.js', () => ({+ textToImage: vi.fn(async () => ({ imageUrl: 'https://cdn.example/ref.png', model: 'flux' })),+}));++// Paid Replicate reconstruct. A single module-level spy lets a test assert it was+// NEVER called (free chosen first). By default it is out of credit, exactly like+// the broke prod account — so if a test DOES reach it, the leak path is exercised.+const replicateSubmit = vi.fn(async () => {+ throw Object.assign(+ new Error(+ 'You have insufficient credit to run this model. Go to https://replicate.com/account/billing#billing to purchase credit.',+ ),+ { code: 'provider_error', status: 502, providerStatus: 402 },+ );+});+vi.mock('../../api/_providers/replicate.js', () => ({+ createRegenProvider: () => ({ submit: replicateSubmit }),+}));++// Free HuggingFace Spaces lane. createRegenProvider throws when HF_TOKEN is unset+// (mirrors the real provider's gating), so the lane is only available where a+// token is configured. submit() blocks and packs the GLB; status() echoes it.+const hfSubmit = vi.fn(async () => ({ extJobId: 'hf-packed-job' }));+const hfStatus = vi.fn(async () => ({ status: 'done', resultGlbUrl: 'https://cdn.example/hf.glb' }));+vi.mock('../../api/_providers/huggingface.js', () => ({+ createRegenProvider: () => {+ if (!process.env.HF_TOKEN) {+ throw Object.assign(new Error('HF_TOKEN env var is required'), {+ code: 'provider_unconfigured',+ status: 501,+ });+ }+ return { submit: hfSubmit, status: hfStatus };+ },+}));++vi.mock('../../api/_lib/forge-store.js', () => ({+ hashClient: (v) => `client:${v || 'anon'}`,+ hashIp: (v) => `ip:${v}`,+ createCreation: vi.fn(async () => 'creation-1'),+ materializeCreation: vi.fn(async ({ glbUrl }) => ({ id: 'creation-1', glbUrl })),+ markFailed: vi.fn(async () => {}),+ findByJob: vi.fn(async () => null),+}));++vi.mock('../../api/_lib/forge-image-validate.js', () => ({+ validateForgeImage: vi.fn(async () => ({ ok: true })),+}));++vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ limits: {+ ...actual.limits,+ mcp3dGenerate: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ mcp3dGenerateFree: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ mcp3dGenerateFreeTiered: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ },+ clientIp: () => '203.0.113.11',+ };+});++const { default: handler } = await import('../../api/forge.js');++function makeReq(body) {+ return {+ method: 'POST',+ url: '/api/forge',+ headers: { 'content-type': 'application/json', 'x-forge-client': 'tester' },+ on(event, cb) {+ if (event === 'data') cb(Buffer.from(JSON.stringify(body)));+ if (event === 'end') cb();+ },+ };+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(name, value) {+ this.headers[String(name).toLowerCase()] = value;+ },+ end(body) {+ this.body = body ? JSON.parse(body) : null;+ },+ };+}++describe('forge free-first reconstruct ordering', () => {+ it('reconstructs a text prompt on the FREE HuggingFace lane before ever touching paid Replicate', async () => {+ process.env.HF_TOKEN = 'test-hf-token';+ nvidiaTextTo3d.mockClear();+ replicateSubmit.mockClear();+ hfSubmit.mockClear();+ try {+ const req = makeReq({ prompt: 'a red ceramic mug', tier: 'standard', path: 'image' });+ const res = makeRes();+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.body.status).toBe('done');+ expect(res.body.backend).toBe('huggingface');+ expect(res.body.mode).toBe('text_to_3d');+ expect(res.body.glb_url).toBe('https://cdn.example/hf.glb');+ // NVIDIA NIM was attempted first (and failed), then the FREE HF lane served+ // it — the paid Replicate reconstruct was NEVER invoked.+ expect(nvidiaTextTo3d).toHaveBeenCalled();+ expect(hfSubmit).toHaveBeenCalled();+ expect(replicateSubmit).not.toHaveBeenCalled();+ } finally {+ delete process.env.HF_TOKEN;+ }+ });++ it('prefers the free HF lane for an image upload too (no paid Replicate call)', async () => {+ process.env.HF_TOKEN = 'test-hf-token';+ replicateSubmit.mockClear();+ hfSubmit.mockClear();+ try {+ const req = makeReq({+ image_urls: ['https://cdn.example/photo.png'],+ tier: 'standard',+ path: 'image',+ skip_validation: true,+ });+ const res = makeRes();+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.body.status).toBe('done');+ expect(res.body.backend).toBe('huggingface');+ expect(res.body.mode).toBe('image_to_3d');+ expect(hfSubmit).toHaveBeenCalled();+ expect(replicateSubmit).not.toHaveBeenCalled();+ } finally {+ delete process.env.HF_TOKEN;+ }+ });++ it('sanitizes the paid-lane "insufficient credit" billing leak into an honest unavailable state', async () => {+ // No free reconstruct lane (HF_TOKEN unset) and the paid Replicate account is+ // out of credit — the buyer must never see the vendor billing message.+ delete process.env.HF_TOKEN;+ replicateSubmit.mockClear();+ const req = makeReq({ prompt: 'a red ceramic mug', tier: 'standard', path: 'image' });+ const res = makeRes();+ await handler(req, res);++ expect(replicateSubmit).toHaveBeenCalled(); // free lane unavailable → fell to paid+ expect(res.statusCode).toBe(503);+ expect(res.body.error).toBe('generation_unavailable');+ expect(res.body.message).not.toMatch(/credit|replicate|billing|insufficient/i);+ expect(res.headers['retry-after']).toBe('30');+ });++ it('restores the paid-default ORDER when FORGE_PREFER_FREE=false (Replicate tried first)', async () => {+ // The flag flips ORDER, not availability. With free-first OFF the paid+ // Replicate default is attempted FIRST; HF still serves as the post-failure+ // fallback (so the request doesn't dead-end), but only after Replicate is hit.+ process.env.HF_TOKEN = 'test-hf-token';+ process.env.FORGE_PREFER_FREE = 'false';+ replicateSubmit.mockClear();+ hfSubmit.mockClear();+ try {+ const req = makeReq({ prompt: 'a red ceramic mug', tier: 'standard', path: 'image' });+ const res = makeRes();+ await handler(req, res);++ // Replicate WAS tried first (legacy ordering) — contrast with the free-first+ // test where it is never called. HF then served it as the existing fallback.+ expect(replicateSubmit).toHaveBeenCalled();+ expect(res.body.backend).toBe('huggingface');+ } finally {+ delete process.env.HF_TOKEN;+ delete process.env.FORGE_PREFER_FREE;+ }+ });+});diff --git a/tests/api/gasless-tx.test.js b/tests/api/gasless-tx.test.jsnew file mode 100644index 000000000..31a1d5175--- /dev/null+++ b/tests/api/gasless-tx.test.js@@ -0,0 +1,122 @@+// Unit tests for the gasless (platform-sponsored) purchase transaction builder.+//+// Runs fully offline: real @solana/web3.js + @solana/spl-token, a fake RPC+// connection that returns a fixed blockhash, and `decimals` passed in so no+// on-chain getMint call is needed. Proves the platform is the fee-payer, that+// it pre-signs, that the buyer's authority is an unsigned slot, and that the+// fee split / reference key land in the compiled message.++import { describe, it, expect, beforeEach } from 'vitest';+import { Keypair, PublicKey, VersionedTransaction } from '@solana/web3.js';++import {+ buildGaslessPurchaseTx,+ resolveMarketplacePayer,+ _resetMarketplacePayerCache,+} from '../../api/_lib/solana/gasless-tx.js';++const PAYER = Keypair.generate();+const BUYER = Keypair.generate();+const SELLER = Keypair.generate();+const TREASURY = Keypair.generate();+const MINT = Keypair.generate(); // stand-in SPL mint+const REFERENCE = Keypair.generate().publicKey;++// A valid base58 32-byte string to stand in for a recent blockhash.+const FAKE_BLOCKHASH = Keypair.generate().publicKey.toBase58();+const fakeConnection = {+ getLatestBlockhash: async () => ({ blockhash: FAKE_BLOCKHASH, lastValidBlockHeight: 1 }),+};++function setPayerEnv() {+ process.env.MARKETPLACE_PAYER_KEYPAIR = Buffer.from(PAYER.secretKey).toString('base64');+ _resetMarketplacePayerCache();+}++function clearPayerEnv() {+ delete process.env.MARKETPLACE_PAYER_KEYPAIR;+ delete process.env.PLATFORM_TREASURY_KEYPAIR;+ delete process.env.TREASURY_KEYPAIR;+ _resetMarketplacePayerCache();+}++const baseArgs = {+ connection: fakeConnection,+ buyerPublicKey: BUYER.publicKey.toBase58(),+ recipient: SELLER.publicKey.toBase58(),+ mint: MINT.publicKey.toBase58(),+ reference: REFERENCE.toBase58(),+ decimals: 6,+};++describe('buildGaslessPurchaseTx', () => {+ beforeEach(() => setPayerEnv());++ it('returns null when no payer keypair is configured', async () => {+ clearPayerEnv();+ const out = await buildGaslessPurchaseTx({ ...baseArgs, creatorAtomics: 1_000_000n });+ expect(out).toBeNull();+ });++ it('makes the platform payer the fee-payer and pre-signs it', async () => {+ const out = await buildGaslessPurchaseTx({ ...baseArgs, creatorAtomics: 1_000_000n });+ expect(out).not.toBeNull();+ expect(out.gasless).toBe(true);+ expect(out.feePayer).toBe(PAYER.publicKey.toBase58());++ const tx = VersionedTransaction.deserialize(Buffer.from(out.transaction, 'base64'));+ // Fee-payer is always the first static account key.+ expect(tx.message.staticAccountKeys[0].equals(PAYER.publicKey)).toBe(true);+ // The payer's signature slot is filled; the buyer's is still all-zero.+ const payerSig = tx.signatures[0];+ expect(payerSig.some((b) => b !== 0)).toBe(true);+ });++ it('leaves the buyer authority as an unsigned required signer', async () => {+ const out = await buildGaslessPurchaseTx({ ...baseArgs, creatorAtomics: 1_000_000n });+ const tx = VersionedTransaction.deserialize(Buffer.from(out.transaction, 'base64'));+ const keys = tx.message.staticAccountKeys.map((k) => k.toBase58());+ const buyerIdx = keys.indexOf(BUYER.publicKey.toBase58());+ expect(buyerIdx).toBeGreaterThan(0); // present, but not the fee-payer+ expect(buyerIdx).toBeLessThan(tx.message.header.numRequiredSignatures); // still a signer+ // Only the payer has signed so far.+ expect(tx.signatures[buyerIdx].every((b) => b === 0)).toBe(true);+ });++ it('includes the Solana Pay reference key in the message', async () => {+ const out = await buildGaslessPurchaseTx({ ...baseArgs, creatorAtomics: 1_000_000n });+ const tx = VersionedTransaction.deserialize(Buffer.from(out.transaction, 'base64'));+ expect(tx.message.staticAccountKeys.some((k) => k.equals(REFERENCE))).toBe(true);+ });++ it('adds a second transfer leg only when a platform fee applies', async () => {+ const single = await buildGaslessPurchaseTx({ ...baseArgs, creatorAtomics: 1_000_000n });+ const txSingle = VersionedTransaction.deserialize(Buffer.from(single.transaction, 'base64'));+ expect(txSingle.message.compiledInstructions).toHaveLength(1);++ const split = await buildGaslessPurchaseTx({+ ...baseArgs,+ creatorAtomics: 900_000n,+ platformFeeAtomics: 100_000n,+ platformFeeWallet: TREASURY.publicKey.toBase58(),+ });+ const txSplit = VersionedTransaction.deserialize(Buffer.from(split.transaction, 'base64'));+ expect(txSplit.message.compiledInstructions).toHaveLength(2);+ // The treasury fee wallet's ATA owner is present in the account keys.+ expect(txSplit.message.staticAccountKeys.length).toBeGreaterThan(+ txSingle.message.staticAccountKeys.length,+ );+ });+});++describe('resolveMarketplacePayer', () => {+ it('falls back to PLATFORM_TREASURY_KEYPAIR when the dedicated var is unset', async () => {+ clearPayerEnv();+ process.env.PLATFORM_TREASURY_KEYPAIR = Buffer.from(PAYER.secretKey).toString('base64');+ _resetMarketplacePayerCache();+ const kp = await resolveMarketplacePayer();+ expect(kp).not.toBeNull();+ expect(kp.publicKey.equals(PAYER.publicKey)).toBe(true);+ clearPayerEnv();+ });+});diff --git a/tests/api/has-skill-access.test.js b/tests/api/has-skill-access.test.jsnew file mode 100644index 000000000..00765e5e9--- /dev/null+++ b/tests/api/has-skill-access.test.js@@ -0,0 +1,160 @@+// Unit tests for the server-side access-control gate, hasSkillAccess().+//+// This is the authoritative "may user X execute skill Y on agent Z?" check used+// by the skill execution endpoint. It grants access through any one of: free+// skill, confirmed purchase, flat agent subscription, creator-tier subscription+// whose included_skills covers the skill, or an active trial — checked in that+// priority order so a trial is never burned when something stronger applies.++import { describe, it, expect, beforeEach, vi } from 'vitest';++// db.js is mocked with an ordered queue: each `sql\`...\`` shifts the next row+// set. hasSkillAccess issues its queries in a fixed order — price, purchase,+// flat subscription, tier subscription — so tests push exactly what each path+// will read.+const sqlState = { queue: [], calls: [] };++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: strings.join('?'), values });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ }),+}));++const { hasSkillAccess, consumeTrialUse } = await import('../../api/_lib/skill-access.js');++const USER = 'user-1';+const AGENT = 'agent-1';+const SKILL = 'translate';+const PRICE = { skill: SKILL, amount: 1000, currency_mint: 'USDC', chain: 'solana' };++beforeEach(() => {+ sqlState.queue = [];+ sqlState.calls = [];+});++describe('hasSkillAccess', () => {+ it('allows a free skill (no active price row)', async () => {+ sqlState.queue.push([]); // price lookup → none+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toEqual({ paid: false, owned: true });+ expect(sqlState.calls).toHaveLength(1); // short-circuits after price lookup+ });++ it('denies a priced skill for an anonymous (no userId) caller', async () => {+ sqlState.queue.push([PRICE]);+ const r = await hasSkillAccess(null, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: false, reason: 'not_purchased' });+ expect(r.price).toEqual(PRICE);+ expect(sqlState.calls).toHaveLength(1); // no purchase/sub queries without a user+ });++ it('allows a confirmed one-time purchase without touching subscriptions', async () => {+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([{ status: 'confirmed', valid_until: null, trial_remaining: null }]);+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: true });+ expect(r.via_subscription).toBeUndefined();+ expect(r.trial).toBeUndefined();+ // price + purchase only — subscriptions are not consulted once owned.+ expect(sqlState.calls).toHaveLength(2);+ });++ it('honours a confirmed time-pass that is still valid', async () => {+ const future = new Date(Date.now() + 3600_000).toISOString();+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([{ status: 'confirmed', valid_until: future }]);+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: true });+ });++ it('denies an expired time-pass when no subscription covers the skill', async () => {+ const past = new Date(Date.now() - 3600_000).toISOString();+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([{ status: 'confirmed', valid_until: past }]);+ sqlState.queue.push([]); // flat subscription → none+ sqlState.queue.push([]); // tier subscription → none+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: false, reason: 'expired' });+ });++ it('allows access via a flat agent-level subscription', async () => {+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([]); // no purchase+ sqlState.queue.push([{ id: 'flat-sub' }]); // flat subscription active+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: true, via_subscription: true });+ });++ it('allows access via a creator tier whose included_skills covers the skill', async () => {+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([]); // no purchase+ sqlState.queue.push([]); // no flat subscription+ sqlState.queue.push([{ id: 'tier-sub' }]); // tier with skill in included_skills+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: true, via_subscription: true });+ });++ it('denies when a tier subscription exists but does not include this skill', async () => {+ // The tier query filters by `skill = ANY(included_skills)`, so a tier that+ // omits the skill simply returns no row.+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([]); // no purchase+ sqlState.queue.push([]); // no flat subscription+ sqlState.queue.push([]); // tier query → skill not in any included_skills+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: false, reason: 'not_purchased' });+ });++ it('allows an active trial with remaining uses', async () => {+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([{ status: 'trial', trial_remaining: 2 }]);+ sqlState.queue.push([]); // no flat subscription+ sqlState.queue.push([]); // no tier subscription+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: true, trial: true, trial_remaining: 2 });+ });++ it('denies an exhausted trial', async () => {+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([{ status: 'trial', trial_remaining: 0 }]);+ sqlState.queue.push([]); // no flat subscription+ sqlState.queue.push([]); // no tier subscription+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: false, reason: 'trial_exhausted' });+ });++ it('prefers a subscription over burning a trial', async () => {+ // A user holding both a trial and a flat subscription is granted access via+ // the subscription — the trial row is left untouched.+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([{ status: 'trial', trial_remaining: 1 }]);+ sqlState.queue.push([{ id: 'flat-sub' }]); // flat subscription active+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: true, via_subscription: true });+ expect(r.trial).toBeUndefined();+ });++ it('denies when priced and the user has no purchase or subscription', async () => {+ sqlState.queue.push([PRICE]);+ sqlState.queue.push([]); // no purchase+ sqlState.queue.push([]); // no flat subscription+ sqlState.queue.push([]); // no tier subscription+ const r = await hasSkillAccess(USER, AGENT, SKILL);+ expect(r).toMatchObject({ paid: true, owned: false, reason: 'not_purchased' });+ });+});++describe('consumeTrialUse', () => {+ it('returns the decremented remaining count', async () => {+ sqlState.queue.push([{ trial_remaining: 1 }]);+ const remaining = await consumeTrialUse(USER, AGENT, SKILL);+ expect(remaining).toBe(1);+ });++ it('returns null when no trial row matches', async () => {+ sqlState.queue.push([]); // UPDATE … RETURNING matched nothing+ const remaining = await consumeTrialUse(USER, AGENT, SKILL);+ expect(remaining).toBeNull();+ });+});diff --git a/tests/api/marketplace-agent-detail-prices.test.js b/tests/api/marketplace-agent-detail-prices.test.jsindex 1e881f6ab..808b03447 100644--- a/tests/api/marketplace-agent-detail-prices.test.js+++ b/tests/api/marketplace-agent-detail-prices.test.js@@ -45,6 +45,17 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({// null, but mock it so the test never depends on R2 env config.vi.mock('../../api/_lib/r2.js', () => ({ publicUrl: (k) => (k ? `https://cdn.test/${k}` : null) }));+// Force the skill-price cache to always miss → every detail read re-queries the+// (mocked) DB. Without this, the module-level cache would carry case 1's prices+// into case 2 (these cases reuse one AGENT_ID with different active prices), so+// the cache mock is what keeps each case isolated. The caching/invalidation+// behaviour itself is covered directly in skill-price-cache.test.js.+vi.mock('../../api/_lib/cache.js', () => ({+ cacheGet: vi.fn(async () => null),+ cacheSet: vi.fn(async () => {}),+ cacheDel: vi.fn(async () => {}),+}));+const { default: router } = await import('../../api/marketplace/[action].js');// $THREE — the only coin this platform references.diff --git a/tests/api/marketplace-agent-detail-subscriptions.test.js b/tests/api/marketplace-agent-detail-subscriptions.test.jsnew file mode 100644index 000000000..12973f7a9--- /dev/null+++ b/tests/api/marketplace-agent-detail-subscriptions.test.js@@ -0,0 +1,172 @@+// GET /api/marketplace/agents/:id must surface the creator's active+// subscription tiers and the signed-in viewer's current subscription so the+// detail page can render the "Subscribe for exclusive perks" section and mark+// the plan the viewer already holds.+//+// handleDetail() reads active rows from subscription_plans (scoped to the+// agent) and the viewer's active creator_subscriptions row. These tests pin+// that contract from the outside — driving the real router default export with+// DB / auth / rate-limit / r2 / cache mocked so the suite stays offline:+//+// • active tiers → agent.subscription_tiers[] (cheapest first, price_usd numeric)+// • a subscribed viewer → agent.user_subscription = { id, plan_id, … }+// • no tiers and no subscription → [] and null (never absent/undefined)+// • a missing subscription_plans table (pre-migration) degrades to [] / null,+// it never 500s the whole detail read++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { makeReq, makeRes } from '../_helpers/monetization.js';++const AGENT_ID = '11111111-2222-4333-8444-555555555555';+const USER_ID = 'viewer-uuid';+const PLAN_BASIC = 'aaaaaaaa-1111-4111-8111-111111111111';+const PLAN_PRO = 'bbbbbbbb-2222-4222-8222-222222222222';+const SUB_ID = 'cccccccc-3333-4333-8333-333333333333';++// ── Content-addressed SQL mock ───────────────────────────────────────────────+// Classify by query text so call order never matters. The creator_subscriptions+// query JOINs subscription_plans, so it MUST be matched before the plain+// subscription_plans (tiers) query or the tiers branch would swallow it.+let agentRow = null;+let activePrices = [];+let purchasedRows = [];+let tierRows = [];+let subRows = [];+let tiersThrowUndefinedTable = false;++const sqlMock = vi.fn((strings) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (/FROM agent_skill_prices/i.test(q)) return Promise.resolve(activePrices);+ if (/FROM agent_identities/i.test(q)) return Promise.resolve(agentRow ? [agentRow] : []);+ if (/FROM skill_purchases/i.test(q)) return Promise.resolve(purchasedRows);+ if (/FROM agent_bookmarks/i.test(q)) return Promise.resolve([]);+ if (/FROM creator_subscriptions/i.test(q)) {+ if (tiersThrowUndefinedTable) {+ return Promise.reject(Object.assign(new Error('relation does not exist'), { code: '42P01' }));+ }+ return Promise.resolve(subRows);+ }+ if (/FROM subscription_plans/i.test(q)) {+ if (tiersThrowUndefinedTable) {+ return Promise.reject(Object.assign(new Error('relation does not exist'), { code: '42P01' }));+ }+ return Promise.resolve(tierRows);+ }+ return Promise.resolve([]);+});+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));++// Signed-in viewer for every probe.+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => ({ id: USER_ID })),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { widgetRead: vi.fn(async () => ({ success: true, reset: Date.now() + 1000, limit: 60, remaining: 59 })) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++vi.mock('../../api/_lib/r2.js', () => ({ publicUrl: (k) => (k ? `https://cdn.test/${k}` : null) }));++// Always-miss cache so getSkillPrices re-queries the mocked DB each read.+vi.mock('../../api/_lib/cache.js', () => ({+ cacheGet: vi.fn(async () => null),+ cacheSet: vi.fn(async () => {}),+ cacheDel: vi.fn(async () => {}),+}));++const { default: router } = await import('../../api/marketplace/[action].js');++function detailRow(overrides = {}) {+ return {+ id: AGENT_ID,+ name: 'Polyglot',+ description: 'Translates and summarizes.',+ category: 'translation',+ tags: ['translate'],+ skills: ['translate', 'summarize'],+ user_id: 'owner-uuid',+ is_published: true,+ thumbnail_key: null,+ avatar_storage_key: null,+ avatar_visibility: 'public',+ asset_price_amount: null,+ system_prompt: 'You translate.',+ greeting: 'Hola',+ capabilities: {},+ rating_avg: 0,+ rating_count: 0,+ ...overrides,+ };+}++async function getDetail(id = AGENT_ID) {+ const req = makeReq({ method: 'GET', url: `/api/marketplace/agents/${id}` });+ const res = makeRes();+ await router(req, res);+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null, headers: res.headers };+}++beforeEach(() => {+ sqlMock.mockClear();+ agentRow = detailRow();+ activePrices = [];+ purchasedRows = [];+ tierRows = [];+ subRows = [];+ tiersThrowUndefinedTable = false;+});++describe('GET /api/marketplace/agents/:id — subscription tiers', () => {+ it('returns active tiers in subscription_tiers with price_usd normalised to a number', async () => {+ // numeric(8,2) arrives from postgres as a string — the handler coerces it.+ tierRows = [+ { id: PLAN_BASIC, name: 'Supporter', price_usd: '5.00', interval: 'monthly', perks: ['Priority replies'], included_skills: ['translate'] },+ { id: PLAN_PRO, name: 'Pro', price_usd: '20.00', interval: 'monthly', perks: ['Everything in Supporter', 'Early access'], included_skills: ['translate', 'summarize'] },+ ];++ const { status, body } = await getDetail();+ expect(status).toBe(200);++ const tiers = body.data.agent.subscription_tiers;+ expect(Array.isArray(tiers)).toBe(true);+ expect(tiers).toHaveLength(2);+ expect(tiers[0]).toMatchObject({ id: PLAN_BASIC, name: 'Supporter', interval: 'monthly' });+ expect(tiers[0].price_usd).toBe(5); // number, not "5.00"+ expect(typeof tiers[0].price_usd).toBe('number');+ expect(tiers[0].perks).toEqual(['Priority replies']);+ expect(tiers[1].included_skills).toEqual(['translate', 'summarize']);+ });++ it('marks the viewer current subscription in user_subscription', async () => {+ tierRows = [{ id: PLAN_BASIC, name: 'Supporter', price_usd: '5.00', interval: 'monthly', perks: [], included_skills: [] }];+ const periodEnd = '2026-07-18T00:00:00.000Z';+ subRows = [{ id: SUB_ID, plan_id: PLAN_BASIC, status: 'active', current_period_end: periodEnd }];++ const { body } = await getDetail();+ const sub = body.data.agent.user_subscription;+ expect(sub).toMatchObject({ id: SUB_ID, plan_id: PLAN_BASIC, status: 'active' });+ expect(sub.current_period_end).toBe(periodEnd);+ });++ it('returns [] tiers and null user_subscription when none exist (never absent)', async () => {+ const { body } = await getDetail();+ expect(body.data.agent.subscription_tiers).toEqual([]);+ expect(body.data.agent.user_subscription).toBeNull();+ });++ it('serves authenticated reads with a private cache so viewer state never leaks', async () => {+ const { headers } = await getDetail();+ expect(headers['cache-control']).toMatch(/private/);+ });++ it('degrades to [] / null (not 500) when the subscription tables are missing', async () => {+ tiersThrowUndefinedTable = true;+ const { status, body } = await getDetail();+ expect(status).toBe(200);+ expect(body.data.agent.subscription_tiers).toEqual([]);+ expect(body.data.agent.user_subscription).toBeNull();+ });+});diff --git a/tests/api/monetization-service.test.js b/tests/api/monetization-service.test.jsnew file mode 100644index 000000000..199722e92--- /dev/null+++ b/tests/api/monetization-service.test.js@@ -0,0 +1,323 @@+// Unit tests for MonetizationService — the single seam the monetization API+// handlers call through. The lower-level primitives it orchestrates (payout+// resolution, on-chain confirmation, access checks, fee math, balance+// accounting) have their own suites, so here they are mocked: these tests pin+// the service's own business rules — ownership gating, the atomic price replace,+// the already-owned / idempotent purchase paths, error → status mapping, and the+// creator-sales rollup.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// ── Content-addressed SQL mock ───────────────────────────────────────────────+// Classify each tagged-template query by its text and answer from `state`, so+// neither call order nor the lazy `sql`null`` time-window fragment can desync a+// queue. Every call is recorded for write-path assertions.+const state = {+ agent: null, // agent_identities ownership lookup → { id, user_id } | null+ price: null, // single-skill agent_skill_prices lookup → row | null+ prices: [], // active price list+ existing: null, // active-access (confirmed/trial) row | null+ pending: null, // reusable pending row | null+ inserted: null, // INSERT ... RETURNING row+ confirmRow: null, // confirm lookup row | null+ royalty: [], // royalty_ledger rows+ assets: [], // asset_purchases rows+ assetsThrow: false, // simulate the asset_purchases table not existing yet+};+let calls = [];++function respond(q) {+ if (/FROM skill_purchases sp/i.test(q) && /LEFT JOIN agent_skill_prices/i.test(q))+ return state.confirmRow ? [state.confirmRow] : [];+ if (/SELECT id, user_id\s+FROM agent_identities/i.test(q)) return state.agent ? [state.agent] : [];+ if (/FROM agent_skill_prices/i.test(q) && /AND skill =/i.test(q)) return state.price ? [state.price] : [];+ if (/SELECT skill, amount/i.test(q) && /FROM agent_skill_prices/i.test(q)) return state.prices;+ if (/FROM skill_purchases/i.test(q) && /status IN \('confirmed', 'trial'\)/i.test(q))+ return state.existing ? [state.existing] : [];+ if (/FROM skill_purchases/i.test(q) && /status = 'pending'/i.test(q))+ return state.pending ? [state.pending] : [];+ if (/INSERT INTO skill_purchases/i.test(q)) return state.inserted ? [state.inserted] : [];+ if (/FROM royalty_ledger/i.test(q)) return state.royalty;+ if (/FROM asset_purchases/i.test(q)) return state.assets;+ return [];+}++const sqlMock = vi.fn((strings, ...values) => {+ const q = Array.isArray(strings) ? strings.join(' ? ') : String(strings);+ calls.push({ q, values });+ if (state.assetsThrow && /FROM asset_purchases/i.test(q)) {+ return Promise.reject(Object.assign(new Error('relation "asset_purchases" does not exist'), { code: '42P01' }));+ }+ return Promise.resolve(respond(q));+});+sqlMock.transaction = vi.fn((queries) => Promise.all(queries));++// Mock db.js so importing the service never reaches Neon/env config — the+// service's own queries run through the injected sqlMock instead.+vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));++// ── Mock the lower-level helpers the service orchestrates ─────────────────────+const purchaseConfirm = {+ confirmSkillPurchase: vi.fn(async () => ({ status: 'confirmed', tx_signature: 'SIG' })),+ resolvePayoutAddress: vi.fn(async () => 'PAYOUT'),+ logEvent: vi.fn(async () => {}),+};+vi.mock('../../api/_lib/purchase-confirm.js', () => purchaseConfirm);++const skillAccess = { hasSkillAccess: vi.fn(async () => ({ paid: true, owned: true, price: { skill: 'echo' } })) };+vi.mock('../../api/_lib/skill-access.js', () => skillAccess);++const monetization = { getAvailableBalance: vi.fn(async () => ({ earned: 100, withdrawn: 0, pending: 0, available: 100 })) };+vi.mock('../../api/_lib/monetization.js', () => monetization);++const platformFee = {+ resolveMarketplaceFee: vi.fn(async () => ({ bps: 250, feeAtomics: 25000n, recipient: { toBase58: () => 'TREASURY' } })),+};+vi.mock('../../api/_lib/marketplace-platform-fee.js', () => platformFee);++const priceCache = { invalidateSkillPriceCache: vi.fn(() => {}) };+vi.mock('../../api/_lib/skill-price-cache.js', () => priceCache);++const { MonetizationService } = await import('../../api/_lib/services/MonetizationService.js');++// Build a service whose own queries hit the mock; helpers are module-mocked.+const svc = (user) => new MonetizationService(user, { sql: sqlMock });++beforeEach(() => {+ calls = [];+ Object.assign(state, {+ agent: null, price: null, prices: [], existing: null,+ pending: null, inserted: null, confirmRow: null, royalty: [], assets: [], assetsThrow: false,+ });+ vi.clearAllMocks();+});++const findCall = (re) => calls.find((c) => re.test(c.q));++// ── Constructor / auth ────────────────────────────────────────────────────────+describe('constructor + requireAuth', () => {+ it('derives userId from a session user, an auth object, or a raw string', () => {+ expect(svc({ id: 'u1' }).userId).toBe('u1');+ expect(svc({ userId: 'u2' }).userId).toBe('u2');+ expect(svc('u3').userId).toBe('u3');+ expect(svc(null).userId).toBeNull();+ });++ it('requireAuth throws 401 when anonymous', () => {+ expect(() => svc(null).requireAuth()).toThrowError(/sign in required/);+ try { svc(null).requireAuth(); } catch (e) { expect(e.status).toBe(401); expect(e.code).toBe('unauthorized'); }+ });+});++// ── assertOwnership ────────────────────────────────────────────────────────────+describe('assertOwnership', () => {+ it('returns the agent when the caller owns it', async () => {+ state.agent = { id: 'a1', user_id: 'u1' };+ await expect(svc({ id: 'u1' }).assertOwnership('a1')).resolves.toEqual({ id: 'a1', user_id: 'u1' });+ });++ it('throws 404 when the agent does not exist', async () => {+ state.agent = null;+ await expect(svc({ id: 'u1' }).assertOwnership('a1')).rejects.toMatchObject({ status: 404, code: 'not_found' });+ });++ it('throws 403 when the caller is not the owner', async () => {+ state.agent = { id: 'a1', user_id: 'someone-else' };+ await expect(svc({ id: 'u1' }).assertOwnership('a1')).rejects.toMatchObject({ status: 403, code: 'forbidden' });+ });++ it('throws 401 when anonymous (before any DB lookup)', async () => {+ await expect(svc(null).assertOwnership('a1')).rejects.toMatchObject({ status: 401 });+ expect(findCall(/FROM agent_identities/i)).toBeUndefined();+ });+});++// ── getSkillPricesForAgent ─────────────────────────────────────────────────────+describe('getSkillPricesForAgent', () => {+ it('returns the active price rows (pure read, no ownership)', async () => {+ state.prices = [{ skill: 'echo', amount: 50000, currency_mint: 'M', chain: 'solana' }];+ const out = await svc(null).getSkillPricesForAgent('a1');+ expect(out).toHaveLength(1);+ expect(out[0].skill).toBe('echo');+ expect(findCall(/FROM agent_identities/i)).toBeUndefined();+ });+});++// ── setSkillPrices ─────────────────────────────────────────────────────────────+describe('setSkillPrices', () => {+ const prices = [+ { skill: 'web-search', amount: 50000, currency_mint: 'M', chain: 'solana' },+ { skill: 'summarize', amount: 100000, currency_mint: 'M', chain: 'solana' },+ ];++ it('verifies ownership, then atomically deactivates + upserts and invalidates cache', async () => {+ state.agent = { id: 'a1', user_id: 'u1' };+ const out = await svc({ id: 'u1' }).setSkillPrices('a1', prices);+ expect(out).toEqual({ ok: true, count: 2 });+ expect(findCall(/FROM agent_identities/i)).toBeDefined(); // ownership checked+ expect(findCall(/SET is_active = false WHERE agent_id/i)).toBeDefined();+ const inserts = calls.filter((c) => /INTO agent_skill_prices/i.test(c.q));+ expect(inserts).toHaveLength(2);+ expect(inserts.map((c) => c.values[1])).toEqual(['web-search', 'summarize']);+ expect(sqlMock.transaction).toHaveBeenCalledOnce();+ expect(priceCache.invalidateSkillPriceCache).toHaveBeenCalledWith('a1');+ });++ it('skips the redundant ownership lookup when the caller already verified it', async () => {+ await svc({ id: 'u1' }).setSkillPrices('a1', prices, { skipOwnershipCheck: true });+ expect(findCall(/FROM agent_identities/i)).toBeUndefined();+ expect(sqlMock.transaction).toHaveBeenCalledOnce();+ });++ it('rejects a non-owner before any write', async () => {+ state.agent = { id: 'a1', user_id: 'other' };+ await expect(svc({ id: 'u1' }).setSkillPrices('a1', prices)).rejects.toMatchObject({ status: 403 });+ expect(sqlMock.transaction).not.toHaveBeenCalled();+ expect(priceCache.invalidateSkillPriceCache).not.toHaveBeenCalled();+ });+});++// ── preparePurchaseTransaction ─────────────────────────────────────────────────+describe('preparePurchaseTransaction', () => {+ it('throws 401 when anonymous', async () => {+ await expect(svc(null).preparePurchaseTransaction('a1', 'echo')).rejects.toMatchObject({ status: 401 });+ });++ it('throws 404 when the skill is not for sale', async () => {+ state.price = null;+ await expect(svc({ id: 'u1' }).preparePurchaseTransaction('a1', 'echo')).rejects.toMatchObject({+ status: 404, code: 'not_found',+ });+ });++ it('throws 412 when the creator has no payout wallet', async () => {+ state.price = { amount: 1000000, currency_mint: 'M', chain: 'solana', mint_decimals: 6 };+ purchaseConfirm.resolvePayoutAddress.mockResolvedValueOnce(null);+ await expect(svc({ id: 'u1' }).preparePurchaseTransaction('a1', 'echo')).rejects.toMatchObject({+ status: 412, code: 'creator_wallet_missing',+ });+ });++ it('short-circuits when the buyer already has active access', async () => {+ state.price = { amount: 1000000, currency_mint: 'M', chain: 'solana', mint_decimals: 6 };+ state.existing = { reference: 'OLD', status: 'confirmed', tx_signature: 'T', confirmed_at: 'now', valid_until: null, trial_remaining: null, kind: 'purchase' };+ const out = await svc({ id: 'u1' }).preparePurchaseTransaction('a1', 'echo');+ expect(out.already_owned).toBe(true);+ expect(out.reference).toBe('OLD');+ expect(findCall(/INSERT INTO skill_purchases/i)).toBeUndefined();+ });++ it('creates a pending purchase and returns the fee-split quote', async () => {+ state.price = { amount: 1000000, currency_mint: 'MINT', chain: 'solana', mint_decimals: 6 };+ state.inserted = {+ reference: 'REF', amount: '1000000', currency_mint: 'MINT', chain: 'solana',+ expires_at: 'soon', valid_until: null, platform_fee_amount: '25000', platform_fee_wallet: 'TREASURY',+ };+ const out = await svc({ id: 'u1' }).preparePurchaseTransaction('a1', 'echo', { referrerUserId: 'ref-1' });+ expect(out.already_owned).toBe(false);+ expect(out.reference).toBe('REF');+ expect(out.recipient).toBe('PAYOUT');+ expect(out.amount).toBe('1000000');+ expect(out.creator_amount).toBe('975000'); // 1_000_000 − 25_000 fee+ expect(out.fee).toEqual({ recipient: 'TREASURY', amount: '25000', bps: 250 });+ expect(out.kind).toBe('purchase');+ expect(purchaseConfirm.logEvent).toHaveBeenCalledWith('REF', 'created', expect.objectContaining({ skill: 'echo' }));+ });+});++// ── confirmPurchase ────────────────────────────────────────────────────────────+describe('confirmPurchase', () => {+ it('throws 404 when no purchase matches the reference for this user', async () => {+ state.confirmRow = null;+ await expect(svc({ id: 'u1' }).confirmPurchase('REF')).rejects.toMatchObject({ status: 404 });+ });++ it('returns confirmed immediately for an already-confirmed row', async () => {+ state.confirmRow = { id: 'p1', status: 'confirmed', tx_signature: 'DONE', chain: 'solana' };+ const out = await svc({ id: 'u1' }).confirmPurchase('REF');+ expect(out).toEqual({ status: 'confirmed', tx_signature: 'DONE' });+ expect(purchaseConfirm.confirmSkillPurchase).not.toHaveBeenCalled();+ });++ it('throws 410 for an expired pending row', async () => {+ state.confirmRow = { id: 'p1', status: 'pending', chain: 'solana', expires_at: '2000-01-01T00:00:00Z' };+ await expect(svc({ id: 'u1' }).confirmPurchase('REF')).rejects.toMatchObject({ status: 410, code: 'purchase_expired' });+ });++ it('throws 400 when an EVM confirm omits the tx hash', async () => {+ state.confirmRow = { id: 'p1', status: 'pending', chain: 'base', expires_at: null };+ await expect(svc({ id: 'u1' }).confirmPurchase('REF')).rejects.toMatchObject({ status: 400, code: 'tx_hash_required' });+ });++ it('delegates to confirmSkillPurchase for a valid solana pending row', async () => {+ state.confirmRow = { id: 'p1', status: 'pending', chain: 'solana', expires_at: null, amount: '1000000' };+ purchaseConfirm.confirmSkillPurchase.mockResolvedValueOnce({ status: 'confirmed', tx_signature: 'SIG2' });+ const out = await svc({ id: 'u1' }).confirmPurchase('REF');+ expect(out).toEqual({ status: 'confirmed', tx_signature: 'SIG2' });+ expect(purchaseConfirm.confirmSkillPurchase).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'p1', reference: 'REF' }),+ { txHash: null },+ );+ });+});++// ── checkSkillOwnership ────────────────────────────────────────────────────────+describe('checkSkillOwnership', () => {+ it('maps the canonical access check to has_access (owned → true)', async () => {+ skillAccess.hasSkillAccess.mockResolvedValueOnce({ paid: true, owned: true, price: { skill: 'echo' } });+ const out = await svc({ id: 'u1' }).checkSkillOwnership('a1', 'echo');+ expect(out.has_access).toBe(true);+ expect(out.paid).toBe(true);+ expect(skillAccess.hasSkillAccess).toHaveBeenCalledWith('u1', 'a1', 'echo');+ });++ it('reports has_access false when the buyer does not own a paid skill', async () => {+ skillAccess.hasSkillAccess.mockResolvedValueOnce({ paid: true, owned: false, reason: 'not_purchased' });+ const out = await svc({ id: 'u1' }).checkSkillOwnership('a1', 'echo');+ expect(out.has_access).toBe(false);+ expect(out.reason).toBe('not_purchased');+ });+});++// ── getCreatorSalesData ────────────────────────────────────────────────────────+describe('getCreatorSalesData', () => {+ it('throws 401 when anonymous', async () => {+ await expect(svc(null).getCreatorSalesData()).rejects.toMatchObject({ status: 401 });+ });++ it('rolls up skill royalties + asset sales into totals and a merged feed', async () => {+ state.royalty = [+ { id: 'r1', price_usd: '2.50', status: 'settled', created_at: '2026-01-02T00:00:00Z', skill_name: 'echo', agent_name: 'A' },+ { id: 'r2', price_usd: '1.00', status: 'pending', created_at: '2026-01-01T00:00:00Z', skill_name: 'sum', agent_name: 'A' },+ ];+ state.assets = [+ { id: 'p1', item_type: 'avatar', item_id: 'av1', amount: 5_000_000, currency_mint: 'M', confirmed_at: '2026-01-03T00:00:00Z', created_at: '2026-01-03T00:00:00Z', status: 'confirmed', item_name: 'Cool Avatar' },+ ];+ const out = await svc({ id: 'u1' }).getCreatorSalesData();+ expect(out.pending_usd).toBeCloseTo(1.0);+ expect(out.settled_usd).toBeCloseTo(2.5 + 5.0); // royalty settled + asset (5_000_000 / 1e6)+ expect(out.entries).toHaveLength(3);+ // Newest first across both sources.+ expect(out.entries[0].created_at).toBe('2026-01-03T00:00:00Z');+ expect(out.entries[0].skill_name).toBe('Avatar sale');+ expect(out.entries[0].kind).toBe('avatar');+ });++ it('survives the asset_purchases table being absent', async () => {+ state.royalty = [{ id: 'r1', price_usd: '3.00', status: 'settled', created_at: '2026-01-01T00:00:00Z', skill_name: 'echo', agent_name: 'A' }];+ state.assetsThrow = true; // the asset query rejects; the service swallows it+ const out = await svc({ id: 'u1' }).getCreatorSalesData();+ expect(out.settled_usd).toBeCloseTo(3.0);+ expect(out.entries).toHaveLength(1);+ });+});++// ── getAvailableBalance ────────────────────────────────────────────────────────+describe('getAvailableBalance', () => {+ it('delegates to the accounting helper with the current user', async () => {+ monetization.getAvailableBalance.mockResolvedValueOnce({ earned: 9, withdrawn: 1, pending: 0, available: 8 });+ const out = await svc({ id: 'u1' }).getAvailableBalance('MINT');+ expect(out.available).toBe(8);+ expect(monetization.getAvailableBalance).toHaveBeenCalledWith('u1', 'MINT');+ });+});diff --git a/tests/api/skill-price-cache.test.js b/tests/api/skill-price-cache.test.jsnew file mode 100644index 000000000..cce732769--- /dev/null+++ b/tests/api/skill-price-cache.test.js@@ -0,0 +1,180 @@+// Unit tests for the agent skill-price cache (api/_lib/skill-price-cache.js).+//+// The module's job is a read-through cache over agent_skill_prices: serve from+// the shared cache adapter when warm, fall through to the DB on a miss (then+// store), and drop the entry on invalidation so the next read reflects an edit.+// These tests pin that orchestration by counting DB round-trips.+//+// The cache adapter (_lib/cache.js) is replaced with a deterministic Map-backed+// fake so the test never depends on whether Upstash is configured in the+// environment — cache.js's own Redis/in-memory behaviour is exercised elsewhere.+// db.js is replaced with a counting sql stub so each agent's DB hits are+// observable.++import { describe, it, expect, beforeEach, vi } from 'vitest';++// ── Map-backed cache adapter fake ────────────────────────────────────────────+const store = new Map();+const cacheGet = vi.fn(async (key) => (store.has(key) ? store.get(key) : null));+const cacheSet = vi.fn(async (key, value) => {+ store.set(key, value);+});+const cacheDel = vi.fn(async (key) => {+ store.delete(key);+});+vi.mock('../../api/_lib/cache.js', () => ({ cacheGet, cacheSet, cacheDel }));++// ── Counting SQL stub ────────────────────────────────────────────────────────+// Returns the canned active-price rows for the queried agent id and tallies how+// many times each agent was actually read from the DB.+const dbHits = new Map(); // agentId → count+const pricesByAgent = new Map(); // agentId → rows+const sql = vi.fn(async (_strings, ...values) => {+ const agentId = values[0];+ dbHits.set(agentId, (dbHits.get(agentId) || 0) + 1);+ return pricesByAgent.get(agentId) ?? [];+});+vi.mock('../../api/_lib/db.js', () => ({ sql }));++const { getSkillPrices, getSkillPrice, invalidateSkillPriceCache, skillPriceMap } = await import(+ '../../api/_lib/skill-price-cache.js'+);++// $THREE — the only coin this platform references.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++const AGENT_A = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa';+const AGENT_B = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb';++function priceRow(skill, over = {}) {+ return {+ skill,+ amount: 50000,+ currency_mint: THREE_MINT,+ chain: 'solana',+ mint_decimals: 6,+ trial_uses: 0,+ time_pass_hours: null,+ time_pass_amount: null,+ ...over,+ };+}++beforeEach(() => {+ store.clear();+ dbHits.clear();+ pricesByAgent.clear();+ cacheGet.mockClear();+ cacheSet.mockClear();+ cacheDel.mockClear();+ sql.mockClear();+});++describe('getSkillPrices — read-through caching', () => {+ it('hits the DB once, then serves repeat reads from cache', async () => {+ pricesByAgent.set(AGENT_A, [priceRow('translate')]);++ const first = await getSkillPrices(AGENT_A);+ expect(first).toEqual([priceRow('translate')]);+ expect(dbHits.get(AGENT_A)).toBe(1);+ expect(cacheSet).toHaveBeenCalledTimes(1);++ const second = await getSkillPrices(AGENT_A);+ expect(second).toEqual([priceRow('translate')]);+ // Still 1 — the second read was served from the cache, no new DB query.+ expect(dbHits.get(AGENT_A)).toBe(1);+ });++ it('caches each agent independently', async () => {+ pricesByAgent.set(AGENT_A, [priceRow('translate')]);+ pricesByAgent.set(AGENT_B, [priceRow('summarize', { amount: 99000 })]);++ await getSkillPrices(AGENT_A);+ await getSkillPrices(AGENT_B);+ const a2 = await getSkillPrices(AGENT_A);+ const b2 = await getSkillPrices(AGENT_B);++ expect(a2[0].skill).toBe('translate');+ expect(b2[0].skill).toBe('summarize');+ expect(dbHits.get(AGENT_A)).toBe(1);+ expect(dbHits.get(AGENT_B)).toBe(1);+ });++ it('falls back to a direct DB read when the cache backend throws', async () => {+ pricesByAgent.set(AGENT_A, [priceRow('translate')]);+ cacheGet.mockRejectedValueOnce(new Error('redis down'));++ const rows = await getSkillPrices(AGENT_A);+ expect(rows).toEqual([priceRow('translate')]);+ expect(dbHits.get(AGENT_A)).toBe(1);+ });+});++describe('invalidateSkillPriceCache', () => {+ it('drops the entry so the next read re-queries the DB', async () => {+ pricesByAgent.set(AGENT_A, [priceRow('translate', { amount: 50000 })]);+ await getSkillPrices(AGENT_A);+ expect(dbHits.get(AGENT_A)).toBe(1);++ // Creator edits the price; the write path invalidates.+ pricesByAgent.set(AGENT_A, [priceRow('translate', { amount: 75000 })]);+ await invalidateSkillPriceCache(AGENT_A);+ expect(cacheDel).toHaveBeenCalledTimes(1);++ const after = await getSkillPrices(AGENT_A);+ expect(after[0].amount).toBe(75000); // fresh value, not the stale 50000+ expect(dbHits.get(AGENT_A)).toBe(2); // re-queried after invalidation+ });+});++describe('getSkillPrice — single skill via the agent cache', () => {+ it('returns the matching row and reuses the warm cache', async () => {+ pricesByAgent.set(AGENT_A, [priceRow('translate'), priceRow('summarize')]);++ await getSkillPrices(AGENT_A); // warm the cache+ const hit = await getSkillPrice(AGENT_A, 'summarize');+ expect(hit).toMatchObject({ skill: 'summarize', currency_mint: THREE_MINT });+ expect(dbHits.get(AGENT_A)).toBe(1); // served from the warm cache+ });++ it('returns null when the skill is not priced', async () => {+ pricesByAgent.set(AGENT_A, [priceRow('translate')]);+ expect(await getSkillPrice(AGENT_A, 'nope')).toBeNull();+ });+});++describe('skillPriceMap', () => {+ it('folds rows into a map keyed by skill with the full pricing shape', async () => {+ const map = skillPriceMap([+ priceRow('translate', { amount: 50000, trial_uses: 2 }),+ priceRow('summarize', { amount: 100000, time_pass_hours: 24, time_pass_amount: 250000 }),+ ]);+ expect(Object.keys(map).sort()).toEqual(['summarize', 'translate']);+ expect(map.translate).toEqual({+ amount: 50000,+ currency_mint: THREE_MINT,+ chain: 'solana',+ mint_decimals: 6,+ trial_uses: 2,+ time_pass_hours: null,+ time_pass_amount: null,+ });+ expect(map.summarize.time_pass_hours).toBe(24);+ expect(map.summarize.time_pass_amount).toBe(250000);+ });++ it('defaults mint_decimals to 6 and trial_uses to 0 when a row omits them', () => {+ const map = skillPriceMap([+ { skill: 'translate', amount: 50000, currency_mint: THREE_MINT, chain: 'solana' },+ ]);+ expect(map.translate.mint_decimals).toBe(6);+ expect(map.translate.trial_uses).toBe(0);+ expect(map.translate.time_pass_hours).toBeNull();+ });++ it('returns an empty object for empty or nullish input', () => {+ expect(skillPriceMap([])).toEqual({});+ expect(skillPriceMap(null)).toEqual({});+ expect(skillPriceMap(undefined)).toEqual({});+ });+});diff --git a/tests/api/subscription-pricing.test.js b/tests/api/subscription-pricing.test.jsnew file mode 100644index 000000000..7a6532433--- /dev/null+++ b/tests/api/subscription-pricing.test.js@@ -0,0 +1,87 @@+// Unit tests for the pure subscription pricing + period math.+//+// No DB, no RPC, no Solana — verifies USD→USDC atomic conversion (with correct+// rounding) and the weekly/monthly period window used to set a subscription's+// current_period_end.++import { describe, it, expect } from 'vitest';+import {+ USDC_MAINNET_MINT,+ USDC_DECIMALS,+ usdToUsdcAtomics,+ intervalMs,+ computePeriod,+} from '../../api/_lib/subscription-pricing.js';++const DAY = 24 * 3600 * 1000;++describe('subscription-pricing', () => {+ it('exposes the canonical USDC mint at 6 decimals', () => {+ expect(USDC_MAINNET_MINT).toBe('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');+ expect(USDC_DECIMALS).toBe(6);+ });++ describe('usdToUsdcAtomics', () => {+ it('converts whole and fractional dollars to 6-decimal atomics', () => {+ expect(usdToUsdcAtomics(1)).toBe(1_000_000n);+ expect(usdToUsdcAtomics(9.99)).toBe(9_990_000n);+ expect(usdToUsdcAtomics(0.5)).toBe(500_000n);+ });++ it('rounds to the nearest atomic instead of truncating', () => {+ // 4.9999 * 1e6 = 4_999_900 exactly; 4.99999 rounds up to 5_000_000 - 10.+ expect(usdToUsdcAtomics(4.9999)).toBe(4_999_900n);+ expect(usdToUsdcAtomics(0.0000004)).toBe(0n); // below half an atomic → 0+ expect(usdToUsdcAtomics(0.0000006)).toBe(1n); // above half an atomic → 1+ });++ it('accepts numeric strings (Postgres numeric comes back as a string)', () => {+ expect(usdToUsdcAtomics('19.99')).toBe(19_990_000n);+ });++ it('returns 0 for a zero price', () => {+ expect(usdToUsdcAtomics(0)).toBe(0n);+ });++ it('throws on a negative or non-finite price', () => {+ expect(() => usdToUsdcAtomics(-1)).toThrow('invalid price');+ expect(() => usdToUsdcAtomics(Number.NaN)).toThrow('invalid price');+ expect(() => usdToUsdcAtomics('abc')).toThrow('invalid price');+ });+ });++ describe('intervalMs', () => {+ it('is 7 days for weekly', () => {+ expect(intervalMs('weekly')).toBe(7 * DAY);+ });+ it('is 30 days for monthly', () => {+ expect(intervalMs('monthly')).toBe(30 * DAY);+ });+ it('defaults unknown intervals to the monthly window', () => {+ expect(intervalMs('quarterly')).toBe(30 * DAY);+ expect(intervalMs(undefined)).toBe(30 * DAY);+ });+ });++ describe('computePeriod', () => {+ it('returns start = from and end = from + interval (weekly)', () => {+ const from = new Date('2026-06-18T00:00:00.000Z');+ const { start, end } = computePeriod('weekly', from);+ expect(start.toISOString()).toBe('2026-06-18T00:00:00.000Z');+ expect(end.toISOString()).toBe('2026-06-25T00:00:00.000Z');+ });++ it('advances by 30 days for monthly', () => {+ const from = new Date('2026-06-18T12:00:00.000Z');+ const { end } = computePeriod('monthly', from);+ expect(end.getTime() - from.getTime()).toBe(30 * DAY);+ });++ it('does not mutate the passed-in date', () => {+ const from = new Date('2026-06-18T00:00:00.000Z');+ const snapshot = from.getTime();+ computePeriod('monthly', from);+ expect(from.getTime()).toBe(snapshot);+ });+ });+});diff --git a/tests/api/x402-forge.test.js b/tests/api/x402-forge.test.jsindex 569bcaa5f..ca2774fbf 100644--- a/tests/api/x402-forge.test.js+++ b/tests/api/x402-forge.test.js@@ -64,6 +64,20 @@ const nvidiaMock = vi.hoisted(() => ({}));vi.mock('../../api/_providers/nvidia.js', () => nvidiaMock);+// Free HuggingFace Spaces reconstruct lane — the free-first alternative to the+// paid Replicate reconstruct. Default: UNAVAILABLE (createRegenProvider throws, as+// the real provider does without HF_TOKEN), so the existing reconstruct-fallback+// tests still reach Replicate. The free-first test overrides it per-call.+const hfMock = vi.hoisted(() => ({+ createRegenProvider: vi.fn(() => {+ throw Object.assign(new Error('HF_TOKEN env var is required for the huggingface provider'), {+ code: 'provider_unconfigured',+ status: 501,+ });+ }),+}));+vi.mock('../../api/_providers/huggingface.js', () => hfMock);+// Rate limiter: deterministic success, no Upstash dependency.vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {const actual = await importActual();@@ -236,6 +250,62 @@ describe('POST /api/x402/forge — paid generation', () => {expect(res.headers['x-payment-response']).toBe('stub-payment-response');});+ it('prefers the FREE HuggingFace lane over the paid Replicate reconstruct when available', async () => {+ // NVIDIA NIM unavailable (default throws) → reconstruct step. HF is live this+ // call, so it must be chosen BEFORE Replicate — the paid lane is never touched.+ hfMock.createRegenProvider.mockReturnValueOnce({+ submit: vi.fn(async () => ({ extJobId: 'hf-packed-job' })),+ status: vi.fn(async () => ({ status: 'done', resultGlbUrl: 'https://hf.example/out.glb' })),+ });+ replicateMock.submit.mockClear();+ // persistRemoteGlb fetches the GLB to copy it to R2; reject so it fail-softs to+ // the HF url without a real network call.+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('no network in test'));+ try {+ const res = makeRes();+ await handler(+ makeReq({ headers: { 'x-payment': 'pay-free-hf' }, body: { prompt: 'a brass owl', tier: 'standard' } }),+ res,+ );+ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.backend).toBe('huggingface');+ expect(body.status).toBe('done');+ expect(body.glb_url).toBeTruthy();+ // Free was chosen first — the paid Replicate reconstruct was never invoked.+ expect(replicateMock.submit).not.toHaveBeenCalled();+ // The buyer still paid + received a model (settlement ran).+ expect(res.headers['x-payment-response']).toBe('stub-payment-response');+ } finally {+ fetchSpy.mockRestore();+ }+ });++ it('sanitizes a paid-lane "insufficient credit" failure into a clean unavailable state (no leak, no settle)', async () => {+ // NVIDIA unavailable, HF unavailable (default), Replicate out of credit: the+ // raw vendor billing message must never reach the buyer, and submit-before-+ // settle means the payment was not taken.+ replicateMock.submit.mockRejectedValueOnce(+ Object.assign(+ new Error(+ 'You have insufficient credit to run this model. Go to https://replicate.com/account/billing#billing to purchase credit.',+ ),+ { code: 'provider_error', status: 502, providerStatus: 402 },+ ),+ );+ const res = makeRes();+ await handler(+ makeReq({ headers: { 'x-payment': 'pay-broke-replicate' }, body: { prompt: 'a brass owl', tier: 'standard' } }),+ res,+ );+ expect(res.statusCode).toBe(503);+ const body = JSON.parse(res.body);+ expect(body.error).toBe('generation_unavailable');+ expect(body.error_description).not.toMatch(/credit|replicate|billing|insufficient/i);+ // Submit failed before settle → no settlement receipt was emitted.+ expect(res.headers['x-payment-response']).toBeUndefined();+ });+it('rejects a paid request that carries no actual input', async () => {const res = makeRes();await handler(makeReq({ headers: { 'x-payment': 'stub-payment-proof' }, body: {} }), res);diff --git a/tests/monetization-service.test.js b/tests/monetization-service.test.jsnew file mode 100644index 000000000..07a2f0c0a--- /dev/null+++ b/tests/monetization-service.test.js@@ -0,0 +1,655 @@+// Unit + integration tests for the monetization service layer.+//+// The financial core of monetization lives in three places, none of which had+// direct coverage before this suite:+//+// • api/_lib/fee.js — platform fee split (calculateFee, getFeeBps)+// • api/_lib/monetization.js — recordRevenueEvent (revenue attribution ++// fee/net split) and getAvailableBalance+// (withdrawable-balance aggregation)+// • api/monetization/*.js — the unified REST surface: prices.js (set/list+// skill prices) and revenue.js (creator sales+// aggregation)+//+// Money math is unforgiving, so every branch — validation, rounding, the+// owner/non-owner gate, and the earned − pending − withdrawn arithmetic — is+// exercised here. The DB client is mocked with a queue-driven `sql` stub+// (shared by the directly-called service functions and the HTTP handlers) so+// the logic is tested in isolation from Neon, exactly as Prompt 18 specifies.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { createTestAgent, createTestUser, invoke } from './_helpers/monetization.js';++// ── Mock state ────────────────────────────────────────────────────────────────++const authState = { session: null, bearer: null };+const sqlState = { queue: [], calls: [] };+const rlState = { success: true };++// ── Mocks ─────────────────────────────────────────────────────────────────────++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => authState.session),+ authenticateBearer: vi.fn(async () => authState.bearer),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../api/_lib/db.js', () => {+ // Mirrors the real `sql` proxy: a tagged-template call receives the strings+ // array as the first arg; the function form receives a query string. Each+ // call records (query, values) for assertions and shifts the next queued+ // result, defaulting to [] so `const [row] = await sql\`…\`` never throws.+ const sql = vi.fn(async (strings, ...values) => {+ if (typeof strings === 'string') {+ sqlState.calls.push({ query: strings, values: values[0] ?? [] });+ } else {+ sqlState.calls.push({ query: strings.join('?'), values });+ }+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ });+ sql.transaction = (queries) => Promise.all(queries);+ return { sql };+});++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ authIp: vi.fn(async () => ({ success: rlState.success })),+ publicIp: vi.fn(async () => ({ success: rlState.success })),+ pricingPerIp: vi.fn(async () => ({ success: rlState.success })),+ withdrawalPerUser: vi.fn(async () => ({ success: rlState.success })),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++vi.mock('../api/_lib/csrf.js', () => ({+ requireCsrf: vi.fn(async () => true),+ generateToken: vi.fn(async () => 'test-csrf-token'),+}));++// ── Imports under test (after mocks) ───────────────────────────────────────────++const { recordRevenueEvent, getAvailableBalance } = await import('../api/_lib/monetization.js');+const { calculateFee, getFeeBps } = await import('../api/_lib/fee.js');+const { default: pricesHandler } = await import('../api/monetization/prices.js');+const { default: revenueHandler } = await import('../api/monetization/revenue.js');++const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// ── Reset between tests ─────────────────────────────────────────────────────────++beforeEach(() => {+ authState.session = null;+ authState.bearer = null;+ sqlState.queue = [];+ sqlState.calls = [];+ rlState.success = true;+});++// ── 1. Fee calculation (api/_lib/fee.js) ────────────────────────────────────────++describe('calculateFee', () => {+ it('exposes a sane default fee rate (250 bps = 2.5%)', () => {+ const bps = getFeeBps();+ expect(Number.isInteger(bps)).toBe(true);+ expect(bps).toBeGreaterThan(0);+ expect(bps).toBeLessThanOrEqual(10_000);+ });++ it('splits a round amount into platform fee and creator net', () => {+ const bps = getFeeBps();+ const { fee, net } = calculateFee(1_000_000);+ expect(fee).toBe(Math.floor((1_000_000 * bps) / 10_000));+ expect(net).toBe(1_000_000 - fee);+ // With the default 250 bps this is the 25_000 / 975_000 split the rest of+ // the monetization stack asserts against.+ if (bps === 250) {+ expect(fee).toBe(25_000);+ expect(net).toBe(975_000);+ }+ });++ it('floors the fee for amounts that do not divide evenly', () => {+ // 333 * 250 / 10_000 = 8.325 → floored to 8.+ const { fee, net } = calculateFee(333);+ expect(fee).toBe(Math.floor((333 * getFeeBps()) / 10_000));+ expect(Number.isInteger(fee)).toBe(true);+ expect(fee + net).toBe(333);+ });++ it('preserves the invariant fee + net === gross across a range', () => {+ for (const gross of [1, 7, 999, 1_000_000, 123_456_789]) {+ const { fee, net } = calculateFee(gross);+ expect(fee + net).toBe(gross);+ expect(fee).toBeGreaterThanOrEqual(0);+ expect(fee).toBeLessThanOrEqual(gross);+ }+ });++ it('returns a zero split for a zero amount', () => {+ expect(calculateFee(0)).toEqual({ fee: 0, net: 0 });+ });+});++// ── 2. recordRevenueEvent (api/_lib/monetization.js) ────────────────────────────++describe('recordRevenueEvent', () => {+ const baseEvent = {+ agentId: 'agent-uuid-1',+ skillName: 'answer-question',+ callerAddress: 'Payer1111111111111111111111111111111111111',+ amountUsdc: 1_000_000,+ network: 'solana',+ txHash: 'sig-abc',+ intentId: 'intent-xyz',+ };++ function findInsert() {+ return sqlState.calls.find((c) => c.query.includes('agent_revenue_events'));+ }++ it('records the gross amount with the correct fee/net split', async () => {+ sqlState.queue.push([{ id: 'rev-1', agent_id: baseEvent.agentId, skill: baseEvent.skillName }]);++ const row = await recordRevenueEvent(baseEvent);++ const insert = findInsert();+ expect(insert).toBeDefined();+ // VALUES order: agent_id, intent_id, skill, gross, fee, net, mint, chain, payer+ const [agentId, , skill, gross, fee, net, , chain, payer] = insert.values;+ expect(agentId).toBe(baseEvent.agentId);+ expect(skill).toBe(baseEvent.skillName);+ expect(gross).toBe(1_000_000);+ expect(fee).toBe(calculateFee(1_000_000).fee);+ expect(net).toBe(calculateFee(1_000_000).net);+ expect(fee + net).toBe(gross);+ expect(chain).toBe('solana');+ expect(payer).toBe(baseEvent.callerAddress);+ expect(row).toEqual({ id: 'rev-1', agent_id: baseEvent.agentId, skill: baseEvent.skillName });+ });++ it('defaults the currency mint to USDC when none is supplied', async () => {+ sqlState.queue.push([{ id: 'rev-2' }]);++ await recordRevenueEvent({ ...baseEvent, currencyMint: undefined });++ const insert = findInsert();+ expect(insert.values).toContain(USDC_MINT);+ });++ it('uses the explicit intentId as the intent reference', async () => {+ sqlState.queue.push([{ id: 'rev-3' }]);+ await recordRevenueEvent(baseEvent);+ expect(findInsert().values[1]).toBe('intent-xyz');+ });++ it('falls back to the txHash when no intentId is given', async () => {+ sqlState.queue.push([{ id: 'rev-4' }]);+ await recordRevenueEvent({ ...baseEvent, intentId: undefined });+ expect(findInsert().values[1]).toBe('sig-abc');+ });++ it("falls back to 'direct' when neither intentId nor txHash is given", async () => {+ sqlState.queue.push([{ id: 'rev-5' }]);+ await recordRevenueEvent({ ...baseEvent, intentId: undefined, txHash: undefined });+ expect(findInsert().values[1]).toBe('direct');+ });++ it('rejects a non-positive amount before touching the database', async () => {+ await expect(recordRevenueEvent({ ...baseEvent, amountUsdc: 0 }))+ .rejects.toMatchObject({ status: 400 });+ await expect(recordRevenueEvent({ ...baseEvent, amountUsdc: -5 }))+ .rejects.toMatchObject({ status: 400 });+ expect(sqlState.calls).toHaveLength(0);+ });++ it('rejects a non-numeric amount', async () => {+ await expect(recordRevenueEvent({ ...baseEvent, amountUsdc: 'abc' }))+ .rejects.toMatchObject({ status: 400 });+ expect(sqlState.calls).toHaveLength(0);+ });++ it('rejects a missing agentId', async () => {+ await expect(recordRevenueEvent({ ...baseEvent, agentId: undefined }))+ .rejects.toThrow(/agentId/);+ expect(sqlState.calls).toHaveLength(0);+ });++ it('rejects a missing skillName', async () => {+ await expect(recordRevenueEvent({ ...baseEvent, skillName: undefined }))+ .rejects.toThrow(/skillName/);+ expect(sqlState.calls).toHaveLength(0);+ });+});++// ── 3. getAvailableBalance (api/_lib/monetization.js) ───────────────────────────++describe('getAvailableBalance', () => {+ function queueBalance({ earned, pending, withdrawn }) {+ sqlState.queue.push([{ earned }]); // revenue events sum+ sqlState.queue.push([{ pending, withdrawn }]); // withdrawals split+ }++ it('computes available = earned − pending − withdrawn', async () => {+ queueBalance({ earned: 5_000_000n, pending: 1_000_000n, withdrawn: 2_000_000n });++ const balance = await getAvailableBalance('user-1');++ expect(balance).toEqual({+ earned: 5_000_000,+ pending: 1_000_000,+ withdrawn: 2_000_000,+ available: 2_000_000,+ });+ });++ it('coerces bigint column sums to plain numbers', async () => {+ queueBalance({ earned: 10_000_000n, pending: 0n, withdrawn: 0n });++ const balance = await getAvailableBalance('user-1');++ expect(typeof balance.earned).toBe('number');+ expect(typeof balance.available).toBe('number');+ expect(balance.available).toBe(10_000_000);+ });++ it('clamps available at zero when withdrawals exceed earnings', async () => {+ queueBalance({ earned: 1_000_000n, pending: 0n, withdrawn: 3_000_000n });++ const balance = await getAvailableBalance('user-1');++ expect(balance.available).toBe(0); // never negative+ expect(balance.earned).toBe(1_000_000);+ expect(balance.withdrawn).toBe(3_000_000);+ });++ it('treats pending/processing withdrawals as reserved against the balance', async () => {+ queueBalance({ earned: 4_000_000n, pending: 4_000_000n, withdrawn: 0n });++ const balance = await getAvailableBalance('user-1');++ expect(balance.available).toBe(0);+ expect(balance.pending).toBe(4_000_000);+ });++ it('queries without a currency filter when no mint is given', async () => {+ queueBalance({ earned: 1n, pending: 0n, withdrawn: 0n });++ await getAvailableBalance('user-1');++ const earnedCall = sqlState.calls.find((c) => c.query.includes('agent_revenue_events'));+ // All-currencies branch binds only the userId.+ expect(earnedCall.values).toEqual(['user-1']);+ });++ it('binds the currency mint when a filter is supplied', async () => {+ queueBalance({ earned: 1n, pending: 0n, withdrawn: 0n });++ await getAvailableBalance('user-1', USDC_MINT);++ const earnedCall = sqlState.calls.find((c) => c.query.includes('agent_revenue_events'));+ const wdrawCall = sqlState.calls.find((c) => c.query.includes('agent_withdrawals'));+ expect(earnedCall.values).toEqual(['user-1', USDC_MINT]);+ expect(wdrawCall.values).toEqual(['user-1', USDC_MINT]);+ });+});++// ── 4. setSkillPrices — api/monetization/prices.js ──────────────────────────────++describe('prices endpoint (setSkillPrices)', () => {+ it('lets an owner set a new price and returns 201', async () => {+ const { agent, session } = createTestAgent();+ authState.session = session;++ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership+ sqlState.queue.push([]); // no existing price+ sqlState.queue.push([]); // upsert+ sqlState.queue.push([+ {+ id: 'price-1',+ skill: 'answer-question',+ currency_mint: USDC_MINT,+ chain: 'solana',+ amount: 50_000,+ is_active: true,+ created_at: '2026-06-18T00:00:00Z',+ updated_at: '2026-06-18T00:00:00Z',+ },+ ]);++ const { status, body } = await invoke(pricesHandler, {+ method: 'PUT',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'answer-question', price_usdc: 0.05 },+ });++ expect(status).toBe(201);+ expect(body.price.skill_name).toBe('answer-question');+ expect(body.price.amount_atomic).toBe(50_000);+ expect(body.price.price_usdc).toBe(0.05);+ });++ it('converts price_usdc to atomic units in the upsert (0.05 → 50000)', async () => {+ const { agent, session } = createTestAgent();+ authState.session = session;++ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);+ sqlState.queue.push([]);+ sqlState.queue.push([]);+ sqlState.queue.push([{ id: 'p', skill: 'echo', currency_mint: USDC_MINT, chain: 'solana', amount: 50_000, is_active: true }]);++ await invoke(pricesHandler, {+ method: 'PUT',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.05 },+ });++ const upsert = sqlState.calls.find((c) => c.query.includes('ON CONFLICT'));+ expect(upsert).toBeDefined();+ expect(upsert.values).toContain(50_000); // amountAtomic = round(0.05 * 1e6)+ });++ it('returns 200 when updating an existing price', async () => {+ const { agent, session } = createTestAgent();+ authState.session = session;++ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership+ sqlState.queue.push([{ id: 'price-1' }]); // existing price → update path+ sqlState.queue.push([]); // upsert+ sqlState.queue.push([{ id: 'price-1', skill: 'echo', currency_mint: USDC_MINT, chain: 'solana', amount: 100_000, is_active: true }]);++ const { status } = await invoke(pricesHandler, {+ method: 'PUT',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.1 },+ });++ expect(status).toBe(200);+ });++ it('blocks a non-owner with 403', async () => {+ const { agent } = createTestAgent();+ const { session: otherSession } = createTestUser();+ authState.session = otherSession;++ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // owned by someone else++ const { status, body } = await invoke(pricesHandler, {+ method: 'PUT',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.01 },+ });++ expect(status).toBe(403);+ expect(body.error).toBe('forbidden');+ });++ it('returns 404 when the agent does not exist', async () => {+ const { agent, session } = createTestAgent();+ authState.session = session;++ sqlState.queue.push([]); // no agent row++ const { status, body } = await invoke(pricesHandler, {+ method: 'PUT',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.01 },+ });++ expect(status).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('returns 401 when unauthenticated', async () => {+ const { agent } = createTestAgent();++ const { status, body } = await invoke(pricesHandler, {+ method: 'PUT',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.01 },+ });++ expect(status).toBe(401);+ expect(body.error).toBe('unauthorized');+ });++ it('rejects a price below the minimum atomic unit with 400', async () => {+ const { agent, session } = createTestAgent();+ authState.session = session;++ // 0.0000004 USDC rounds to 0 atomic units, under MIN_PRICE_ATOMIC (1).+ const { status, body } = await invoke(pricesHandler, {+ method: 'PUT',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.0000004 },+ });++ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('rejects an invalid skill_name with a validation error', async () => {+ const { agent, session } = createTestAgent();+ authState.session = session;++ const { status, body } = await invoke(pricesHandler, {+ method: 'PUT',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'has spaces!', price_usdc: 0.01 },+ });++ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('soft-deletes a price for the owner', async () => {+ const { agent, session } = createTestAgent();+ authState.session = session;++ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership+ sqlState.queue.push([{ id: 'price-1' }]); // UPDATE … RETURNING id++ const { status, body } = await invoke(pricesHandler, {+ method: 'DELETE',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'echo' },+ });++ expect(status).toBe(200);+ expect(body.deleted).toBe(true);+ expect(body.skill_name).toBe('echo');+ });++ it('returns 404 when hard-deleting a price that does not exist', async () => {+ const { agent, session } = createTestAgent();+ authState.session = session;++ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership+ sqlState.queue.push([]); // DELETE … RETURNING id → nothing++ const { status, body } = await invoke(pricesHandler, {+ method: 'DELETE',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'ghost', hard: true },+ });++ expect(status).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('lists active prices publicly via GET', async () => {+ const { agent } = createTestAgent();++ sqlState.queue.push([{ id: agent.id }]); // agent exists+ sqlState.queue.push([+ { id: 'p1', skill: 'echo', currency_mint: USDC_MINT, chain: 'solana', amount: 1_000_000, is_active: true },+ { id: 'p2', skill: 'summarize', currency_mint: USDC_MINT, chain: 'solana', amount: 2_500_000, is_active: true },+ ]);++ const { status, body } = await invoke(pricesHandler, {+ method: 'GET',+ url: `/api/monetization/prices?agent_id=${agent.id}`,+ });++ expect(status).toBe(200);+ expect(body.prices).toHaveLength(2);+ expect(body.prices[0].price_usdc).toBe(1); // 1_000_000 atomic → 1 USDC+ expect(body.prices[1].amount_atomic).toBe(2_500_000);+ });++ it('returns 400 on GET without a UUID agent_id', async () => {+ const { status, body } = await invoke(pricesHandler, {+ method: 'GET',+ url: '/api/monetization/prices?agent_id=not-a-uuid',+ });++ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('returns 429 when the rate limit is exceeded', async () => {+ const { agent, session } = createTestAgent();+ authState.session = session;+ rlState.success = false;++ const { status, body } = await invoke(pricesHandler, {+ method: 'PUT',+ url: '/api/monetization/prices',+ body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.01 },+ });++ expect(status).toBe(429);+ expect(body.error).toBe('rate_limited');+ });+});++// ── 5. getCreatorSalesData — api/monetization/revenue.js ────────────────────────++describe('revenue endpoint (getCreatorSalesData)', () => {+ it('aggregates totals, per-skill, and per-day breakdowns', async () => {+ authState.session = { id: 'user-1' };++ sqlState.queue.push([+ { gross_total: 3_000_000n, fee_total: 75_000n, net_total: 2_925_000n, event_count: 3 },+ ]); // summary+ sqlState.queue.push([+ { skill: 'echo', net_total: 1_950_000n, count: 2 },+ { skill: 'summarize', net_total: 975_000n, count: 1 },+ ]); // by_skill+ sqlState.queue.push([+ { period: '2026-06-17T00:00:00.000Z', net_total: 975_000n, count: 1 },+ { period: '2026-06-18T00:00:00.000Z', net_total: 1_950_000n, count: 2 },+ ]); // by_day++ const { status, body } = await invoke(revenueHandler, {+ method: 'GET',+ url: '/api/monetization/revenue?period=7d',+ });++ expect(status).toBe(200);+ expect(body.total_usdc).toBe(3); // 3_000_000 atomic → 3 USDC+ expect(body.total_fees_usdc).toBe(0.075);+ expect(body.net_usdc).toBe(2.925);+ expect(body.event_count).toBe(3);+ expect(body.net_atomic).toBe(2_925_000);+ expect(body.by_skill).toHaveLength(2);+ expect(body.by_skill[0]).toMatchObject({ skill: 'echo', total: 1.95, count: 2 });+ expect(body.by_day).toHaveLength(2);+ expect(body.by_day[0].date).toBe('2026-06-17');+ });++ it('returns zeroed totals when there is no revenue', async () => {+ authState.session = { id: 'user-1' };++ sqlState.queue.push([{ gross_total: 0n, fee_total: 0n, net_total: 0n, event_count: 0 }]);+ sqlState.queue.push([]); // by_skill+ sqlState.queue.push([]); // by_day++ const { status, body } = await invoke(revenueHandler, {+ method: 'GET',+ url: '/api/monetization/revenue',+ });++ expect(status).toBe(200);+ expect(body.total_usdc).toBe(0);+ expect(body.event_count).toBe(0);+ expect(body.by_skill).toEqual([]);+ expect(body.by_day).toEqual([]);+ });++ it('returns 401 when unauthenticated', async () => {+ const { status, body } = await invoke(revenueHandler, {+ method: 'GET',+ url: '/api/monetization/revenue',+ });++ expect(status).toBe(401);+ expect(body.error).toBe('unauthorized');+ });++ it('returns 400 on an unknown period', async () => {+ authState.session = { id: 'user-1' };++ const { status, body } = await invoke(revenueHandler, {+ method: 'GET',+ url: '/api/monetization/revenue?period=forever',+ });++ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('returns 400 on a malformed agent_id', async () => {+ authState.session = { id: 'user-1' };++ const { status, body } = await invoke(revenueHandler, {+ method: 'GET',+ url: '/api/monetization/revenue?agent_id=not-a-uuid',+ });++ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('returns 404 when scoped to an agent that does not exist', async () => {+ const { agent } = createTestAgent();+ authState.session = { id: 'user-1' };++ sqlState.queue.push([]); // no agent row++ const { status, body } = await invoke(revenueHandler, {+ method: 'GET',+ url: `/api/monetization/revenue?agent_id=${agent.id}`,+ });++ expect(status).toBe(404);+ expect(body.error).toBe('not_found');+ });++ it('returns 403 when scoped to an agent owned by someone else', async () => {+ const { agent } = createTestAgent();+ authState.session = { id: 'user-1' };++ sqlState.queue.push([{ id: agent.id, user_id: 'a-different-user' }]);++ const { status, body } = await invoke(revenueHandler, {+ method: 'GET',+ url: `/api/monetization/revenue?agent_id=${agent.id}`,+ });++ expect(status).toBe(403);+ expect(body.error).toBe('forbidden');+ });++ it('returns 429 when the rate limit is exceeded', async () => {+ authState.session = { id: 'user-1' };+ rlState.success = false;++ const { status, body } = await invoke(revenueHandler, {+ method: 'GET',+ url: '/api/monetization/revenue',+ });++ expect(status).toBe(429);+ expect(body.error).toBe('rate_limited');+ });+});diff --git a/tests/skill-license-onchain.test.js b/tests/skill-license-onchain.test.jsnew file mode 100644index 000000000..b3bc51519--- /dev/null+++ b/tests/skill-license-onchain.test.js@@ -0,0 +1,237 @@+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { createHash } from 'node:crypto';++import { describe, it, expect } from 'vitest';+import { Keypair, PublicKey, SystemProgram, SYSVAR_RENT_PUBKEY } from '@solana/web3.js';++import {+ SKILL_LICENSE_PROGRAM_ID,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+ skillSeed,+ deriveMarketplacePda,+ deriveSkillLicensePda,+ deriveSkillMintPda,+ deriveAssociatedTokenAddress,+ decodeSkillLicense,+ buildMintSkillLicenseIx,+ buildInitializeMarketplaceIx,+} from '../api/_lib/skill-license-onchain.js';++const idl = JSON.parse(+ readFileSync(fileURLToPath(new URL('../contracts/idl/skill_license.json', import.meta.url)), 'utf8'),+);++const OWNER = new PublicKey('9MjzHaTB6Jko4YKo9mDzJSaGnktzhbebgsnqPpYWnXC7');+const AGENT = new PublicKey('So11111111111111111111111111111111111111112');+const SKILL = 'summarize';++const ixDisc = (name) => idl.instructions.find((i) => i.name === name).discriminator;++describe('skillSeed', () => {+ it('is the 32-byte sha256 of the name, matching the Rust seed', () => {+ const seed = skillSeed(SKILL);+ expect(seed).toHaveLength(32);+ expect(Buffer.from(seed).toString('hex')).toBe(+ createHash('sha256').update(SKILL).digest('hex'),+ );+ });++ it('differs for different skill names', () => {+ expect(Buffer.from(skillSeed('a')).equals(Buffer.from(skillSeed('b')))).toBe(false);+ });+});++describe('PDA derivations', () => {+ it('marketplace PDA is deterministic and off-curve', () => {+ const [a, bumpA] = deriveMarketplacePda();+ const [b] = deriveMarketplacePda();+ expect(a.toBase58()).toBe(b.toBase58());+ expect(PublicKey.isOnCurve(a.toBytes())).toBe(false);+ expect(bumpA).toBeGreaterThanOrEqual(0);+ expect(bumpA).toBeLessThanOrEqual(255);+ });++ it('license + mint PDAs are deterministic for the same inputs', () => {+ const [lic1] = deriveSkillLicensePda(OWNER, AGENT, SKILL);+ const [lic2] = deriveSkillLicensePda(OWNER, AGENT, SKILL);+ const [mint1] = deriveSkillMintPda(OWNER, AGENT, SKILL);+ const [mint2] = deriveSkillMintPda(OWNER, AGENT, SKILL);+ expect(lic1.toBase58()).toBe(lic2.toBase58());+ expect(mint1.toBase58()).toBe(mint2.toBase58());+ });++ it('license and mint PDAs differ (distinct seed prefixes)', () => {+ const [lic] = deriveSkillLicensePda(OWNER, AGENT, SKILL);+ const [mint] = deriveSkillMintPda(OWNER, AGENT, SKILL);+ expect(lic.toBase58()).not.toBe(mint.toBase58());+ });++ it('changing skill, owner, or agent changes the license PDA', () => {+ const [base] = deriveSkillLicensePda(OWNER, AGENT, SKILL);+ const [otherSkill] = deriveSkillLicensePda(OWNER, AGENT, 'translate');+ const [otherOwner] = deriveSkillLicensePda(AGENT, AGENT, SKILL);+ const [otherAgent] = deriveSkillLicensePda(OWNER, OWNER, SKILL);+ const set = new Set([+ base.toBase58(),+ otherSkill.toBase58(),+ otherOwner.toBase58(),+ otherAgent.toBase58(),+ ]);+ expect(set.size).toBe(4);+ });++ it('ATA derivation matches the standard associated-token program derivation', () => {+ const [mint] = deriveSkillMintPda(OWNER, AGENT, SKILL);+ const ata = deriveAssociatedTokenAddress(OWNER, mint);+ const [expected] = PublicKey.findProgramAddressSync(+ [OWNER.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()],+ ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ expect(ata.toBase58()).toBe(expected.toBase58());+ });+});++describe('decodeSkillLicense', () => {+ function encodeLicense({ authority, agentMint, nftMint, skillName, purchaseDate, revokedAt, bump }) {+ const disc = Buffer.from(idl.accounts.find((a) => a.name === 'SkillLicense').discriminator);+ const pd = Buffer.alloc(8);+ pd.writeBigInt64LE(BigInt(purchaseDate));+ const rv = Buffer.alloc(8);+ rv.writeBigInt64LE(BigInt(revokedAt));+ const nameBytes = Buffer.from(skillName, 'utf8');+ const nameLen = Buffer.alloc(4);+ nameLen.writeUInt32LE(nameBytes.length);+ return Buffer.concat([+ disc,+ new PublicKey(authority).toBuffer(),+ new PublicKey(agentMint).toBuffer(),+ new PublicKey(nftMint).toBuffer(),+ Buffer.from(skillSeed(skillName)),+ pd,+ rv,+ Buffer.from([bump]),+ nameLen,+ nameBytes,+ ]);+ }++ it('round-trips an active license', () => {+ const nft = Keypair.generate().publicKey;+ const buf = encodeLicense({+ authority: OWNER.toBase58(),+ agentMint: AGENT.toBase58(),+ nftMint: nft.toBase58(),+ skillName: SKILL,+ purchaseDate: 1_750_000_000,+ revokedAt: 0,+ bump: 254,+ });+ const rec = decodeSkillLicense(buf);+ expect(rec.authority).toBe(OWNER.toBase58());+ expect(rec.agentMint).toBe(AGENT.toBase58());+ expect(rec.nftMint).toBe(nft.toBase58());+ expect(rec.skillName).toBe(SKILL);+ expect(rec.purchaseDate).toBe(1_750_000_000);+ expect(rec.revokedAt).toBe(0);+ expect(rec.revoked).toBe(false);+ expect(rec.bump).toBe(254);+ expect(rec.skillHash).toBe(createHash('sha256').update(SKILL).digest('hex'));+ });++ it('reports a revoked license', () => {+ const buf = encodeLicense({+ authority: OWNER.toBase58(),+ agentMint: AGENT.toBase58(),+ nftMint: Keypair.generate().publicKey.toBase58(),+ skillName: SKILL,+ purchaseDate: 1_750_000_000,+ revokedAt: 1_750_500_000,+ bump: 255,+ });+ const rec = decodeSkillLicense(buf);+ expect(rec.revoked).toBe(true);+ expect(rec.revokedAt).toBe(1_750_500_000);+ });++ it('throws on a discriminator mismatch', () => {+ const bad = Buffer.alloc(200);+ expect(() => decodeSkillLicense(bad)).toThrow(/discriminator/);+ });+});++describe('buildMintSkillLicenseIx', () => {+ const minter = Keypair.generate().publicKey;+ const built = buildMintSkillLicenseIx({ minter, owner: OWNER, agentMint: AGENT, skillName: SKILL });+ const ix = built.instruction;++ it('targets the program and leads with the mint discriminator + borsh skill name', () => {+ expect(ix.programId.toBase58()).toBe(SKILL_LICENSE_PROGRAM_ID);+ expect([...ix.data.subarray(0, 8)]).toEqual(ixDisc('mint_skill_license'));+ // borsh string: u32 LE length then bytes+ expect(ix.data.readUInt32LE(8)).toBe(SKILL.length);+ expect(ix.data.subarray(12).toString('utf8')).toBe(SKILL);+ });++ it('orders accounts and signer/writable flags to match the IDL', () => {+ const [marketplace] = deriveMarketplacePda();+ const [license] = deriveSkillLicensePda(OWNER, AGENT, SKILL);+ const [nft] = deriveSkillMintPda(OWNER, AGENT, SKILL);+ const ata = deriveAssociatedTokenAddress(OWNER, nft);+ const expected = [+ [marketplace.toBase58(), false, true],+ [minter.toBase58(), true, true],+ [OWNER.toBase58(), false, false],+ [AGENT.toBase58(), false, false],+ [license.toBase58(), false, true],+ [nft.toBase58(), false, true],+ [ata.toBase58(), false, true],+ [TOKEN_PROGRAM_ID.toBase58(), false, false],+ [ASSOCIATED_TOKEN_PROGRAM_ID.toBase58(), false, false],+ [SystemProgram.programId.toBase58(), false, false],+ [SYSVAR_RENT_PUBKEY.toBase58(), false, false],+ ];+ expect(ix.keys.map((k) => [k.pubkey.toBase58(), k.isSigner, k.isWritable])).toEqual(expected);+ });++ it('reports the derived PDAs it used', () => {+ const [license] = deriveSkillLicensePda(OWNER, AGENT, SKILL);+ expect(built.accounts.skillLicense).toBe(license.toBase58());+ });+});++describe('buildInitializeMarketplaceIx', () => {+ it('encodes the discriminator + minter pubkey and the right account flags', () => {+ const authority = Keypair.generate().publicKey;+ const minter = Keypair.generate().publicKey;+ const { instruction: ix } = buildInitializeMarketplaceIx({ authority, minter });+ const [marketplace] = deriveMarketplacePda();++ expect([...ix.data.subarray(0, 8)]).toEqual(ixDisc('initialize_marketplace'));+ expect(new PublicKey(ix.data.subarray(8, 40)).toBase58()).toBe(minter.toBase58());+ expect(ix.keys.map((k) => [k.pubkey.toBase58(), k.isSigner, k.isWritable])).toEqual([+ [marketplace.toBase58(), false, true],+ [authority.toBase58(), true, true],+ [SystemProgram.programId.toBase58(), false, false],+ ]);+ });+});++describe('IDL consistency', () => {+ it('declares the same program id baked into the lib', () => {+ expect(idl.address).toBe(SKILL_LICENSE_PROGRAM_ID);+ });++ it('exposes the five program instructions', () => {+ expect(idl.instructions.map((i) => i.name).sort()).toEqual(+ [+ 'burn_skill_license',+ 'initialize_marketplace',+ 'mint_skill_license',+ 'revoke_skill_license',+ 'set_minter',+ ].sort(),+ );+ });+});diff --git a/vercel.json b/vercel.jsonindex d48130ecc..80799c768 100644--- a/vercel.json+++ b/vercel.json@@ -2441,6 +2441,10 @@"src": "/api/users/referral-claim","dest": "/api/users/referral-claim.js"},+ {+ "src": "/api/users/lookup",+ "dest": "/api/users/lookup.js"+ },{"src": "/api/threews/subdomain","dest": "/api/threews/subdomain.js"@@ -2889,6 +2893,14 @@"src": "/api/subscriptions/plans(/.*)?","dest": "/api/subscriptions/plans.js"},+ {+ "src": "/api/subscriptions/subscribe",+ "dest": "/api/subscriptions/subscribe.js"+ },+ {+ "src": "/api/subscriptions/verify",+ "dest": "/api/subscriptions/verify.js"+ },{"src": "/api/subscriptions(/.*)?","dest": "/api/subscriptions/index.js"