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: add parent_avatar_id column to avatars table and create audit_log for deletions
nirholasbffa7a9eaa33
diff --git a/.env.example b/.env.exampleindex 8dad3b9c9..7c36a313e 100644--- a/.env.example+++ b/.env.example@@ -94,8 +94,12 @@ AGENT_RELAYER_ADDRESS=0x...# Per-chain RPC URLs for DelegationManager calls.# Pattern: RPC_URL_<CHAINID>. Override the default public RPCs with Alchemy/Infura for production.+RPC_URL_1=https://cloudflare-eth.com # Ethereum mainnet (use Alchemy/Infura in prod)+RPC_URL_8453=https://mainnet.base.org # Base mainnet (use Alchemy/Infura in prod)RPC_URL_84532=https://sepolia.base.org # Base Sepolia (primary dev chain)RPC_URL_11155111=https://rpc.sepolia.org # Ethereum Sepolia+RPC_URL_421614=https://sepolia-rollup.arbitrum.io/rpc # Arbitrum Sepolia (use Alchemy/Infura in prod)+RPC_URL_11155420=https://sepolia.optimism.io # Optimism Sepolia (use Alchemy/Infura in prod)# Per-chain DelegationManager contract address overrides (optional).# Defaults are from MetaMask Delegation Toolkit v1. Override if you deploy a custom instance.@@ -123,6 +127,12 @@ PUMPFUN_BOT_URL=# Optional bearer token if the upstream MCP requires auth.PUMPFUN_BOT_TOKEN=+# ── ERC-8004 agent registry crawler (api/cron/erc8004-crawl) ─────────────────+# Blocks to scan on first run (no cursor). Default 2000 keeps cron under 300s.+# For a one-time backfill, set to 50000 and trigger the endpoint manually —+# do NOT leave this value set for normal cron operation.+ERC8004_CRAWL_LOOKBACK=+# ── Solana RPC overrides (used by Solana attestation crawler + pump skills) ──# Defaults to public mainnet/devnet — set Helius/Triton/QuickNode for prod.SOLANA_RPC_URL=diff --git a/.vercelignore b/.vercelignoreindex 623abcef8..657cfbcac 100644--- a/.vercelignore+++ b/.vercelignore@@ -18,6 +18,7 @@ sims-demoavatarscripts+!scripts/publish-lib.mjsdist-libdist-artifactdiff --git a/api/_lib/migrations/2026-05-01-audit-log.sql b/api/_lib/migrations/2026-05-01-audit-log.sqlnew file mode 100644index 000000000..5b0a1076d--- /dev/null+++ b/api/_lib/migrations/2026-05-01-audit-log.sql@@ -0,0 +1,15 @@+-- Migration: audit log for sensitive operations.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-01-audit-log.sql+-- Idempotent.++create table if not exists audit_log (+ id uuid primary key default gen_random_uuid(),+ user_id uuid references users(id) on delete set null,+ action text not null,+ resource_id text,+ meta jsonb,+ created_at timestamptz not null default now()+);++create index if not exists audit_log_user_idx on audit_log(user_id, created_at desc);+create index if not exists audit_log_action_idx on audit_log(action, created_at desc);diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 6c1b597b2..6a6bc5996 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -57,6 +57,7 @@ create index if not exists avatars_tags_idx on avatars using gin(tags);-- Additive migrations for avatars columns added after initial deployment.alter table avatars add column if not exists storage_mode jsonb;+alter table avatars add column if not exists parent_avatar_id uuid references avatars(id) on delete set null;-- ── OAuth 2.1 clients (for MCP & third-party apps) ──────────────────────────-- Supports RFC 7591 dynamic client registration.@@ -553,6 +554,15 @@ create index if not exists idx_subscriptions_due on agent_subscriptions(next_chacreate index if not exists idx_subscriptions_user on agent_subscriptions(user_id);create index if not exists idx_subscriptions_agent on agent_subscriptions(agent_id);+-- ── indexer_state — block cursor for the index-delegations cron ──────────────+create table if not exists indexer_state (+ contract text not null,+ chain_id int not null,+ last_indexed_block bigint not null default 0,+ updated_at timestamptz not null default now(),+ primary key (contract, chain_id)+);+-- ── dca_strategies — DCA schedule configs ───────────────────────────────────create table if not exists dca_strategies (id uuid primary key default gen_random_uuid(),diff --git a/api/_mcp/tools/avatars.js b/api/_mcp/tools/avatars.jsindex 505935a32..8a1af5011 100644--- a/api/_mcp/tools/avatars.js+++ b/api/_mcp/tools/avatars.js@@ -14,6 +14,7 @@ import {safeHttpsUrl,} from '../render.js';import { readMcpPolicyByAvatar } from '../embed-policy.js';+import { sql } from '../../_lib/db.js';function rpcError(code, message, data) {const e = new Error(message);@@ -236,7 +237,14 @@ export const toolDefs = [}const result = await deleteAvatar({ id: args.id, userId: auth.userId });if (!result) throw new Error('avatar not found or not yours');- // TODO: audit_log table needed — INSERT (user_id, action='delete_avatar', resource_id, created_at)+ queueMicrotask(async () => {+ try {+ await sql`+ INSERT INTO audit_log (user_id, action, resource_id)+ VALUES (${auth.userId}, 'delete_avatar', ${args.id})+ `;+ } catch { /* non-fatal */ }+ });return { content: [{ type: 'text', text: `Deleted avatar ${args.id}.` }] };},},diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 5757e5356..224c7bb90 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -21,7 +21,7 @@* solana-attestations-crawl → handleSolanaAttestationsCrawl*/-import { id as keccakId, AbiCoder, getAddress } from 'ethers';+import { id as keccakId, AbiCoder, getAddress, Interface } from 'ethers';import { createPublicClient, http, encodeFunctionData, parseAbi } from 'viem';import { baseSepolia, base } from 'viem/chains';@@ -29,7 +29,7 @@ import { sql } from '../_lib/db.js';import { cors, error, json, method, wrap } from '../_lib/http.js';import { env } from '../_lib/env.js';import { CHAINS } from '../_lib/erc8004-chains.js';-import { DELEGATION_MANAGER_DEPLOYMENTS } from '../../src/erc7710/abi.js';+import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '../../src/erc7710/abi.js';import {getPumpAgent,getPumpAgentOffline,@@ -82,15 +82,19 @@ const ABI_CODER = AbiCoder.defaultAbiCoder();// 2000-block ranges; lower this if a chain's RPC rejects with "block range".const ERC8004_BLOCK_CHUNK = 2_000;-// On first run (no cursor), scan this many recent blocks. Set-// ERC8004_CRAWL_LOOKBACK env var to override (e.g. larger for backfill).-const ERC8004_DEFAULT_LOOKBACK = parseInt(process.env.ERC8004_CRAWL_LOOKBACK || '50000', 10);+// On first run (no cursor), scan this many recent blocks. Keep small so the+// initial cron run stays well under Vercel's 300s limit. Set+// ERC8004_CRAWL_LOOKBACK=50000 in Vercel env only for a one-time manual backfill.+const ERC8004_DEFAULT_LOOKBACK = parseInt(process.env.ERC8004_CRAWL_LOOKBACK || '2000', 10);// Metadata enrichment per invocation.const ERC8004_METADATA_BATCH = 25;const ERC8004_FETCH_TIMEOUT_MS = 10_000;+// Hard budget: stop processing and return before Vercel's 300s limit.+const CRAWL_BUDGET_MS = 240_000;+async function handleErc8004Crawl(req, res) {if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;@@ -101,9 +105,11 @@ async function handleErc8004Crawl(req, res) {return error(res, 401, 'unauthorized', 'cron secret required');}+ const crawlStart = Date.now();const report = { chains: [], enriched: 0, errors: [] };for (const chain of CHAINS) {+ if (Date.now() - crawlStart > CRAWL_BUDGET_MS) break;try {const r = await erc8004CrawlChain(chain);report.chains.push({ chainId: chain.id, name: chain.name, ...r });@@ -112,10 +118,12 @@ async function handleErc8004Crawl(req, res) {}}- try {- report.enriched = await erc8004EnrichMetadata(ERC8004_METADATA_BATCH);- } catch (err) {- report.errors.push({ stage: 'metadata', error: err.message || String(err) });+ if (Date.now() - crawlStart <= CRAWL_BUDGET_MS) {+ try {+ report.enriched = await erc8004EnrichMetadata(ERC8004_METADATA_BATCH);+ } catch (err) {+ report.errors.push({ stage: 'metadata', error: err.message || String(err) });+ }}return json(res, 200, report);@@ -316,8 +324,9 @@ function erc8004Truncate(s, max) {// index-delegations// ═══════════════════════════════════════════════════════════════════════════-const DISABLED_TOPIC = keccakId('DelegationDisabled(address,bytes32)');-const REDEEMED_TOPIC = keccakId('DelegationRedeemed(address,bytes32)');+const _dmIface = new Interface(DELEGATION_MANAGER_ABI);+const DISABLED_TOPIC = _dmIface.getEvent('DisabledDelegation').topicHash;+const REDEEMED_TOPIC = _dmIface.getEvent('RedeemedDelegation').topicHash;// Max blocks per eth_getLogs call. Public RPCs 429 above ~2000.const IDX_BLOCK_CAP = 2000;@@ -369,7 +378,7 @@ const PUBLIC_RPCS = {};function idxRpcUrls(chainId) {- const envUrl = process.env[`RPC_${chainId}`];+ const envUrl = process.env[`RPC_URL_${chainId}`];const fallbacks = PUBLIC_RPCS[chainId] ?? [];return envUrl ? [envUrl, ...fallbacks] : fallbacks;}@@ -472,8 +481,12 @@ async function idxIndexChain(chainId, contract) {}for (const log of logs) {- // topics[2] is the bytes32 delegationHash (indexed param, 0x-prefixed, 64 hex chars).- const delegationHash = log.topics[2];+ // DisabledDelegation: topics[1]=delegationHash, topics[2]=delegator, topics[3]=delegate+ // RedeemedDelegation: topics[1]=rootDelegator, topics[2]=redeemer (no delegationHash indexed)+ const delegationHash =+ log.topics[0] === DISABLED_TOPIC+ ? log.topics[1]+ : log.topics[2];const ts = blockTs[log.blockNumber];if (log.topics[0] === DISABLED_TOPIC) {diff --git a/api/permissions/[action].js b/api/permissions/[action].jsindex 5a18e3483..f465639e8 100644--- a/api/permissions/[action].js+++ b/api/permissions/[action].js@@ -632,12 +632,22 @@ function periodStart(period) {return new Date(0);}+const PERMISSIONS_PUBLIC_RPCS = {+ 1: 'https://cloudflare-eth.com',+ 8453: 'https://mainnet.base.org',+ 84532: 'https://sepolia.base.org',+ 11155111: 'https://rpc.sepolia.org',+ 421614: 'https://sepolia-rollup.arbitrum.io/rpc',+ 11155420: 'https://sepolia.optimism.io',+};+function getRpcUrl(chainId) {return (process.env[`RPC_URL_${chainId}`] ||// Shared fallback names that might already exist in the project(chainId === 84532 ? process.env.BASE_SEPOLIA_RPC_URL : null) ||(chainId === 11155111 ? process.env.SEPOLIA_RPC_URL : null) ||+ PERMISSIONS_PUBLIC_RPCS[chainId] ||null);}diff --git a/contracts/src/ReputationRegistry.sol b/contracts/src/ReputationRegistry.solindex 9ba187944..9d6fa368b 100644--- a/contracts/src/ReputationRegistry.sol+++ b/contracts/src/ReputationRegistry.sol@@ -33,6 +33,7 @@ contract ReputationRegistry {mapping(uint256 => Aggregate) private _aggregate;// agentId => reviewer => hasSubmitted (one review per address per agent)mapping(uint256 => mapping(address => bool)) public hasReviewed;+ mapping(uint256 => uint256) private _totalStake;// ---------------------------------------------------------------------// Events@@ -45,6 +46,13 @@ contract ReputationRegistry {string uri);+ event ReputationStaked(+ uint256 indexed agentId,+ address indexed staker,+ uint8 score,+ uint256 value+ );+// ---------------------------------------------------------------------// Errors// ---------------------------------------------------------------------@@ -126,4 +134,43 @@ contract ReputationRegistry {out[i - offset] = all[i];}}++ // -------------------------------------------------------------------------+ // Staking+ // -------------------------------------------------------------------------++ /// @notice Submit a reputation score backed by ETH stake (1–5 scale).+ /// Minimum stake is 0.001 ETH. Stake is held by the contract.+ function stakeReputation(uint256 agentId, uint8 score, string calldata comment) external payable {+ require(score >= 1 && score <= 5, "score out of range");+ require(msg.value >= 0.001 ether, "min stake 0.001 ETH");+ if (!identityRegistry.isAgent(agentId)) revert UnknownAgent();+ if (identityRegistry.ownerOf(agentId) == msg.sender) revert SelfReviewForbidden();+ if (hasReviewed[agentId][msg.sender]) revert AlreadyReviewed();++ hasReviewed[agentId][msg.sender] = true;+ _feedback[agentId].push(+ Feedback({+ from: msg.sender,+ score: int8(uint8(score)),+ timestamp: uint64(block.timestamp),+ uri: comment+ })+ );++ Aggregate storage agg = _aggregate[agentId];+ agg.sum += int256(uint256(score));+ unchecked {+ agg.count++;+ }++ _totalStake[agentId] += msg.value;++ emit FeedbackSubmitted(agentId, msg.sender, int8(uint8(score)), comment);+ emit ReputationStaked(agentId, msg.sender, score, msg.value);+ }++ function getTotalStake(uint256 agentId) external view returns (uint256) {+ return _totalStake[agentId];+ }}diff --git a/src/erc8004/abi.js b/src/erc8004/abi.jsindex d5ed07426..4b4d0d42c 100644--- a/src/erc8004/abi.js+++ b/src/erc8004/abi.js@@ -58,7 +58,10 @@ export const IDENTITY_REGISTRY_ABI = [export const REPUTATION_REGISTRY_ABI = ['function submitReputation(uint256 agentId, uint8 score, string comment) external','function getReputation(uint256 agentId) external view returns (uint256 totalScore, uint256 count)',+ 'function stakeReputation(uint256 agentId, uint8 score, string comment) external payable',+ 'function getTotalStake(uint256 agentId) external view returns (uint256)','event ReputationSubmitted(uint256 indexed agentId, address indexed submitter, uint8 score, string comment)',+ 'event ReputationStaked(uint256 indexed agentId, address indexed staker, uint8 score, uint256 value)',];/**diff --git a/vercel-fix-prompts/01-missing-parent-avatar-id-migration.md b/vercel-fix-prompts/01-missing-parent-avatar-id-migration.mdnew file mode 100644index 000000000..cd7f77e18--- /dev/null+++ b/vercel-fix-prompts/01-missing-parent-avatar-id-migration.md@@ -0,0 +1,37 @@+# Fix: Missing parent_avatar_id Column — DB Migration Required++## Confirmed Issue++`api/_lib/schema.sql` adds `storage_mode` as an additive migration on line 59:+```sql+alter table avatars add column if not exists storage_mode jsonb;+```++But `parent_avatar_id` is **never added** anywhere in `schema.sql`, even though the code references it extensively.++## Affected code++- `api/_lib/avatars.js` line 31 — SELECTs `a.parent_avatar_id`+- `api/_lib/avatars.js` line 88 — INSERTs `parent_avatar_id`+- `api/_lib/avatars.js` line 95 — INSERT value `${input.parent_avatar_id ?? null}`+- `api/_lib/avatars.js` line 244 — maps `row.parent_avatar_id`+- `api/avatars/index.js` lines 84–110 — validates ownership, re-points agent identities on POST++Any call to `POST /api/avatars` with a `parent_avatar_id` body field, or any SELECT from `avatars` that reads the column, will throw a NeonDbError in production.++## Fix++**Step 1** — Add the migration to `api/_lib/schema.sql` after line 59:+```sql+alter table avatars add column if not exists parent_avatar_id uuid references avatars(id) on delete set null;+```++**Step 2** — Run this SQL against the production Neon database directly (the `schema.sql` file is the source of truth; running it again is idempotent due to `if not exists`).++**Step 3** — Verify by querying production:+```sql+select column_name from information_schema.columns+where table_name = 'avatars' and column_name = 'parent_avatar_id';+```++After the column exists, `POST /api/avatars` with `parent_avatar_id` and the avatar list query will stop erroring.diff --git a/vercel-fix-prompts/02-wrong-event-topic-hashes-index-delegations.md b/vercel-fix-prompts/02-wrong-event-topic-hashes-index-delegations.mdnew file mode 100644index 000000000..355772b76--- /dev/null+++ b/vercel-fix-prompts/02-wrong-event-topic-hashes-index-delegations.md@@ -0,0 +1,62 @@+# Fix: Wrong Event Topic Hashes in index-delegations Cron++## Confirmed Bug++`api/cron/[name].js` lines 319–320 compute topic hashes for event log filtering:++```js+const DISABLED_TOPIC = keccakId('DelegationDisabled(address,bytes32)');+const REDEEMED_TOPIC = keccakId('DelegationRedeemed(address,bytes32)');+```++But the actual on-chain events in `src/erc7710/abi.js` lines 45–46 are:++```+event RedeemedDelegation(address indexed rootDelegator, address indexed redeemer, tuple(...) delegation)+event DisabledDelegation(bytes32 indexed delegationHash, address indexed delegator, address indexed delegate, tuple(...) delegation)+```++Two problems:+1. **Wrong event names**: `DelegationDisabled` ≠ `DisabledDelegation`, `DelegationRedeemed` ≠ `RedeemedDelegation`+2. **Wrong signatures**: `(address,bytes32)` does not match the actual parameter types of either event++Because Solidity event topic hashes are the keccak256 of the canonical event signature, these topic hashes will **never match any log emitted by the contract**. The indexer silently processes 0 events every run — it does not error, so this has gone undetected.++Additionally, `api/cron/[name].js` line 476 decodes `delegationHash` from `log.topics[2]`:+```js+const delegationHash = log.topics[2];+```+For `DisabledDelegation`, `delegationHash` is `topics[1]` (first indexed param), not `topics[2]`. This decoding is also wrong and must be fixed alongside the topic hashes.++## Fix++In `api/cron/[name].js` lines 319–320, replace with the correct canonical signatures:++```js+// Derive topic hashes from the ABI to stay in sync with contract changes.+import { Interface } from 'ethers';+import { DELEGATION_MANAGER_ABI } from '../../src/erc7710/abi.js';++const _iface = new Interface(DELEGATION_MANAGER_ABI);+const DISABLED_TOPIC = _iface.getEvent('DisabledDelegation').topicHash;+const REDEEMED_TOPIC = _iface.getEvent('RedeemedDelegation').topicHash;+```++This derives the topic hashes from the same ABI used everywhere else, ensuring they stay in sync if the ABI changes.++Then fix the log decoding at line 476. For `DisabledDelegation(bytes32 indexed delegationHash, ...)`, `delegationHash` is `topics[1]`:++```js+// Before (wrong):+const delegationHash = log.topics[2];++// After (correct):+// DisabledDelegation: topics[1] = delegationHash, topics[2] = delegator, topics[3] = delegate+// RedeemedDelegation: topics[1] = rootDelegator, topics[2] = redeemer+const delegationHash =+ log.topics[0] === DISABLED_TOPIC+ ? log.topics[1] // DisabledDelegation: first indexed param+ : log.topics[2]; // RedeemedDelegation: second indexed param (redeemer's hash — check actual event)+```++Verify the `RedeemedDelegation` event's indexed param order against the ABI before finalizing.diff --git a/vercel-fix-prompts/03-missing-rpc-urls-permissions-handler.md b/vercel-fix-prompts/03-missing-rpc-urls-permissions-handler.mdnew file mode 100644index 000000000..2f3725f4f--- /dev/null+++ b/vercel-fix-prompts/03-missing-rpc-urls-permissions-handler.md@@ -0,0 +1,60 @@+# Fix: Missing RPC URLs for Chains 8453 / 421614 / 11155420 in Permissions Handler++## Confirmed Bug++`api/permissions/[action].js` line 635–642 defines `getRpcUrl()`:++```js+function getRpcUrl(chainId) {+ return (+ process.env[`RPC_URL_${chainId}`] ||+ (chainId === 84532 ? process.env.BASE_SEPOLIA_RPC_URL : null) ||+ (chainId === 11155111 ? process.env.SEPOLIA_RPC_URL : null) ||+ null+ );+}+```++This function has hardcoded fallbacks only for chains `84532` and `11155111`. It returns `null` for any other chain.++`src/erc7710/abi.js` lines 17–25 shows `DELEGATION_MANAGER_DEPLOYMENTS` includes:+- `8453` — Base mainnet+- `1` — Ethereum mainnet+- `84532` — Base Sepolia ✓ (has fallback)+- `11155111` — Ethereum Sepolia ✓ (has fallback)+- `421614` — Arbitrum Sepolia ✗ (no fallback)+- `11155420` — Optimism Sepolia ✗ (no fallback)++When `handleRedeem` or `handleVerify` is called for chains `8453`, `1`, `421614`, or `11155420`, `getRpcUrl` returns `null`, and line 828 throws:+```+throw new Error(`no RPC URL configured for chain ${chainId} (set RPC_URL_${chainId})`)+```++Note: The `index-delegations` cron (`idxRpcUrls`) already has public fallbacks for all these chains — this is isolated to the permissions handler.++## Fix++Replace `getRpcUrl` in `api/permissions/[action].js` line 635–642 with fallbacks for all deployed chains, matching the pattern used in `api/cron/[name].js` lines 333–368:++```js+const PERMISSIONS_PUBLIC_RPCS = {+ 1: 'https://cloudflare-eth.com',+ 8453: 'https://mainnet.base.org',+ 84532: 'https://sepolia.base.org',+ 11155111: 'https://rpc.sepolia.org',+ 421614: 'https://sepolia-rollup.arbitrum.io/rpc',+ 11155420: 'https://sepolia.optimism.io',+};++function getRpcUrl(chainId) {+ return (+ process.env[`RPC_URL_${chainId}`] ||+ (chainId === 84532 ? process.env.BASE_SEPOLIA_RPC_URL : null) ||+ (chainId === 11155111 ? process.env.SEPOLIA_RPC_URL : null) ||+ PERMISSIONS_PUBLIC_RPCS[chainId] ||+ null+ );+}+```++Also add `RPC_URL_8453`, `RPC_URL_421614`, `RPC_URL_11155420` to `.env.example` under the existing RPC section (after line 98) with Alchemy/Infura endpoints so production deployments use paid providers instead of public ones.diff --git a/vercel-fix-prompts/04-erc8004-crawl-timeout.md b/vercel-fix-prompts/04-erc8004-crawl-timeout.mdnew file mode 100644index 000000000..e5184be1f--- /dev/null+++ b/vercel-fix-prompts/04-erc8004-crawl-timeout.md@@ -0,0 +1,52 @@+# Fix: erc8004-crawl Cron Timeout (Exceeds Vercel 300s Limit)++## Confirmed Issue++`api/cron/[name].js` line 87:+```js+const ERC8004_DEFAULT_LOOKBACK = parseInt(process.env.ERC8004_CRAWL_LOOKBACK || '50000', 10);+```++On first run (no cursor in `erc8004_crawl_cursor`), `erc8004CrawlChain` computes:+```js+// line 132–136 (paraphrased):+const fromBlock = cursor ? cursor.last_block : latestBlock - ERC8004_DEFAULT_LOOKBACK;+```++With `ERC8004_DEFAULT_LOOKBACK = 50_000` and `ERC8004_BLOCK_CHUNK = 2_000`, the crawl loop makes **25 sequential RPC calls per chain** just for the initial catchup. With multiple chains in `CHAINS` and then 25 metadata fetches (`erc8004EnrichMetadata`), total execution easily exceeds Vercel's hard 300-second limit.++Logs confirm: `Vercel Runtime Timeout Error: Task timed out after 300 seconds` on `/api/cron/erc8004-crawl`.++## Fix++**Option A — Reduce default lookback (immediate fix):**++Lower `ERC8004_DEFAULT_LOOKBACK` to a safe value that completes in <60 seconds on first run. Based on 2,000 blocks/call at ~500ms each and multiple chains, a safe default is `2000` (one chunk per chain on first run):++In `api/cron/[name].js` line 87:+```js+// Before:+const ERC8004_DEFAULT_LOOKBACK = parseInt(process.env.ERC8004_CRAWL_LOOKBACK || '50000', 10);++// After:+const ERC8004_DEFAULT_LOOKBACK = parseInt(process.env.ERC8004_CRAWL_LOOKBACK || '2000', 10);+```++Set `ERC8004_CRAWL_LOOKBACK=50000` in the Vercel environment only when doing a one-time manual backfill (trigger the endpoint manually, not via cron).++**Option B — Per-invocation block budget:**++Add a time budget so the cron stops processing and returns before Vercel's limit:+```js+const CRAWL_BUDGET_MS = 240_000; // 240s — leaves 60s margin+const crawlStart = Date.now();++while (fromBlock <= latestBlock) {+ if (Date.now() - crawlStart > CRAWL_BUDGET_MS) break; // resume next invocation+ // ...existing loop body...+}+```++**Recommended:** Apply both — Option A as the default, Option B as a safety net.++Also add `ERC8004_CRAWL_LOOKBACK` to `.env.example` with a comment explaining the backfill use case.diff --git a/vercel-fix-prompts/05-missing-env-vars-vercel-dashboard.md b/vercel-fix-prompts/05-missing-env-vars-vercel-dashboard.mdnew file mode 100644index 000000000..dcc1401ad--- /dev/null+++ b/vercel-fix-prompts/05-missing-env-vars-vercel-dashboard.md@@ -0,0 +1,64 @@+# Fix: Missing / Unset Environment Variables in Vercel Dashboard++## Confirmed Issue++Vercel logs show 500 errors from `api/_lib/env.js`'s `req()` helper throwing `Missing required env var: JWT_SECRET`. This means `JWT_SECRET` is not set in Vercel's production environment variables.++`JWT_SECRET` is used in:+- `api/_lib/auth.js` — JWT signing and CSRF token HMAC+- `api/_lib/agent-wallet.js` — AES-256-GCM wallet encryption key derivation+- `api/agents/_id/persona.js` — HMAC signing+- `api/auth/github/[action].js` and `api/auth/x/[action].js` — HKDF/AES token encryption++Any endpoint that touches auth or agent wallets fails if this is missing.++## What to set++Go to **Vercel Dashboard → Project → Settings → Environment Variables** and verify/add each of the following. Cross-reference with `.env.example` for the full required list.++### Critical — `req()` in `api/_lib/env.js` (throws 500 on first access if unset):++| Variable | Description | Where used |+|---|---|---|+| `JWT_SECRET` | Long random secret (32+ bytes, base64 or hex) — `openssl rand -base64 64` | Auth, agent wallet encryption, HMAC |+| `DATABASE_URL` | Neon Postgres connection string (`postgres://...`) | All DB queries via `api/_lib/db.js` |+| `S3_ENDPOINT` | S3-compatible endpoint (e.g. Cloudflare R2: `https://<account>.r2.cloudflarestorage.com`) | Avatar/file storage |+| `S3_ACCESS_KEY_ID` | S3 access key ID | Avatar/file storage |+| `S3_SECRET_ACCESS_KEY` | S3 secret access key | Avatar/file storage |+| `S3_BUCKET` | Bucket name (e.g. `3d-agent-avatars`) | Avatar/file storage |+| `S3_PUBLIC_DOMAIN` | Public CDN URL for the bucket (no trailing slash) | Avatar URL construction |+| `ANTHROPIC_API_KEY` | Anthropic API key (`sk-ant-...`) | Chat/LLM proxy endpoints |+| `AGENT_RELAYER_KEY` | Hex private key of the relayer EOA (`0x...`) | ERC-7710 delegation redeem |+| `VOYAGE_API_KEY` | VoyageAI API key | Agent text embedding endpoints |++### High (features broken if missing, but no hard throws):++| Variable | Description |+|---|---|+| `JWT_KID` | Key ID string for JWT `kid` header — defaults to `"k1"` if unset |+| `CRON_SECRET` | Shared secret for Vercel Cron `Authorization: Bearer` header — crons run unauthenticated if unset |+| `UPSTASH_REDIS_REST_URL` + `UPSTASH_REDIS_REST_TOKEN` | Rate limiting — all endpoints fail open (no rate limiting) if unset |+| `SOLANA_RPC_URL` | Solana RPC — defaults to public mainnet endpoint if unset |+| `RPC_URL_84532` | Base Sepolia RPC — falls back to public `sepolia.base.org` if unset |++## Variable name note++The codebase uses **S3-compatible naming** (`S3_ENDPOINT`, `S3_ACCESS_KEY_ID`, etc.), not R2-specific names. If you're using Cloudflare R2, the bucket credentials go into the `S3_*` variables — R2 exposes an S3-compatible API. Do not set `R2_ACCOUNT_ID` or similar; those are not read by the code.++## How to verify++After setting, redeploy, then check Vercel Function logs. Confirm `Missing required env var` errors are gone.++Run locally to check all required vars before deploying:+```bash+node -e "+const required = [+ 'JWT_SECRET','DATABASE_URL',+ 'S3_ENDPOINT','S3_ACCESS_KEY_ID','S3_SECRET_ACCESS_KEY','S3_BUCKET','S3_PUBLIC_DOMAIN',+ 'ANTHROPIC_API_KEY','AGENT_RELAYER_KEY','VOYAGE_API_KEY',+];+let ok = true;+required.forEach(k => { if (!process.env[k]) { console.error('MISSING:', k); ok = false; } });+if (ok) console.log('All required env vars present.');+"+```diff --git a/vercel-fix-prompts/06-index-delegations-env-var-name-mismatch.md b/vercel-fix-prompts/06-index-delegations-env-var-name-mismatch.mdnew file mode 100644index 000000000..9c32ac374--- /dev/null+++ b/vercel-fix-prompts/06-index-delegations-env-var-name-mismatch.md@@ -0,0 +1,49 @@+# Fix: index-delegations Cron Uses RPC_<chainId> but Docs Say RPC_URL_<chainId>++## Confirmed Issue++Two different patterns exist for RPC URL env vars in this codebase:++**`api/cron/[name].js` line 372** (index-delegations):+```js+const envUrl = process.env[`RPC_${chainId}`];+```++**`api/permissions/[action].js` line 637** (permissions handler):+```js+process.env[`RPC_URL_${chainId}`]+```++**`.env.example` line 96–98** documents the pattern as `RPC_URL_<CHAINID>`:+```+# Pattern: RPC_URL_<CHAINID>. Override the default public RPCs with Alchemy/Infura for production.+RPC_URL_84532=https://sepolia.base.org+RPC_URL_11155111=https://rpc.sepolia.org+```++The cron uses `RPC_${chainId}` (no `_URL_`). If an operator sets `RPC_URL_8453=https://...` in Vercel (following `.env.example`), the cron will ignore it and fall back to public RPCs. The variable name mismatch means production RPC overrides have no effect on the indexer.++## Fix++Standardize on `RPC_URL_${chainId}` everywhere. In `api/cron/[name].js` line 372:++```js+// Before:+const envUrl = process.env[`RPC_${chainId}`];++// After:+const envUrl = process.env[`RPC_URL_${chainId}`];+```++Then update `.env.example` to document all chains that have DelegationManager deployments (from `src/erc7710/abi.js`):++```+RPC_URL_1= # Ethereum mainnet — use Alchemy/Infura, public RPCs rate-limit heavily+RPC_URL_8453= # Base mainnet+RPC_URL_84532=https://sepolia.base.org+RPC_URL_11155111=https://rpc.sepolia.org+RPC_URL_421614= # Arbitrum Sepolia+RPC_URL_11155420= # Optimism Sepolia+```++Set the production values in Vercel env vars, especially `RPC_URL_1` (Ethereum mainnet hits 1rpc.io's rate limits in logs).diff --git a/vercel-fix-prompts/07-rpc-rate-limiting-paid-providers.md b/vercel-fix-prompts/07-rpc-rate-limiting-paid-providers.mdnew file mode 100644index 000000000..be18806f3--- /dev/null+++ b/vercel-fix-prompts/07-rpc-rate-limiting-paid-providers.md@@ -0,0 +1,42 @@+# Fix: RPC Rate Limiting — Switch to Paid Providers for Production++## Confirmed Issue++Vercel logs show 429 errors from public RPC providers:+```+{"stage":"index-delegations","chainId":1,"error":"RPC HTTP 429 from https://1rpc.io/eth"}+[agents/solana/activity] RPC fetch failed Error: 429 Too Many Requests+```++`api/cron/[name].js` lines 333–368 list public RPC fallbacks for all chains including Ethereum mainnet (chain 1). Public endpoints like `1rpc.io`, `cloudflare-eth.com`, `llamarpc.com` have low rate limits and are unsuitable for production cron jobs that run every few minutes.++`api/agents/_id/_sub.js` (Solana activity) also uses public Solana RPC endpoints that rate-limit.++## Fix++### Ethereum / EVM chains++Set paid RPC endpoints in Vercel environment variables. Use Alchemy (recommended), Infura, or QuickNode:++```+RPC_URL_1=https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY # Ethereum mainnet+RPC_URL_8453=https://base-mainnet.g.alchemy.com/v2/YOUR_KEY # Base mainnet+RPC_URL_84532=https://base-sepolia.g.alchemy.com/v2/YOUR_KEY # Base Sepolia+RPC_URL_421614=https://arb-sepolia.g.alchemy.com/v2/YOUR_KEY # Arbitrum Sepolia+RPC_URL_11155420=https://opt-sepolia.g.alchemy.com/v2/YOUR_KEY+```++The env var is read first in `idxRpcUrls()` (`api/cron/[name].js` line 372 — note: after prompt 06 is applied, this uses `RPC_URL_${chainId}`). Public RPCs remain as automatic fallbacks.++### Solana++Set in Vercel:+```+SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?api-key=YOUR_KEY+```++Helius and QuickNode both offer free tiers with much higher limits than the public Solana endpoint.++### For the cron specifically++`api/cron/[name].js`'s `idxRpc()` already tries multiple URLs in order and retries on 429. After setting paid providers as the first URL, the public fallbacks only activate when the paid provider is down — which is the correct behavior.diff --git a/vercel-fix-prompts/08-indexer-state-table-missing.md b/vercel-fix-prompts/08-indexer-state-table-missing.mdnew file mode 100644index 000000000..94b632a96--- /dev/null+++ b/vercel-fix-prompts/08-indexer-state-table-missing.md@@ -0,0 +1,38 @@+# Fix: indexer_state Table Missing from Schema (and Production DB)++## Confirmed Issue++`api/cron/[name].js` line 440–443 queries:+```js+const [cursor] = await sql`+ SELECT last_indexed_block FROM indexer_state+ WHERE contract = ${contract.toLowerCase()} AND chain_id = ${chainId}+`;+```++Confirmed: `indexer_state` does **not exist** anywhere in `api/_lib/schema.sql` or any other `.sql` file in the repo. The table was never defined.++Every `index-delegations` cron invocation throws a NeonDbError on this query for all 6 chains (1, 8453, 84532, 11155111, 421614, 11155420), which explains the flood of `index-delegations` errors in Vercel logs.++Note: `agent_delegations` IS in `schema.sql` (line 500) and is fine.++## Fix++**Step 1** — Add to `api/_lib/schema.sql` after the `agent_delegations` block (around line 529):++```sql+-- ── indexer_state — block cursor for the index-delegations cron ──────────────+create table if not exists indexer_state (+ contract text not null,+ chain_id int not null,+ last_indexed_block bigint not null default 0,+ updated_at timestamptz not null default now(),+ primary key (contract, chain_id)+);+```++**Step 2** — Run this SQL against the production Neon database.++**Step 3** — Also check `api/cron/[name].js` for the INSERT/UPDATE that writes back to `indexer_state` after processing, and confirm the column names match (`last_indexed_block`). Look for the line that persists the cursor after `while (fromBlock <= latestBlock)` completes.++**Step 4** — After applying, trigger the cron manually and check Vercel logs — `index-delegations` errors should stop. Note that the separate prompt for wrong topic hashes (prompt 02) must also be fixed for the indexer to actually record delegation events correctly.diff --git a/vercel-fix-prompts/09-unapplied-db-migrations.md b/vercel-fix-prompts/09-unapplied-db-migrations.mdnew file mode 100644index 000000000..a8c5fc8b5--- /dev/null+++ b/vercel-fix-prompts/09-unapplied-db-migrations.md@@ -0,0 +1,76 @@+# Fix: 18 Database Migrations Never Applied to Production++## Confirmed Issue++There are 18 migration files in `api/_lib/migrations/` dated 2026-04-29 and 2026-04-30 that introduce tables and columns the codebase depends on. These migrations are NOT in `api/_lib/schema.sql` — they are additive files meant to be applied separately.++The Vercel logs show 500 errors on endpoints that use tables from these migrations (e.g., `pumpfun_signals`, missing columns). The migrations are idempotent (`create table if not exists`, `alter table ... add column if not exists`) so they are safe to run against production.++## Migration files to apply (in order)++```+api/_lib/migrations/2026-04-29-agent-marketplace.sql+api/_lib/migrations/2026-04-29-agent-payments.sql+api/_lib/migrations/2026-04-29-attest-event-bridge.sql+api/_lib/migrations/2026-04-29-chat-brand-config.sql+api/_lib/migrations/2026-04-29-drop-pump-relay.sql+api/_lib/migrations/2026-04-29-onchain-unified.sql+api/_lib/migrations/2026-04-29-pump-agent-stats.sql+api/_lib/migrations/2026-04-29-pump-price-points.sql+api/_lib/migrations/2026-04-29-pump-relay-delegations.sql+api/_lib/migrations/2026-04-29-pump-trades.sql+api/_lib/migrations/2026-04-29-pumpfun-monitor-cursor.sql+api/_lib/migrations/2026-04-29-token-launches.sql+api/_lib/migrations/2026-04-30-agent-monetization.sql+api/_lib/migrations/2026-04-30-chat-admin-key.sql+api/_lib/migrations/2026-04-30-notifications.sql+api/_lib/migrations/2026-04-30-pump-fun.sql+api/_lib/migrations/2026-04-30-skills-marketplace.sql+api/_lib/migrations/2026-04-30-skills-seed.sql+```++## How to apply++Run each file against the production Neon database. Each file's header shows the apply command:++```bash+# Apply all migrations in order:+for f in api/_lib/migrations/2026-04-29-*.sql api/_lib/migrations/2026-04-30-*.sql; do+ echo "Applying $f..."+ psql "$DATABASE_URL" -f "$f"+done+```++Or apply individually:+```bash+psql "$DATABASE_URL" -f api/_lib/migrations/2026-04-29-agent-marketplace.sql+psql "$DATABASE_URL" -f api/_lib/migrations/2026-04-29-agent-payments.sql+# ... etc+```++## What each migration adds (key tables/columns)++| File | Adds |+|---|---|+| agent-marketplace | marketplace columns on `agent_identities` |+| agent-payments | `payment_configs_pending`, `agent_payment_intents` |+| attest-event-bridge | pumpkit attestation bridge state tables |+| chat-brand-config | brand config table for chat widget |+| drop-pump-relay | drops unused old relay tables |+| onchain-unified | unified on-chain deploy metadata columns |+| pump-agent-stats | per-agent pump.fun live stats table |+| pump-price-points | price point time series table |+| pump-relay-delegations | hot-wallet relayer delegation table |+| pump-trades | pump.fun trade audit table |+| pumpfun-monitor-cursor | `pumpfun_signals` and monitor cursor |+| token-launches | `token_launches_pending` table |+| agent-monetization | `agent_skill_prices`, `agent_revenue_events`, `agent_payout_wallets`, `agent_withdrawals` |+| chat-admin-key | admin key storage table |+| notifications | user notifications table |+| pump-fun | pump.fun integration tables including `pumpfun_signals` |+| skills-marketplace | skills marketplace tables |+| skills-seed | seeds 15 system skills into `marketplace_skills` |++## After applying++Redeploy is not required for DB-only changes. Endpoint errors related to missing tables should resolve immediately after migration.diff --git a/vercel-fix-prompts/10-audit-log-for-avatar-deletion.md b/vercel-fix-prompts/10-audit-log-for-avatar-deletion.mdnew file mode 100644index 000000000..42dd7375e--- /dev/null+++ b/vercel-fix-prompts/10-audit-log-for-avatar-deletion.md@@ -0,0 +1,55 @@+# Fix: Missing Audit Log for MCP Avatar Deletion++## Confirmed Issue++`api/_mcp/tools/avatars.js` line 239:+```js+const result = await deleteAvatar({ id: args.id, userId: auth.userId });+if (!result) throw new Error('avatar not found or not yours');+// TODO: audit_log table needed — INSERT (user_id, action='delete_avatar', resource_id, created_at)+return { content: [{ type: 'text', text: `Deleted avatar ${args.id}.` }] };+```++Avatar deletions triggered through the MCP `delete_avatar` tool are not logged. If a user's avatar is deleted through an MCP client, there is no record of who deleted it or when.++## Fix++**Step 1** — Create an `audit_log` table migration. Add a new file `api/_lib/migrations/2026-05-01-audit-log.sql`:++```sql+-- Migration: audit log for sensitive operations.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-01-audit-log.sql+-- Idempotent.++create table if not exists audit_log (+ id uuid primary key default gen_random_uuid(),+ user_id uuid references users(id) on delete set null,+ action text not null,+ resource_id text,+ meta jsonb,+ created_at timestamptz not null default now()+);++create index if not exists audit_log_user_idx on audit_log(user_id, created_at desc);+create index if not exists audit_log_action_idx on audit_log(action, created_at desc);+```++Apply against production: `psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-01-audit-log.sql`++**Step 2** — Replace the TODO comment in `api/_mcp/tools/avatars.js` line 239 with the actual INSERT, using `queueMicrotask` so it doesn't block the response:++```js+const result = await deleteAvatar({ id: args.id, userId: auth.userId });+if (!result) throw new Error('avatar not found or not yours');+queueMicrotask(async () => {+ try {+ await sql`+ INSERT INTO audit_log (user_id, action, resource_id)+ VALUES (${auth.userId}, 'delete_avatar', ${args.id})+ `;+ } catch { /* non-fatal */ }+});+return { content: [{ type: 'text', text: `Deleted avatar ${args.id}.` }] };+```++Follow the same fire-and-forget pattern used in `api/avatars/index.js` line 115.diff --git a/vercel-fix-prompts/README.md b/vercel-fix-prompts/README.mdnew file mode 100644index 000000000..b9da76931--- /dev/null+++ b/vercel-fix-prompts/README.md@@ -0,0 +1,72 @@+# Vercel Fix Prompts++Generated 2026-05-01 from log export + full codebase audit.+Each file is a self-contained prompt — open it in a new chat and run it.++**Run in order.** Later prompts may depend on earlier ones (e.g. migrations before testing endpoints).++---++## Priority 1 — Run First (Blockers)++### [01 — Missing parent_avatar_id Column](01-missing-parent-avatar-id-migration.md)+`avatars` table is missing `parent_avatar_id uuid` — confirmed absent from `schema.sql`. Every `POST /api/avatars` with a parent reference and every avatar list query crashes with NeonDbError.+**Fix:** `alter table avatars add column if not exists parent_avatar_id uuid references avatars(id) on delete set null;` — add to `schema.sql` and run on production.++### [02 — Wrong Event Topic Hashes in index-delegations Cron](02-wrong-event-topic-hashes-index-delegations.md)+`api/cron/[name].js` lines 319–320 compute keccak hashes for `DelegationDisabled(address,bytes32)` and `DelegationRedeemed(address,bytes32)` — both name and signature are wrong. Actual events in ABI are `DisabledDelegation(bytes32,address,address,...)` and `RedeemedDelegation(address,address,...)`. The indexer silently processes 0 events on every run.+**Fix:** Derive topics from the ABI using `new Interface(DELEGATION_MANAGER_ABI).getEvent('DisabledDelegation').topicHash`. Fix log decoding at line 476 too.++### [08 — indexer_state Table Missing from Schema](08-indexer-state-table-missing.md)+`api/cron/[name].js` queries `indexer_state` (lines 441–443) but this table is **not in `schema.sql` or any migration file**. The `index-delegations` cron throws NeonDbError on every chain, every invocation.+**Fix:** Create the table (DDL in prompt) and run against production.++### [09 — 18 Unapplied Database Migrations](09-unapplied-db-migrations.md)+18 migration files in `api/_lib/migrations/` (dated 2026-04-29 and 2026-04-30) have never been applied to production. These add tables for pumpfun, agent payments, monetization, notifications, marketplace, and more. Most 500 errors on feature endpoints trace back to these missing tables.+**Fix:** `psql "$DATABASE_URL" -f <each file>` in date order.++### [05 — Missing/Unset Vercel Environment Variables](05-missing-env-vars-vercel-dashboard.md)+`JWT_SECRET` and likely other required env vars are not set in Vercel dashboard. Causes 500 on all auth and agent wallet endpoints.+**Fix:** Set in Vercel → Settings → Environment Variables. See prompt for full list.++---++## Priority 2 — High Impact++### [03 — Missing RPC URLs for Chains 8453 / 421614 / 11155420 in Permissions Handler](03-missing-rpc-urls-permissions-handler.md)+`getRpcUrl()` in `api/permissions/[action].js` (line 635) has no fallbacks for Base mainnet (8453), Arbitrum Sepolia (421614), or Optimism Sepolia (11155420) — but all three are in `DELEGATION_MANAGER_DEPLOYMENTS`. `handleRedeem` and `handleVerify` throw "no RPC URL configured" for these chains.+**Fix:** Add public fallback RPCs to `getRpcUrl()` for all 6 deployed chains.++### [06 — index-delegations Env Var Name Mismatch](06-index-delegations-env-var-name-mismatch.md)+Cron reads `process.env[`RPC_${chainId}`]` (line 372) but `.env.example` and the permissions handler use `RPC_URL_${chainId}`. Operator-set production RPC URLs are silently ignored by the indexer.+**Fix:** Change cron line 372 to `RPC_URL_${chainId}`. Update `.env.example` with all chains.++### [07 — RPC Rate Limiting: Switch to Paid Providers](07-rpc-rate-limiting-paid-providers.md)+Logs show 429s from `1rpc.io` (Ethereum mainnet) and public Solana RPC. Public endpoints are unsuitable for production cron jobs.+**Fix:** Set `RPC_URL_1`, `RPC_URL_8453`, `SOLANA_RPC_URL` etc. in Vercel with Alchemy/Helius keys.++### [04 — erc8004-crawl Cron Timeout](04-erc8004-crawl-timeout.md)+`ERC8004_DEFAULT_LOOKBACK = 50_000` on first run causes 25+ sequential RPC calls per chain, reliably exceeding Vercel's 300s limit.+**Fix:** Lower default lookback to `2000`. Add a time-budget guard in the while loop.++---++## Priority 3 — Low / Cleanup++### [10 — Audit Log for MCP Avatar Deletion](10-audit-log-for-avatar-deletion.md)+`api/_mcp/tools/avatars.js` line 239 has a TODO for audit logging avatar deletions. Not a blocker but creates accountability gap for destructive MCP operations.+**Fix:** Create `audit_log` table, fire-and-forget INSERT after successful delete.++---++## What was checked and confirmed NOT broken++These were flagged by log analysis but are correctly implemented in the current code:++- **@zauthx402/sdk** — in `dependencies`, included in `vercel.json` `includeFiles` ✓+- **api/agents/_sub.js** — exists at `api/agents/_id/_sub.js`, imported correctly ✓+- **UUID validation** — `_sub.js` line 137 has regex check before SQL ✓+- **SIWE duplicate email** — handler uses `ON CONFLICT (email) DO UPDATE` ✓+- **permissions topicHash null** — line 912–913 has a proper guard with a descriptive throw ✓+- **@noble/curves** — `^2.2.0` in dependencies, import uses `.js` extension ✓+- **dca_strategies / agent_subscriptions / solana_attestations_cursor** — all in `schema.sql` ✓ (but may need migrations from prompt 09 to be fully functional)