Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: surface creator subscription income in the earnings dashboard
miniaturization9be2bb12a5b4
diff --git a/api/billing/revenue.js b/api/billing/revenue.jsindex e00e4a239..0af9e45d8 100644--- a/api/billing/revenue.js+++ b/api/billing/revenue.js@@ -97,6 +97,71 @@ export default wrap(async (req, res) => {tsParams,);+ // ── Subscription income ──────────────────────────────────────────────────+ // Creator subscriptions (subscription_plans → creator_subscriptions →+ // subscription_payments) settle the creator leg DIRECTLY to the creator's+ // wallet on-chain, so they never write agent_revenue_events and are absent+ // from net_total / the withdrawable balance. Surface them here as a SEPARATE,+ // USD-denominated figure (amount_usd is numeric(8,2), not atomic units) so the+ // creator sees their full income without ever mixing units or double-counting+ // against the platform-custodied withdrawal pool. When filtering by agent we+ // count only plans scoped to that agent; creator-wide plans show in the+ // all-agents view. `subAgentFilter` reuses the same positional params as the+ // revenue queries above (so $4 is agent_id when present).+ const subAgentFilter = agentId ? `AND pl.agent_id = $4::uuid` : '';+ const [subSummaryRow] = await sql(+ `+ SELECT+ COALESCE(SUM(sp.amount_usd), 0)::numeric AS income_usd,+ COUNT(*)::int AS payment_count+ FROM subscription_payments sp+ JOIN creator_subscriptions cs ON cs.id = sp.subscription_id+ JOIN subscription_plans pl ON pl.id = cs.plan_id+ WHERE pl.creator_id = $1+ AND sp.status = 'succeeded'+ AND sp.paid_at BETWEEN $2 AND $3+ ${subAgentFilter}+ `,+ filterParams,+ );++ // Current-state counts (not date-bounded): active subscribers + active plans.+ const subStateAgentFilter = agentId ? `AND pl.agent_id = $2::uuid` : '';+ const subStateParams = agentId ? [user.id, agentId] : [user.id];+ const [subStateRow] = await sql(+ `+ SELECT+ COUNT(*) FILTER (WHERE cs.status = 'active')::int AS active_subscribers,+ COUNT(DISTINCT pl.id)::int AS plan_count+ FROM subscription_plans pl+ LEFT JOIN creator_subscriptions cs ON cs.plan_id = pl.id+ WHERE pl.creator_id = $1+ AND pl.active = true+ ${subStateAgentFilter}+ `,+ subStateParams,+ );++ const subTsAgentFilter = agentId ? `AND pl.agent_id = $5::uuid` : '';+ const subTimeseries = await sql(+ `+ SELECT+ date_trunc($4, sp.paid_at) AS period,+ COALESCE(SUM(sp.amount_usd), 0)::numeric AS income_usd,+ COUNT(*)::int AS count+ FROM subscription_payments sp+ JOIN creator_subscriptions cs ON cs.id = sp.subscription_id+ JOIN subscription_plans pl ON pl.id = cs.plan_id+ WHERE pl.creator_id = $1+ AND sp.status = 'succeeded'+ AND sp.paid_at BETWEEN $2 AND $3+ ${subTsAgentFilter}+ GROUP BY period+ ORDER BY period+ `,+ tsParams,+ );+return json(res, 200, {summary: {gross_total: Number(summaryRow.gross_total),@@ -116,5 +181,18 @@ export default wrap(async (req, res) => {net_total: Number(r.net_total),count: r.count,})),+ // USD-denominated, paid directly to the creator wallet (not withdrawable+ // from the platform pool — kept distinct from `summary` above by design).+ subscriptions: {+ income_usd: Number(subSummaryRow?.income_usd ?? 0),+ payment_count: subSummaryRow?.payment_count ?? 0,+ active_subscribers: subStateRow?.active_subscribers ?? 0,+ plan_count: subStateRow?.plan_count ?? 0,+ },+ subscription_timeseries: subTimeseries.map((r) => ({+ period: r.period instanceof Date ? r.period.toISOString().slice(0, 10) : String(r.period),+ income_usd: Number(r.income_usd),+ count: r.count,+ })),});});diff --git a/prompts/monetization-prompts/17-database-schema-creator-payouts.md b/prompts/monetization-prompts/17-database-schema-creator-payouts.mddeleted file mode 100644index 3f1cda6a7..000000000--- a/prompts/monetization-prompts/17-database-schema-creator-payouts.md+++ /dev/null@@ -1,74 +0,0 @@-# Prompt 17: Database Schema for Creator Payouts--## Objective-Create database tables to manage creator earnings and track payout (withdrawal) transactions.--## Explanation-Creators need a way to withdraw their earnings. This requires a system to track their current balance, record each payout request, and log the status of the transaction. This prompt sets up the database foundation for the creator payout system.--## Instructions-1. **Locate the Schema File:**- * Open `api/_lib/schema.sql`.--2. **Add a `creator_balances` Table:**- * This table will hold the current withdrawable balance for each creator. It acts as a ledger.- * Columns:- * `user_id` (PRIMARY KEY, Foreign key to `users(id)`).- * `balance` (BIGINT, the current balance in the smallest currency unit).- * `currency_mint` (TEXT).- * `updated_at`.--3. **Add a `creator_payouts` Table:**- * This table will log every withdrawal attempt.- * Columns:- * `id` (UUID PRIMARY KEY).- * `user_id` (Foreign key to `users(id)`).- * `amount` (BIGINT).- * `currency_mint` (TEXT).- * `destination_address` (TEXT, the creator's wallet address for the payout).- * `status` (ENUM: 'requested', 'processing', 'completed', 'failed').- * `transaction_id` (TEXT, the on-chain transaction signature of the payout).- * `created_at`, `updated_at`.--## SQL Example--```sql--- In api/_lib/schema.sql--CREATE TABLE creator_balances (- user_id UUID PRIMARY KEY REFERENCES users(id),- balance BIGINT NOT NULL DEFAULT 0,- currency_mint TEXT NOT NULL,- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);--CREATE TYPE payout_status AS ENUM ('requested', 'processing', 'completed', 'failed');--CREATE TABLE creator_payouts (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL REFERENCES users(id),- amount BIGINT NOT NULL,- currency_mint TEXT NOT NULL,- destination_address TEXT NOT NULL,- status payout_status NOT NULL DEFAULT 'requested',- transaction_id TEXT,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);--CREATE INDEX idx_creator_payouts_user_id ON creator_payouts(user_id);-```--<!-- 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-prompts/17-database-schema-creator-payouts.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-prompts/21-skill-subscription-model-backend.md b/prompts/monetization-prompts/21-skill-subscription-model-backend.mddeleted file mode 100644index 962cf7c5b..000000000--- a/prompts/monetization-prompts/21-skill-subscription-model-backend.md+++ /dev/null@@ -1,82 +0,0 @@-----status: not-started------# Prompt 21: Skill Subscription Model - Backend--## Objective-Implement the backend infrastructure for a subscription model, where users pay a recurring fee for access to all of an agent's paid skills.--## Explanation-Subscriptions provide predictable revenue for creators and value for active users. This is a significant feature requiring new database tables and logic for managing subscription status and recurring payments. We'll focus on the backend setup first. For payments, we could use a service like Helio to manage recurring Solana payments.--## Instructions-- [ ] **Database Schema Changes:**- - [ ] Create a new table: `agent_subscriptions`.- - [ ] Columns: `id`, `user_id`, `agent_id`, `status` (e.g., 'active', 'cancelled', 'past_due'), `expires_at` (Timestamp), `payment_provider_subscription_id` (String).- - [ ] Add a new table `agent_subscription_plans`: `id`, `agent_id`, `amount`, `currency_mint`, `interval` (e.g., 'month', 'year').--- [ ] **API for Subscription Plans:**- - [ ] Create CRUD APIs for creators to manage their subscription plans (`/api/agents/:id/subscription-plans`). A creator might offer monthly and yearly tiers.--- [ ] **API for Creating a Subscription:**- - [ ] Create an endpoint `POST /api/subscriptions/create`.- - [ ] This endpoint would interact with a recurring payment provider (e.g., Helio). It would create a payment link or subscription plan with the provider and return it to the frontend.--- [ ] **Webhook for Payment Events:**- - [ ] Create a webhook endpoint `POST /api/webhooks/payments`.- - [ ] The payment provider will call this webhook to notify your app of events like `subscription.created`, `subscription.payment_succeeded`, `subscription.payment_failed`.- - [ ] When a `payment_succeeded` event is received, you should:- - [ ] Find the corresponding subscription in your `agent_subscriptions` table.- - [ ] Update its `status` to 'active'.- - [ ] Set the `expires_at` to the end of the new billing period (e.g., now + 30 days).--- [ ] **Update Skill Gating Logic:**- - [ ] Modify the skill gating logic from Prompt 19.- - [ ] Before checking for individual skill ownership in `unlocked_skills`, it should first check for an active subscription.- - [ ] Query the `agent_subscriptions` table for the `user_id` and `agent_id`. If an active subscription exists (`status` = 'active' and `expires_at` > now), allow skill execution.--## Webhook Logic Example--```javascript-// POST /api/webhooks/payments-export default async function handler(req, res) {- // 1. Verify the webhook signature to ensure it's from the payment provider- if (!isSignatureValid(req)) {- return res.status(403).send('Invalid signature');- }-- const event = req.body;-- // 2. Handle the event- switch (event.type) {- case 'subscription.payment_succeeded':- const subId = event.data.subscription_id;- const newExpiry = new Date(event.data.new_expiry_timestamp);-- // Find subscription in DB by payment_provider_subscription_id- await db.updateSubscriptionStatus(subId, 'active', newExpiry);- break;- case 'subscription.payment_failed':- // ... handle failed payments, maybe set status to 'past_due'- break;- }-- // 3. Acknowledge receipt- res.status(200).send('Acknowledged');-}-```--<!-- 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-prompts/21-skill-subscription-model-backend.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/src/dashboard-next/pages/monetize.js b/src/dashboard-next/pages/monetize.jsindex 8d7c25d8e..ebf1c0cd0 100644--- a/src/dashboard-next/pages/monetize.js+++ b/src/dashboard-next/pages/monetize.js@@ -257,6 +257,22 @@ function renderHero({ available, revenue, creatorPlans, subscribedTo, pendingRoy}),);+ // Subscription income is USD-denominated and settles straight to the creator's+ // wallet (not part of the withdrawable platform balance), so it gets its own+ // card rather than being folded into "Total earned" / "Available to withdraw".+ const subIncomeUsd = Number(revenue?.subscriptions?.income_usd ?? 0);+ const activeSubs = Number(revenue?.subscriptions?.active_subscribers ?? 0);+ wrap.appendChild(+ heroCard({+ title: 'Subscription income',+ value: subIncomeUsd > 0 ? `$${subIncomeUsd.toFixed(2)}` : '$0.00',+ sub: activeSubs > 0+ ? `${activeSubs} active subscriber${activeSubs === 1 ? '' : 's'} · paid directly to your wallet (last 30 days)`+ : 'Recurring plan revenue, paid directly to your wallet.',+ color: 'var(--nxt-accent)',+ }),+ );+return wrap;}diff --git a/tasks/CLEANUP-MANIFEST.md b/tasks/CLEANUP-MANIFEST.mdindex 2d0c64d07..b6165f66e 100644--- a/tasks/CLEANUP-MANIFEST.md+++ b/tasks/CLEANUP-MANIFEST.md@@ -100,3 +100,20 @@ verifiably present in code:| prompts/avatar-animation-hardening/06-final-qa-and-promote.md | runtime fallen-pose guard in animation-manager.js; regression corpus tests/animation-upright-invariant.test.js green |**KEEP (notable):** all monetization/ + monetization-prompts/ (subscriptions, bundles, NFT receipts, fiat, creator payouts, email, admin — none shipped); all feature-innovation/ (improvement specs, gaps remain); all living-agents/, living-wallet/, wallet-innovation/, inventions/, moonshots/, agent-studio 04-12, vanity-* (named modules absent).+++## monetization revenue (2026-06-21) — subscription earnings visibility shipped + 2 specs retired++Built: creator subscription income now surfaced in the earnings dashboard.+- api/billing/revenue.js: adds a block (income_usd, payment_count,+ active_subscribers, plan_count) + , sourced from+ subscription_payments→creator_subscriptions→subscription_plans. USD-denominated+ and kept SEPARATE from the atomic net_total/withdrawable balance (subscription+ legs settle creator-direct on-chain) so there is no unit-mixing or double-pay.+- src/dashboard-next/pages/monetize.js: new "Subscription income" hero card.++Retired (feature verified shipped):+| spec | evidence |+| --- | --- |+| monetization-prompts/21-skill-subscription-model-backend.md | subscription_plans/creator_subscriptions/subscription_payments (schema.sql:1205+); api/subscriptions/{plans,subscribe,verify}.js; api/_lib/subscription-billing.js; gating in api/_lib/skill-access.js (creator_subscriptions check); process-subscriptions cron in api/cron/[name].js |+| monetization-prompts/17-database-schema-creator-payouts.md | creator payout function shipped via agent_revenue_events (balance ledger) + agent_withdrawals (payout log) + api/billing/{revenue,withdrawals,payout-wallets} + process-withdrawals cron; the spec-named creator_balances/creator_payouts tables are intentionally superseded by this canonical ledger |