Skip to content

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

Make skill_access_grants real: add migration + guard + grant-on-confirm test

nirholas0c932b1dc392
diff --git a/api/_lib/migrations/20260618000000_skill_access_grants.sql b/api/_lib/migrations/20260618000000_skill_access_grants.sql
new file mode 100644
index 000000000..37062e3a5
--- /dev/null
+++ b/api/_lib/migrations/20260618000000_skill_access_grants.sql
@@ -0,0 +1,51 @@
+-- Migration: skill_access_grants — the authoritative "does user X hold access to
+-- skill Y on agent Z?" record, created the moment a payment is confirmed.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20260618000000_skill_access_grants.sql
+-- Idempotent.
+--
+-- skill_purchases tracks the PAYMENT lifecycle (pending → confirmed → …).
+-- skill_access_grants tracks the resulting ACCESS, decoupled from payment so a
+-- grant can be issued by a one-time purchase, a time-pass, a gift, or any future
+-- entitlement path without re-modelling each one onto the purchase row.
+--
+-- Populated by finalizeSkillConfirmation() in api/_lib/purchase-confirm.js once
+-- an on-chain payment is verified. Grant shape:
+-- expires_at NULL — permanent access (one-time purchase)
+-- expires_at <timestamptz> — time-limited access (expires at the window)
+-- uses_left NULL — unmetered access (time-based model)
+-- uses_left <integer> — metered access, decremented per use
+-- A user holds at most one grant per (agent, skill); re-purchase extends it via
+-- ON CONFLICT (user_id, agent_id, skill_name) DO UPDATE.
+
+begin;
+
+create table if not exists skill_access_grants (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ skill_name text not null,
+ purchase_id uuid references skill_purchases(id) on delete set null,
+ expires_at timestamptz,
+ uses_left integer,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (user_id, agent_id, skill_name)
+);
+
+-- Hot path: "what does this user own?" (collection page) and the per-skill
+-- access gate the executor consults before running a paid skill.
+create index if not exists idx_skill_access_grants_user
+ on skill_access_grants (user_id);
+create index if not exists idx_skill_access_grants_agent
+ on skill_access_grants (agent_id);
+create index if not exists idx_skill_access_grants_lookup
+ on skill_access_grants (user_id, agent_id, skill_name);
+
+-- Auto-bump updated_at on any UPDATE; reuse the standard trigger function that
+-- skill_purchases and the rest of the schema already rely on.
+do $$ begin
+ create trigger skill_access_grants_set_updated_at before update on skill_access_grants
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
+
+commit;
diff --git a/prompts/monetization/14-grant-skill-access.md b/prompts/monetization/14-grant-skill-access.md
deleted file mode 100644
index bed574d71..000000000
--- a/prompts/monetization/14-grant-skill-access.md
+++ /dev/null
@@ -1,84 +0,0 @@
-# Prompt 14: Grant Skill Access After Payment
-
-## Objective
-Integrate the logic for creating a `skill_access_grants` record into the payment confirmation flow.
-
-## Explanation
-This prompt links the successful payment confirmation (Prompt 12) with the access grant system (Prompt 13). Once the backend has verified a user's payment on-chain, it must immediately create the corresponding access grant in the database.
-
-## Instructions
-1. **File to Edit:**
- * Open the backend endpoint for payment confirmation: `POST /api/payments/confirm-skill-payment`.
-
-2. **Integrate Grant Creation:**
- * Locate the spot in your code immediately after the payment status has been successfully updated to `completed`.
- * Before sending the final success response to the client, add a call to your database logic to insert a new row into the `skill_access_grants` table.
-
-3. **Determine Grant Rules:**
- * You need to decide what kind of access this payment provides. For a simple one-time payment model, you could grant access for a fixed duration.
- * **Example Rule:** Grant access for 24 hours from the time of purchase.
- * To implement this, calculate the expiry timestamp.
-
-4. **Populate the Grant Record:**
- * The new `skill_access_grants` row should be populated with:
- * `user_id`: From the authenticated user session.
- * `agent_id`, `skill_name`: From the `paymentIntent` record you fetched from the database.
- * `payment_id`: The ID of the now-completed payment.
- * `expires_at`: The calculated expiry timestamp (e.g., `Date.now() + 24 * 60 * 60 * 1000`).
- * `uses_left`: `NULL` for this time-based model.
-
-5. **Transactional Integrity:**
- * Ideally, the database operations for updating the payment status and creating the access grant should be wrapped in a database transaction. This ensures that either both operations succeed or both fail, preventing a state where a user pays but doesn't get access.
-
-## Code Example (Backend - `confirm-skill-payment` logic)
-
-This refines the example from Prompt 12.
-
-```javascript
-// Inside your /api/payments/confirm-skill-payment endpoint handler
-
-// ... after successfully verifying the on-chain transaction ...
-
-try {
- // Use a database transaction to ensure atomicity
- await db.transaction(async (trx) => {
- // c. Update Payment Status
- await trx.update('skill_payments', { status: 'completed', signature: signature })
- .where({ id: paymentId });
-
- // d. Grant Skill Access
- const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours from now
-
- await trx.insert({
- user_id: user.id,
- agent_id: paymentIntent.agentId,
- skill_name: paymentIntent.skillName,
- payment_id: paymentId,
- expires_at: expiresAt,
- uses_left: null, // This is a time-based grant
- }).into('skill_access_grants');
- });
-
- // e. Respond for frontend to continue
- res.status(200).json({ success: true, message: 'Payment confirmed and access granted.' });
-
-} catch (error) {
- console.error('Error in confirmation transaction:', error);
- // The database transaction should automatically roll back on error
- res.status(500).json({ error: 'Failed to finalize payment.' });
-}
-```
-
-<!-- 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-grant-skill-access.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/tests/api/schema-column-guard.test.js b/tests/api/schema-column-guard.test.js
index 3bd74c4b2..50fc6fba5 100644
--- a/tests/api/schema-column-guard.test.js
+++ b/tests/api/schema-column-guard.test.js
@@ -91,6 +91,14 @@ const REQUIRED = [
['skill_purchases', 'tipped_amount'],
['skill_purchases', 'referrer_user_id'],
['agent_skill_prices', 'mint_decimals'],
+ // skill_access_grants (20260618000000_skill_access_grants.sql) — the access
+ // record finalizeSkillConfirmation() writes on payment confirm.
+ ['skill_access_grants', 'user_id'],
+ ['skill_access_grants', 'agent_id'],
+ ['skill_access_grants', 'skill_name'],
+ ['skill_access_grants', 'purchase_id'],
+ ['skill_access_grants', 'expires_at'],
+ ['skill_access_grants', 'uses_left'],
// purchase_receipts
['purchase_receipts', 'purchase_id'],
['purchase_receipts', 'receipt_json'],
diff --git a/tests/api/skill-access-grant-on-confirm.test.js b/tests/api/skill-access-grant-on-confirm.test.js
new file mode 100644
index 000000000..cc19e2d1d
--- /dev/null
+++ b/tests/api/skill-access-grant-on-confirm.test.js
@@ -0,0 +1,116 @@
+// Prompt 14 — grant skill access after payment.
+//
+// Proves the integration point: once finalizeSkillConfirmation() marks an
+// on-chain payment 'confirmed', it MUST insert the corresponding row into
+// skill_access_grants (the authoritative access record). Drives the EVM path of
+// confirmSkillPurchase() because it reaches finalize without the Solana-Pay
+// reference dance, and routes the mocked `sql` by query content so the test is
+// not coupled to call ordering.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+
+const SELLER_ADDR = '0x000000000000000000000000000000000000dEaD';
+const SELLER_USER = 'seller-user-1';
+const grantState = { kind: 'permanent', validUntil: null };
+let calls = [];
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ const q = strings.join(' ? ');
+ calls.push({ q, values });
+ // resolvePayoutAddress — must precede the agent_identities check below.
+ if (/agent_payout_wallets/i.test(q)) return [{ address: SELLER_ADDR }];
+ // getSellerUserId
+ if (/select\s+user_id\s+from\s+agent_identities/i.test(q)) return [{ user_id: SELLER_USER }];
+ // idempotency dupe pre-check (no other purchase claimed this tx)
+ if (/select\s+id\s+from\s+skill_purchases/i.test(q)) return [];
+ // payer-wallet binding check — wallet is linked to the buyer
+ if (/from\s+user_wallets/i.test(q)) return [{ ok: 1 }];
+ // finalize: the atomic confirm UPDATE returns the winning row
+ if (/set\s+status\s*=\s*'confirmed'/i.test(q))
+ return [{ id: PUR.id, kind: grantState.kind, valid_until: grantState.validUntil }];
+ // claim: tx-hash claim UPDATE on the still-pending row
+ if (/update\s+skill_purchases\s+set\s+tx_signature/i.test(q)) return [{ id: PUR.id }];
+ return [];
+ }),
+}));
+
+const evmState = { result: { status: 'match', from: '0xPAYER' } };
+vi.mock('../../api/_lib/evm-payment-verify.js', () => ({
+ verifyEvmUsdcPayment: vi.fn(async () => evmState.result),
+ evmChainId: vi.fn((chain) => (chain === 'base' ? 8453 : null)),
+}));
+
+const notify = vi.fn(async () => {});
+vi.mock('../../api/_lib/notify.js', () => ({ insertNotification: notify }));
+
+vi.mock('../../api/_lib/solana/rpc-fallback.js', () => ({
+ rpcFallbackFromEnv: vi.fn(() => ({ withFallback: vi.fn() })),
+}));
+
+const { confirmSkillPurchase } = await import('../../api/_lib/purchase-confirm.js');
+
+const PUR = {
+ id: '11111111-1111-1111-1111-111111111111',
+ user_id: '22222222-2222-2222-2222-222222222222',
+ agent_id: '33333333-3333-3333-3333-333333333333',
+ skill: 'translate',
+ amount: '1000000',
+ currency_mint: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ chain: 'base',
+ mint_decimals: 6,
+ status: 'pending',
+ expires_at: null,
+ referrer_user_id: null,
+};
+
+function grantInsert() {
+ return calls.find((c) => /insert\s+into\s+skill_access_grants/i.test(c.q));
+}
+
+beforeEach(() => {
+ calls = [];
+ notify.mockClear();
+ grantState.kind = 'permanent';
+ grantState.validUntil = null;
+ evmState.result = { status: 'match', from: '0xPAYER' };
+});
+
+describe('finalizeSkillConfirmation → skill_access_grants', () => {
+ it('inserts a grant when an EVM payment confirms', async () => {
+ const out = await confirmSkillPurchase({ ...PUR }, { txHash: '0xTX' });
+ expect(out.status).toBe('confirmed');
+
+ const ins = grantInsert();
+ expect(ins, 'a skill_access_grants INSERT must be issued on confirm').toBeTruthy();
+ // VALUES (user_id, agent_id, skill_name, purchase_id, expires_at)
+ expect(ins.values).toEqual([PUR.user_id, PUR.agent_id, PUR.skill, PUR.id, null]);
+ });
+
+ it('grants permanent access (null expiry) for a one-time purchase', async () => {
+ await confirmSkillPurchase({ ...PUR }, { txHash: '0xTX' });
+ expect(grantInsert().values[4]).toBeNull();
+ });
+
+ it('grants time-limited access for a time_pass purchase', async () => {
+ grantState.kind = 'time_pass';
+ grantState.validUntil = '2026-07-01T00:00:00.000Z';
+ await confirmSkillPurchase({ ...PUR }, { txHash: '0xTX' });
+ expect(grantInsert().values[4]).toBe('2026-07-01T00:00:00.000Z');
+ });
+
+ it('does NOT insert a grant when the payment is still pending', async () => {
+ evmState.result = { status: 'pending' };
+ const out = await confirmSkillPurchase({ ...PUR }, { txHash: '0xTX' });
+ expect(out.status).toBe('pending');
+ expect(grantInsert()).toBeUndefined();
+ });
+
+ it('does NOT insert a grant before the buyer submits a tx hash', async () => {
+ const out = await confirmSkillPurchase({ ...PUR }, {});
+ expect(out.status).toBe('pending');
+ expect(grantInsert()).toBeUndefined();
+ });
+});