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(payments): EVM payment verification for purchases
nirholas1c415c5788a5
diff --git a/api/_lib/evm-payment-verify.js b/api/_lib/evm-payment-verify.jsnew file mode 100644index 000000000..8aaf88b5d--- /dev/null+++ b/api/_lib/evm-payment-verify.js@@ -0,0 +1,129 @@+// EVM USDC payment verification.+//+// The Solana confirm path scans for a transaction by Solana-Pay reference. EVM+// has no equivalent, so the buyer submits the settlement tx hash and we verify+// it on-chain: the tx must be mined and successful, have enough confirmations,+// and contain a USDC ERC-20 Transfer to the seller's payout address for at least+// the expected amount. This mirrors the strictness of `validateTransfer` on the+// Solana side. Coin-agnostic settlement plumbing: USDC is the settlement asset.++import { createPublicClient, http, getAddress, decodeEventLog, parseAbiItem } from 'viem';+import { base, baseSepolia } from 'viem/chains';+import { env } from './env.js';+import { EVM_USDC } from '../payments/_config.js';++// Map our stored `chain` string to an EVM chain id. Only Base is wired today;+// extend here (and EVM_USDC) to add another settlement network.+const CHAIN_IDS = {+ base: 8453,+ 'base-mainnet': 8453,+ 'base-sepolia': 84532,+ base_sepolia: 84532,+};++const TRANSFER_EVENT = parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)');+const TRANSFER_ABI = [TRANSFER_EVENT];++// Confirmations required before a payment is final enough to grant access. Base+// has ~2s blocks and fast finality; 2 confirmations is a safe default and is+// overridable via env for stricter merchants.+const MIN_CONFIRMATIONS = (() => {+ const v = parseInt(process.env.EVM_MIN_CONFIRMATIONS || '2', 10);+ return Number.isFinite(v) && v >= 1 ? v : 2;+})();++export function evmChainId(chain) {+ return CHAIN_IDS[String(chain || '').toLowerCase()] ?? null;+}++const _clients = new Map();+function clientFor(chainId) {+ if (_clients.has(chainId)) return _clients.get(chainId);+ const chain = chainId === 84532 ? baseSepolia : base;+ const rpcUrl = env.BASE_RPC_URL || (chainId === 84532 ? 'https://sepolia.base.org' : 'https://mainnet.base.org');+ const client = createPublicClient({ chain, transport: http(rpcUrl) });+ _clients.set(chainId, client);+ return client;+}++const TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;++/**+ * Verify a USDC settlement on an EVM chain.+ *+ * @param {object} opts+ * @param {string} opts.txHash 0x-prefixed 32-byte tx hash from the buyer+ * @param {string} opts.chain stored chain string (e.g. 'base')+ * @param {string} opts.recipient seller payout address (0x…)+ * @param {string|bigint} opts.expectedAmount USDC atomics (6 decimals) required+ * @returns {Promise<{ status:'pending'|'match'|'mismatch', txHash?:string,+ * actualAmount?:string, from?:string, message?:string }>}+ */+export async function verifyEvmUsdcPayment({ txHash, chain, recipient, expectedAmount }) {+ if (!txHash || !TX_HASH_RE.test(txHash)) {+ return { status: 'mismatch', message: 'a valid 0x transaction hash is required' };+ }+ const chainId = evmChainId(chain);+ if (!chainId) return { status: 'mismatch', message: `unsupported EVM chain '${chain}'` };+ const usdc = EVM_USDC[chainId];+ if (!usdc) return { status: 'mismatch', message: `no USDC contract known for chain ${chainId}` };++ let to;+ try {+ to = getAddress(recipient);+ } catch {+ return { status: 'mismatch', message: 'seller payout address is not a valid EVM address' };+ }++ const client = clientFor(chainId);++ let receipt;+ try {+ receipt = await client.getTransactionReceipt({ hash: txHash });+ } catch {+ // Not mined yet (or RPC blip) — the buyer can retry confirm.+ return { status: 'pending', txHash };+ }+ if (!receipt) return { status: 'pending', txHash };+ if (receipt.status !== 'success') return { status: 'mismatch', txHash, message: 'transaction reverted on-chain' };++ // Require enough confirmations so a reorg can't strip a granted payment.+ try {+ const head = await client.getBlockNumber();+ if (head - receipt.blockNumber + 1n < BigInt(MIN_CONFIRMATIONS)) {+ return { status: 'pending', txHash };+ }+ } catch {+ return { status: 'pending', txHash };+ }++ // Sum every USDC Transfer in this tx whose `to` is the seller's wallet.+ const usdcAddr = getAddress(usdc);+ let total = 0n;+ let from = null;+ for (const log of receipt.logs) {+ let logAddr;+ try { logAddr = getAddress(log.address); } catch { continue; }+ if (logAddr !== usdcAddr) continue;+ let decoded;+ try {+ decoded = decodeEventLog({ abi: TRANSFER_ABI, data: log.data, topics: log.topics });+ } catch {+ continue; // not a Transfer event+ }+ if (decoded.eventName !== 'Transfer') continue;+ if (getAddress(decoded.args.to) !== to) continue;+ total += decoded.args.value;+ from = from || decoded.args.from;+ }++ if (total === 0n) {+ return { status: 'mismatch', txHash, message: 'no USDC transfer to the seller wallet found in this transaction' };+ }+ const expected = BigInt(expectedAmount);+ if (total < expected) {+ return { status: 'mismatch', txHash, actualAmount: total.toString(), from, message: 'USDC amount transferred is less than the price' };+ }++ return { status: 'match', txHash, actualAmount: total.toString(), from };+}diff --git a/api/_lib/purchase-confirm.js b/api/_lib/purchase-confirm.jsindex 0f8fbccfb..0545a9549 100644--- a/api/_lib/purchase-confirm.js+++ b/api/_lib/purchase-confirm.js@@ -23,6 +23,7 @@ import BigNumber from 'bignumber.js';import { sql } from './db.js';import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';import { insertNotification } from './notify.js';+import { verifyEvmUsdcPayment, evmChainId } from './evm-payment-verify.js';let _rpc;function rpc() {@@ -154,20 +155,24 @@ async function findReferencedTransferAmount(txSignature, recipient, splTokenMint* @returns {Promise<{ status: 'pending' | 'confirmed' | 'tipped' | 'mismatch' | 'expired',* tx_signature?: string, tipped_amount?: string, message?: string }>}*/-export async function confirmSkillPurchase(pur) {+export async function confirmSkillPurchase(pur, opts = {}) {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())) {return { status: 'expired' };}- if (pur.chain !== 'solana') {- throw new Error(`chain '${pur.chain}' not supported`);- }const payoutAddress = await resolvePayoutAddress(pur.agent_id, pur.chain);if (!payoutAddress) throw new Error('payout wallet not configured');+ if (pur.chain === 'solana') return confirmSolanaSkill(pur, payoutAddress);+ if (evmChainId(pur.chain)) return confirmEvmSkill(pur, payoutAddress, opts.txHash);+ throw new Error(`chain '${pur.chain}' not supported`);+}++// Solana path: locate the tx via Solana-Pay reference, then validateTransfer.+async function confirmSolanaSkill(pur, payoutAddress) {const refKey = new PublicKey(pur.reference);const recipient = new PublicKey(payoutAddress);const splToken = new PublicKey(pur.currency_mint);@@ -199,45 +204,87 @@ export async function confirmSkillPurchase(pur) {),);} catch (e) {- // 2a. Mismatch — but the transfer happened. Mark as tipped if we can pin down- // the actual amount that hit the seller's wallet.+ // Mismatch — but the transfer happened. Mark as tipped if we can pin down+ // the actual amount that hit the seller's wallet; else mark failed.const actual = await findReferencedTransferAmount(txSignature, recipient, splToken);- if (actual !== null) {- await sql`- UPDATE skill_purchases- SET status = 'tipped', tx_signature = ${txSignature},- tipped_amount = ${actual.toString()}, confirmed_at = now()- WHERE id = ${pur.id} AND status = 'pending'- `;- await emitReceipt(pur, txSignature, payoutAddress, 'tipped');- await logEvent(pur.id, 'tipped', { actual: actual.toString(), expected: pur.amount, reason: e.message });- // Notify seller — they got SOMETHING; let them know it was a mismatch- // so they can decide whether to grant access manually.- await getSellerUserId(pur.agent_id).then((sellerId) => {- if (!sellerId) return;- return insertNotification(sellerId, 'skill_payment_mismatch', {- agent_id: pur.agent_id,- skill: pur.skill,- expected_amount: String(pur.amount),- actual_amount: actual.toString(),- tx_signature: txSignature,- purchase_id: pur.id,- });- });- return { status: 'tipped', tx_signature: txSignature, tipped_amount: actual.toString(), message: e.message };+ if (actual !== null) return markSkillTipped(pur, txSignature, actual.toString(), e.message, payoutAddress);+ return markSkillMismatch(pur, txSignature, e.message);+ }++ return finalizeSkillConfirmation(pur, txSignature, payoutAddress);+}++// EVM path: the buyer submits the settlement tx hash; verify a USDC transfer of+// at least the price reached the seller's payout wallet on Base.+async function confirmEvmSkill(pur, payoutAddress, txHash) {+ if (!txHash) return { status: 'pending' }; // buyer hasn't broadcast / submitted yet++ // Idempotency: one settlement tx can confirm at most one purchase.+ const [dupe] = await sql`+ SELECT id FROM skill_purchases+ WHERE tx_signature = ${txHash} AND status IN ('confirmed', 'tipped') AND id != ${pur.id}+ LIMIT 1+ `;+ if (dupe) return { status: 'mismatch', message: 'this transaction has already been used for another purchase' };++ const result = await verifyEvmUsdcPayment({+ txHash,+ chain: pur.chain,+ recipient: payoutAddress,+ expectedAmount: pur.amount,+ });+ if (result.status === 'pending') return { status: 'pending' };+ if (result.status === 'mismatch') {+ // A short-but-real transfer is a tip; nothing on-chain at all is a mismatch.+ if (result.actualAmount && BigInt(result.actualAmount) > 0n) {+ return markSkillTipped(pur, txHash, result.actualAmount, result.message || 'amount mismatch', payoutAddress);}+ return markSkillMismatch(pur, txHash, result.message || 'no matching transfer');+ }+ return finalizeSkillConfirmation(pur, txHash, payoutAddress);+}- // 2b. No matching transfer at all — mark failed, no on-chain side effect.- await sql`- UPDATE skill_purchases- SET status = 'failed', tx_signature = ${txSignature}- WHERE id = ${pur.id} AND status = 'pending'- `;- await logEvent(pur.id, 'mismatch_no_transfer', { reason: e.message });- return { status: 'mismatch', message: e.message };+// Seller received some funds against this purchase, but not the exact expected+// amount — record it as 'tipped' so the money is acknowledged and the seller can+// grant access manually. Shared by both chains.+async function markSkillTipped(pur, txSignature, actualAmount, reason, payoutAddress) {+ await sql`+ UPDATE skill_purchases+ SET status = 'tipped', tx_signature = ${txSignature},+ tipped_amount = ${actualAmount}, confirmed_at = now()+ WHERE id = ${pur.id} AND status = 'pending'+ `;+ await emitReceipt(pur, txSignature, payoutAddress, 'tipped');+ await logEvent(pur.id, 'tipped', { actual: actualAmount, expected: pur.amount, reason });+ const sellerId = await getSellerUserId(pur.agent_id);+ if (sellerId) {+ await insertNotification(sellerId, 'skill_payment_mismatch', {+ agent_id: pur.agent_id,+ skill: pur.skill,+ expected_amount: String(pur.amount),+ actual_amount: actualAmount,+ tx_signature: txSignature,+ purchase_id: pur.id,+ });}+ return { status: 'tipped', tx_signature: txSignature, tipped_amount: actualAmount, message: reason };+}++// No matching transfer at all — mark failed, no on-chain side effect.+async function markSkillMismatch(pur, txSignature, reason) {+ await sql`+ UPDATE skill_purchases+ SET status = 'failed', tx_signature = ${txSignature}+ WHERE id = ${pur.id} AND status = 'pending'+ `;+ await logEvent(pur.id, 'mismatch_no_transfer', { reason });+ return { status: 'mismatch', message: reason };+}- // 3. Match. Atomic confirm + ledger writes.+// Atomic confirm + ledger writes. Identical for Solana and EVM once a valid+// payment is proven, so both chains converge here. `txSignature` is the Solana+// signature or the EVM tx hash.+async function finalizeSkillConfirmation(pur, txSignature, payoutAddress) {const intentId = `sp_${pur.id}`;const updated = await sql`UPDATE skill_purchases@@ -253,7 +300,7 @@ export async function confirmSkillPurchase(pur) {VALUES(${intentId}, ${pur.user_id}, ${pur.agent_id}, ${pur.currency_mint},${String(pur.amount)}, 'confirmed', now() + interval '30 days',- 'mainnet', ${txSignature}, now(),+ ${pur.chain === 'solana' ? 'mainnet' : pur.chain}, ${txSignature}, now(),${JSON.stringify({ kind: 'skill_purchase', skill: pur.skill, reference: pur.reference })}::jsonb)ON CONFLICT (id) DO NOTHING`;diff --git a/api/_mcp3d/catalog.js b/api/_mcp3d/catalog.jsindex 0974cd386..a2abd9fea 100644--- a/api/_mcp3d/catalog.js+++ b/api/_mcp3d/catalog.js@@ -3,6 +3,7 @@ import addFormats from 'ajv-formats';import { toolDefs as studioDefs } from './tools/studio.js';import { toolDefs as modelDefs } from '../_mcp/tools/models.js';+import { toolDefs as animationDefs } from '../_mcp/tools/animations.js';// Reuse the battle-tested inspect/optimize tools from the main MCP server so a// generated model can be analyzed in the same conversation — no duplicated@@ -10,7 +11,10 @@ import { toolDefs as modelDefs } from '../_mcp/tools/models.js';// covers "what is this mesh", and optimize covers "how do I ship it".const reusedModelDefs = modelDefs.filter((d) => d.name === 'inspect_model' || d.name === 'optimize_model');-const allDefs = [...studioDefs, ...reusedModelDefs];+// The animation library (list_animations + apply_animation) completes the+// pipeline: text_to_3d → auto_rig_model → apply_animation. Same retarget engine+// the main server exposes — reused here, not duplicated.+const allDefs = [...studioDefs, ...reusedModelDefs, ...animationDefs];// Schema objects for tools/list — strip internal fields (scope, handler).export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);diff --git a/api/_mcp3d/dispatch.js b/api/_mcp3d/dispatch.jsindex 007e23bec..128c6c630 100644--- a/api/_mcp3d/dispatch.js+++ b/api/_mcp3d/dispatch.js@@ -6,11 +6,14 @@ import { TOOL_CATALOG, TOOLS } from './catalog.js';export { PROTOCOL_VERSION };const INSTRUCTIONS = [- 'three.ws 3D Studio turns text or images into interactive 3D models.',- 'text_to_3d(prompt) and image_to_3d(image_url) start a generation job and return a job_id;',- 'poll generation_status(job_id) until it returns a GLB and an inline <model-viewer> artifact.',- 'preview_3d(glb_url) renders any GLB as an artifact; inspect_model / optimize_model analyze one.',- 'Always display returned text/html resources as inline 3D artifacts.',+ 'three.ws 3D Studio turns text or images into interactive, animation-ready 3D models.',+ 'Pipeline: optionally direct_prompt(idea) to sharpen a vague prompt, then text_to_3d(prompt) or',+ 'image_to_3d(image_url) to generate (tier=draft|standard|high, path=image|geometry); poll',+ 'generation_status(job_id) until it returns a GLB and an inline <model-viewer> artifact.',+ 'auto_rig_model(glb_url) adds a skeleton; apply_animation(model_url, animation) and pose_model(prompt)',+ 'drive the rigged result; list_animations enumerates clips. Mesh ops: remesh_model, stylize_model,',+ 'segment_model, retexture_model, retexture_region, generate_material. preview_3d(glb_url) renders any',+ 'GLB; inspect_model / optimize_model analyze one. Always display returned text/html resources as inline 3D artifacts.',].join(' ');export const dispatch = makeDispatcher({diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex 24bcf241d..890e5871d 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -15,6 +15,7 @@// direct_prompt (IBM Granite) rewrites a rough idea into an optimized 3D spec.// generate_material (IBM Granite) emits a glTF PBR material from a description.+import { createHash } from 'node:crypto';import { limits } from '../../_lib/rate-limit.js';import { assertSafePublicUrl } from '../../_lib/ssrf-guard.js';import { createRegenProvider as createReplicateProvider } from '../../_providers/replicate.js';@@ -237,6 +238,94 @@ async function submitGeometryJob({ req, args, backendId, isImageMode, prompt, pr};}+// Poll whichever upstream owns a job. A bare id (legacy / image-TRELLIS path)+// polls Replicate. A forge token (f1.*) decodes to the geometry provider+// (Meshy/Tripo, BYOK re-resolved per poll) or the self-hosted GCP backend.+async function pollAnyProvider(req, jobId) {+ const token = decodeJobToken(jobId);+ if (token) {+ if (token.provider === 'meshy' || token.provider === 'tripo') {+ const key = await resolveProviderKey(req, null, token.provider);+ if (!key) {+ return {+ status: 'failed',+ error:+ 'Your provider API key is required to check this job. Send it as the x-forge-provider-key header and retry.',+ };+ }+ const gp = token.provider === 'tripo' ? createTripoProvider(key) : createMeshyProvider(key);+ return gp.status({ kind: token.kind, taskId: token.taskId });+ }+ if (token.provider === 'gcp') {+ let gcp;+ try {+ gcp = createGcpProvider();+ } catch {+ return { status: 'failed', error: 'The self-hosted reconstruction backend is not configured.' };+ }+ return gcp.status(token.taskId);+ }+ return regenProvider().status(token.taskId);+ }+ return regenProvider().status(jobId);+}++// ── pose_model: deterministic preset selection (ported from the pose-seed tool) ─+function poseTokensOf(str) {+ return String(str || '').toLowerCase().split(/[^a-z0-9]+/g).filter(Boolean);+}+const POSE_INDEX = PRESETS.map((preset) => {+ const idTokens = poseTokensOf(preset.id);+ const labelTokens = poseTokensOf(preset.label);+ const groupTokens = poseTokensOf(preset.group);+ return { preset, all: new Set([...idTokens, ...labelTokens, ...groupTokens]), idTokens, labelTokens };+});+function scorePosePreset(promptTokens, entry) {+ let score = 0;+ for (const t of promptTokens) {+ if (entry.all.has(t)) score += 3;+ else {+ for (const tok of [...entry.idTokens, ...entry.labelTokens]) {+ if (tok.includes(t) || t.includes(tok)) { score += 1; break; }+ }+ }+ }+ return score;+}+function pickPosePreset(prompt) {+ const tokens = poseTokensOf(prompt);+ const deterministic = () => {+ const hash = createHash('sha256').update(String(prompt)).digest();+ return { entry: POSE_INDEX[hash.readUInt32BE(0) % POSE_INDEX.length], score: 0, reason: 'no-match-deterministic-pick' };+ };+ if (tokens.length === 0) return deterministic();+ let best = null;+ let bestScore = -1;+ for (const entry of POSE_INDEX) {+ const sc = scorePosePreset(tokens, entry);+ if (sc > bestScore) { best = entry; bestScore = sc; }+ }+ if (bestScore <= 0) return deterministic();+ return { entry: best, score: bestScore, reason: 'token-match' };+}+const POSE_PREVIEW_BASE = process.env.MCP_POSE_PREVIEW_BASE || 'https://three.ws/pose';++// ── IBM Granite (watsonx.ai) config guard for direct_prompt / generate_material ─+function graniteConfigOrThrow() {+ const cfg = watsonxConfig();+ if (!cfg.configured) {+ throw rpcError(+ -32000,+ 'IBM watsonx.ai is not configured on this server (set WATSONX_API_KEY and WATSONX_PROJECT_ID).',+ );+ }+ return cfg;+}+function stripJsonFence(text) {+ const raw = String(text || '').trim();+ return raw.startsWith('```') ? raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '') : raw;+}+export const toolDefs = [{name: 'text_to_3d',@@ -256,28 +345,56 @@ export const toolDefs = [type: 'string',enum: ['1:1', '4:3', '3:4', '16:9', '9:16'],default: '1:1',- description: 'Aspect ratio of the intermediate reference image.',+ description: 'Aspect ratio of the intermediate reference image (image path only).',+ },+ tier: TIER_PROP,+ path: PATH_PROP,+ backend: BACKEND_PROP,+ __ASPECT_CLOSE__: {},},required: ['prompt'],additionalProperties: false,},- async handler(args, auth) {+ async handler(args, auth, req) {await enforce(limits.mcp3dGenerate, auth);+ const path = parsePathArg(args);+ const tier = resolveTier(parseTierArg(args));+ const backendId = resolveBackendId({ path, backend: args.backend });++ // Geometry-first path (Meshy/Tripo, BYOK) — native text→mesh.+ if (path === 'geometry') {+ return submitGeometryJob({+ req,+ args,+ backendId,+ isImageMode: false,+ prompt: args.prompt,+ primaryImage: null,+ tier,+ path,+ });+ }++ // Image path (default): synthesize a reference image, then reconstruct.const provider = regenProvider();const { imageUrl, model } = await textToImage(args.prompt, {aspectRatio: args.aspect_ratio || '1:1',});- const job = await provider.submit({- mode: 'reconstruct',- params: { image: imageUrl, prompt: args.prompt },- });+ // Only poly-aware backends accept a budget; TRELLIS would 422 on an+ // unknown field, so the tier rides along as provenance only there.+ const params = { image: imageUrl, prompt: args.prompt };+ if (BACKENDS[backendId].polyControl) {+ params.target_polycount = tier.polycount;+ params.tier = tier.id;+ }+ const job = await provider.submit({ mode: 'reconstruct', params });return {content: [{type: 'text',text:- `Started generating a 3D model for "${args.prompt}".\n` ++ `Started generating a 3D model for "${args.prompt}" (${tier.id} tier).\n` +`Reference image: ${imageUrl}\n` +`Job ID: ${job.extJobId}\n${POLL_HINT}`,},@@ -286,6 +403,9 @@ export const toolDefs = [job_id: job.extJobId,status: 'queued',prompt: args.prompt,+ path,+ tier: tier.id,+ backend: backendId,preview_image_url: imageUrl,text_to_image_model: model,eta_seconds: job.eta,@@ -318,10 +438,13 @@ export const toolDefs = [maxLength: 1000,description: 'Optional text hint passed to the reconstruction model.',},+ tier: TIER_PROP,+ path: PATH_PROP,+ backend: BACKEND_PROP,},additionalProperties: false,},- async handler(args, auth) {+ async handler(args, auth, req) {await enforce(limits.mcp3dGenerate, auth);// Merge the multi-view array form with the single image_url, de-duped@@ -363,11 +486,35 @@ export const toolDefs = [}}+ const path = parsePathArg(args);+ const tier = resolveTier(parseTierArg(args));+ const backendId = resolveBackendId({ path, backend: args.backend });++ // Geometry-first path (Meshy/Tripo, BYOK) reconstructs from the primary+ // view; multi-view fusion stays on the image/TRELLIS path below.+ if (path === 'geometry') {+ return submitGeometryJob({+ req,+ args,+ backendId,+ isImageMode: true,+ prompt: args.prompt,+ primaryImage: views[0],+ tier,+ path,+ });+ }+const provider = regenProvider();+ const reconstructParams = { images: views, prompt: args.prompt };+ if (BACKENDS[backendId].polyControl) {+ reconstructParams.target_polycount = tier.polycount;+ reconstructParams.tier = tier.id;+ }const job = await provider.submit({mode: 'reconstruct',sourceUrl: views[0],- params: { images: views, prompt: args.prompt },+ params: reconstructParams,});const viewsUsed = typeof job.viewsUsed === 'number' ? job.viewsUsed : views.length;const multiview = Boolean(job.multiview);@@ -390,7 +537,9 @@ export const toolDefs = [views_requested: views.length,views_used: viewsUsed,multiview,- backend: job.backend ?? null,+ path,+ tier: tier.id,+ backend: job.backend ?? backendId ?? null,eta_seconds: job.eta,},};@@ -414,10 +563,9 @@ export const toolDefs = [required: ['job_id'],additionalProperties: false,},- async handler(args, auth) {+ async handler(args, auth, req) {await enforce(limits.mcp3dStatus, auth);- const provider = regenProvider();- const result = await provider.status(args.job_id);+ const result = await pollAnyProvider(req, args.job_id);if (result.status === 'done' && result.resultGlbUrl) {const glbUrl = result.resultGlbUrl;@@ -1026,4 +1174,209 @@ export const toolDefs = [};},},+ {+ name: 'auto_rig_model',+ title: 'Auto-rig a static 3D model (skeleton + skin weights)',+ description:+ 'Turn a static GLB mesh into an animation-ready character: adds a humanoid skeleton and per-vertex skin weights via the three.ws rig pipeline (VAST-AI UniRig). Pairs with text_to_3d / image_to_3d — generate a mesh, then rig it, then drive it with apply_animation or pose_model. Returns a job_id; poll generation_status for the rigged GLB.',+ inputSchema: {+ type: 'object',+ properties: {+ glb_url: {+ type: 'string',+ format: 'uri',+ description: 'Public https URL of the static GLB mesh to rig.',+ },+ },+ required: ['glb_url'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ await enforce(limits.mcp3dGenerate, auth);+ if (!(await isPublicHttpsUrl(args.glb_url))) {+ return {+ content: [{ type: 'text', text: 'Error: glb_url must be a public https URL.' }],+ isError: true,+ };+ }+ const provider = regenProvider('rerig');+ if (!provider.supportsMode('rerig')) {+ return {+ content: [{ type: 'text', text: 'Auto-rigging is not configured on this deployment.' }],+ isError: true,+ };+ }+ const job = await provider.submit({ mode: 'rerig', sourceUrl: args.glb_url, params: {} });+ return {+ content: [+ {+ type: 'text',+ text:+ `Auto-rigging started.\nJob ID: ${job.extJobId}\n` ++ 'Poll with generation_status — when done it returns a rigged, animation-ready GLB. Typically completes in 30–90 seconds.',+ },+ ],+ structuredContent: {+ job_id: job.extJobId,+ status: 'queued',+ source_glb_url: args.glb_url,+ eta_seconds: typeof job.eta === 'number' ? job.eta : null,+ },+ };+ },+ },+ {+ name: 'pose_model',+ title: 'Resolve a text prompt to a pose-studio seed + joint rotations',+ description:+ 'Map a natural-language pose description to a deterministic pose-studio seed and the full Euler joint-rotation map for the three.ws humanoid mannequin, picked from the in-repo preset library. Returns the preset id, the complete pose (radians per joint), a stable seed, and a previewUrl on three.ws/pose. Deterministic and free — the same prompt always yields the same pose. Pair with auto_rig_model to pose a rigged character.',+ inputSchema: {+ type: 'object',+ properties: {+ prompt: {+ type: 'string',+ minLength: 1,+ maxLength: 500,+ description: 'Pose description, e.g. "warrior stance", "wave hello", "sitting cross-legged".',+ },+ },+ required: ['prompt'],+ additionalProperties: false,+ },+ async handler(args) {+ const picked = pickPosePreset(args.prompt);+ const preset = picked.entry.preset;+ const seed = createHash('sha256').update(`${args.prompt}|${preset.id}`).digest('hex').slice(0, 16);+ const previewUrl = `${POSE_PREVIEW_BASE}?seed=${encodeURIComponent(seed)}&preset=${encodeURIComponent(preset.id)}`;+ return {+ content: [+ {+ type: 'text',+ text: `Pose "${preset.label}" (${preset.group}) — seed ${seed}.\nPreview: ${previewUrl}`,+ },+ ],+ structuredContent: {+ seed,+ preset_id: preset.id,+ preset_label: preset.label,+ group: preset.group,+ parameters: preset.pose,+ preview_url: previewUrl,+ match: { score: picked.score, reason: picked.reason },+ groups: PRESET_GROUPS,+ },+ };+ },+ },+ {+ name: 'direct_prompt',+ title: 'Optimize a rough idea into a 3D-generation prompt (IBM Granite)',+ description:+ 'Rewrite a rough idea into an optimized text_to_3d prompt using IBM Granite. Returns one clean single-subject description plus structured directives (subject, style, materials, colors, detail) that produce cleaner meshes. Run before text_to_3d when a prompt is vague, conflicting, or multi-subject. Requires IBM watsonx.ai credentials on the server.',+ inputSchema: {+ type: 'object',+ properties: {+ idea: {+ type: 'string',+ minLength: 1,+ maxLength: 2000,+ description: 'The rough idea or prompt to optimize, e.g. "some kind of cool dragon thing".',+ },+ style: {+ type: 'string',+ maxLength: 200,+ description: 'Optional style hint, e.g. "low-poly", "realistic", "stylized PBR".',+ },+ },+ required: ['idea'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ await enforce(limits.mcp3dGenerate, auth);+ const cfg = graniteConfigOrThrow();+ const system =+ 'You are a 3D-generation prompt director. Given a rough idea, produce a prompt that yields a single, clearly-described object for image-to-3D reconstruction. Return ONLY valid JSON with keys: "prompt" (one concise sentence describing ONE subject), "subject", "style", "materials" (array), "colors" (array), "detail" (one of draft|standard|high), "notes". No markdown, no prose outside the JSON.';+ const user = args.style ? `${args.idea}\n\nPreferred style: ${args.style}` : args.idea;+ const result = await watsonxChatComplete(cfg, {+ messages: [+ { role: 'system', content: system },+ { role: 'user', content: user },+ ],+ maxTokens: 700,+ temperature: 0.3,+ });+ let parsed = null;+ try {+ parsed = JSON.parse(stripJsonFence(result.text));+ } catch {+ // Granite didn't return clean JSON — surface the raw text below.+ }+ if (!parsed || typeof parsed.prompt !== 'string') {+ return {+ content: [{ type: 'text', text: result.text }],+ structuredContent: { ok: true, optimized_prompt: null, raw_response: result.text, model: result.model },+ };+ }+ return {+ content: [{ type: 'text', text: `Optimized prompt: ${parsed.prompt}` }],+ structuredContent: { ok: true, optimized_prompt: parsed.prompt, spec: parsed, model: result.model, usage: result.usage },+ };+ },+ },+ {+ name: 'generate_material',+ title: 'Generate a glTF PBR material from a description (IBM Granite)',+ description:+ 'Generate a physically-based (PBR) glTF 2.0 material from a text description using IBM Granite — base color, metallic, roughness, and emissive factors. Returns a pbrMetallicRoughness material object you can attach to a generated mesh. Requires IBM watsonx.ai credentials on the server.',+ inputSchema: {+ type: 'object',+ properties: {+ description: {+ type: 'string',+ minLength: 3,+ maxLength: 500,+ description: 'Material to describe, e.g. "worn copper, scratched, slightly oxidized".',+ },+ name: {+ type: 'string',+ maxLength: 100,+ description: 'Optional material name.',+ },+ },+ required: ['description'],+ additionalProperties: false,+ },+ async handler(args, auth) {+ await enforce(limits.mcp3dGenerate, auth);+ const cfg = graniteConfigOrThrow();+ const system =+ 'You are a 3D material author. Given a description, return ONLY a valid glTF 2.0 material JSON object with keys: "name", "pbrMetallicRoughness" { "baseColorFactor": [r,g,b,a] (0-1), "metallicFactor" (0-1), "roughnessFactor" (0-1) }, "emissiveFactor": [r,g,b] (0-1), "doubleSided" (bool), and a "_notes" string. No markdown, no prose outside the JSON.';+ const user = args.name ? `Name: ${args.name}\nMaterial: ${args.description}` : args.description;+ const result = await watsonxChatComplete(cfg, {+ messages: [+ { role: 'system', content: system },+ { role: 'user', content: user },+ ],+ maxTokens: 600,+ temperature: 0.2,+ });+ let material = null;+ try {+ material = JSON.parse(stripJsonFence(result.text));+ } catch {+ // Fall through to raw text when Granite returns non-JSON.+ }+ if (!material || typeof material !== 'object') {+ return {+ content: [{ type: 'text', text: result.text }],+ structuredContent: { ok: true, material: null, raw_response: result.text, model: result.model },+ };+ }+ if (args.name && !material.name) material.name = args.name;+ return {+ content: [{ type: 'text', text: `Generated glTF material${material.name ? ` "${material.name}"` : ''}.` }],+ structuredContent: { ok: true, material, model: result.model, usage: result.usage },+ };+ },+ },];diff --git a/api/coin/[mint]/cohorts.js b/api/coin/[mint]/cohorts.jsindex 1eea16dec..d6563b5d6 100644--- a/api/coin/[mint]/cohorts.js+++ b/api/coin/[mint]/cohorts.js@@ -16,14 +16,23 @@ import { sql } from '../../_lib/db.js';import { cors, json, error, method, wrap } from '../../_lib/http.js';import { isValidSolanaAddress } from '../../_lib/validate.js';import { getSessionUser } from '../../_lib/auth.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';import {loadCoinByMint,listCohorts,isCohortId,cohortCounts,queryCohort,+ isLiveCohort,+ liveHolderSet,+ liveCohortCounts,+ liveCohortMembers,} from '../../_lib/coin/index.js';+// Holder data changes slowly and the live path costs a Helius call, so let the+// CDN absorb repeat loads (the agent detail page hits this on every view).+const OVERVIEW_CACHE = 'public, max-age=30, s-maxage=120, stale-while-revalidate=300';+function mintFromReq(req) {const m = req.query?.mint;if (m) return m;@@ -56,6 +65,113 @@ function numParam(url, key) {return Number.isFinite(n) ? n : undefined;}+/** A launched agent token (no coin_launches row) identified by its mint. */+async function loadAgentTokenByMint(mint) {+ const [row] = await sql`+ select id, user_id, meta->'token' as token+ from agent_identities+ where meta->'token'->>'mint' = ${mint} and deleted_at is null+ limit 1+ `;+ return row || null;+}++/** True if the session user owns the agent that launched this token (or admin). */+function ownsAgentToken(user, agentToken) {+ if (!user) return false;+ if (user.is_admin) return true;+ return Boolean(agentToken.user_id) && user.id === agentToken.user_id;+}++// Agent tokens have no snapshot, so cohorts are computed live from the holder+// set Helius indexes for the mint. Same two shapes as the snapshot path:+// public counts + concentration, and a creator-only sampled member export.+// Tenure cohorts (diamond-hands / new-buyers / exited) report null / 422 —+// they need holder history this token has not accrued yet.+async function serveLiveCohorts(req, res, { mint, agentToken }) {+ const rl = await limits.cohortsIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const url = new URL(req.url, 'http://localhost');+ const cohortId = url.searchParams.get('cohort');+ const params = {+ topPct: numParam(url, 'topPct'),+ minHoldDays: numParam(url, 'minHoldDays'),+ windowDays: numParam(url, 'windowDays'),+ idleDays: numParam(url, 'idleDays'),+ };++ const token = agentToken.token || {};+ const network = token.cluster === 'devnet' ? 'devnet' : 'mainnet';+ const coinInfo = { mint, symbol: token.symbol || null, name: token.name || null };++ let set;+ try {+ set = await liveHolderSet({ mint, network });+ } catch (e) {+ // Helius unconfigured / RPC blip — typed, not a 500.+ return error(res, 503, 'holders_unavailable', e?.message || 'holder data is temporarily unavailable');+ }++ // ── Overview: definitions + counts + concentration (public) ──────────────+ if (!cohortId) {+ const { holderCount, counts, concentration } = liveCohortCounts(set, params);+ res.setHeader('Cache-Control', OVERVIEW_CACHE);+ return json(res, 200, {+ coin: coinInfo,+ source: 'live',+ lastSnapshotAt: null,+ holderCount,+ concentration,+ cohorts: listCohorts().map((c) => ({ ...c, count: counts[c.id] ?? null })),+ });+ }++ // ── Member export: token creator only ────────────────────────────────────+ if (!isCohortId(cohortId)) {+ return error(res, 404, 'not_found', `unknown cohort: ${cohortId}`);+ }+ const user = await getSessionUser(req, res).catch(() => null);+ if (!user) return error(res, 401, 'unauthenticated', 'sign in to export cohort members');+ if (!ownsAgentToken(user, agentToken)) {+ return error(res, 403, 'forbidden', 'only the token creator can export holder cohorts');+ }+ if (!isLiveCohort(cohortId)) {+ return error(+ res,+ 422,+ 'snapshot_required',+ `the "${cohortId}" cohort needs holder history, which this token has not accrued yet`,+ );+ }++ const limit = numParam(url, 'limit') ?? 200;+ const sampleRaw = numParam(url, 'sample');+ const sample = sampleRaw != null && sampleRaw > 0 && sampleRaw < 1 ? sampleRaw : undefined;+ const salt = url.searchParams.get('salt') || mint;++ const { members, sampled, total, truncated } = liveCohortMembers(set, {+ cohortId,+ params,+ limit,+ sample,+ salt,+ });++ return json(res, 200, {+ coin: coinInfo,+ source: 'live',+ cohort: cohortId,+ sampled,+ sample: sample ?? null,+ count: members.length,+ total,+ truncated,+ members,+ lastSnapshotAt: null,+ });+}+export default wrap(async (req, res) => {if (cors(req, res)) return;if (!method(req, res, ['GET'])) return;@@ -66,7 +182,14 @@ export default wrap(async (req, res) => {}const coin = await loadCoinByMint(mint);- if (!coin) return error(res, 404, 'not_found', 'no launch found for this mint');+ if (!coin) {+ // Agent tokens are never registered in coin_launches, so they have no+ // coin_holders snapshot — serve live Helius-derived cohorts instead.+ // A mint that is neither a launch nor a known agent token still 404s.+ const agentToken = await loadAgentTokenByMint(mint);+ if (agentToken) return serveLiveCohorts(req, res, { mint, agentToken });+ return error(res, 404, 'not_found', 'no launch found for this mint');+ }const url = new URL(req.url, 'http://localhost');const cohortId = url.searchParams.get('cohort');diff --git a/api/marketplace/buy-asset.js b/api/marketplace/buy-asset.jsindex 789ea47f2..de5a75368 100644--- a/api/marketplace/buy-asset.js+++ b/api/marketplace/buy-asset.js@@ -27,6 +27,7 @@ import { clientIp, limits } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.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'];@@ -250,7 +251,7 @@ async function handleConfirm(req, res, reference) {return error(res, 410, 'purchase_expired', 'this pending purchase expired; please start a new one');}if (pur.chain !== 'solana') {- return error(res, 501, 'not_implemented', `chain '${pur.chain}' confirmation not yet supported`);+ return handleEvmAssetConfirm(req, res, pur);}const refKey = new PublicKey(pur.reference);@@ -301,6 +302,13 @@ async function handleConfirm(req, res, reference) {});}+ return finalizeAssetConfirm(res, pur, txSignature);+}++// Atomic confirm + receipt + notifications for a verified asset payment. Shared+// by the Solana and EVM confirm paths; `txSignature` is the Solana signature or+// the EVM tx hash.+async function finalizeAssetConfirm(res, pur, txSignature) {const updated = await sql`UPDATE asset_purchasesSET status = 'confirmed', tx_signature = ${txSignature}, confirmed_at = now(), updated_at = now()@@ -355,6 +363,59 @@ async function handleConfirm(req, res, reference) {return json(res, 200, { data: { status: 'confirmed', tx_signature: txSignature } });}+// EVM asset confirm: the buyer submits the settlement tx hash; verify a USDC+// transfer of at least the price reached the seller's payout wallet on Base,+// then finalize through the same path as Solana.+async function handleEvmAssetConfirm(req, res, pur) {+ if (!evmChainId(pur.chain)) {+ return error(res, 400, 'unsupported_chain', `chain '${pur.chain}' is not supported`);+ }+ const body = await readJson(req).catch(() => null);+ const 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');++ // Idempotency: one settlement tx can confirm at most one purchase.+ const [dupe] = await sql`+ SELECT id FROM asset_purchases+ WHERE tx_signature = ${txHash} AND status IN ('confirmed', 'tipped') AND id != ${pur.id}+ LIMIT 1+ `;+ if (dupe) return error(res, 409, 'transfer_mismatch', 'this transaction has already been used for another purchase');++ const result = await verifyEvmUsdcPayment({+ txHash,+ chain: pur.chain,+ recipient: pur.payout_address,+ expectedAmount: pur.amount,+ });+ if (result.status === 'pending') return json(res, 200, { data: { status: 'pending' } });+ if (result.status === 'mismatch') {+ // A short-but-real transfer is a tip; nothing on-chain is a hard mismatch.+ if (result.actualAmount && BigInt(result.actualAmount) > 0n) {+ await sql`+ UPDATE asset_purchases+ SET status = 'tipped', tx_signature = ${txHash}, confirmed_at = now(), updated_at = now()+ WHERE id = ${pur.id} AND status = 'pending'+ `;+ await insertNotification(pur.seller_user_id, 'asset_payment_mismatch', {+ item_type: pur.item_type,+ item_id: pur.item_id,+ expected_amount: String(pur.amount),+ actual_amount: result.actualAmount,+ tx_signature: txHash,+ purchase_id: pur.id,+ reason: result.message,+ });+ return error(res, 409, 'transfer_mismatch', result.message || 'on-chain transfer did not match expected', {+ status: 'tipped',+ tx_signature: txHash,+ });+ }+ return error(res, 409, 'transfer_mismatch', result.message || 'no matching transfer found');+ }+ return finalizeAssetConfirm(res, pur, txHash);+}+// Resolve the inviting user from a ?ref=<code> query or users.referred_by_id.async function resolveReferrer(req, buyerUserId) {const url = new URL(req.url, 'http://x');diff --git a/api/marketplace/purchase.js b/api/marketplace/purchase.jsindex c0f86ae8b..77eb4f225 100644--- a/api/marketplace/purchase.js+++ b/api/marketplace/purchase.js@@ -255,11 +255,16 @@ async function handleConfirm(req, res, reference) {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') {- return error(res, 501, 'not_implemented', `chain '${pur.chain}' confirmation not yet supported`);+ 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');}- const result = await confirmSkillPurchase({ ...pur, reference });+ const result = await confirmSkillPurchase({ ...pur, reference }, { txHash });if (result.status === 'pending') {return json(res, 200, { data: { status: 'pending' } });}diff --git a/server-3d.json b/server-3d.jsonindex 10323194d..fd05ca4d1 100644--- a/server-3d.json+++ b/server-3d.json@@ -1,7 +1,7 @@{"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "io.github.nirholas/threews-3d-studio",- "description": "Turn text or an image into an interactive, textured 3D model (GLB). By three.ws.",+ "description": "Turn text or an image into an interactive, animation-ready 3D model (GLB): generate (text/image→3D, quality tiers + geometry backends), auto-rig, animate, pose, remesh, segment, retexture, and IBM Granite prompt-direction + material generation. By three.ws.","repository": {"url": "https://github.com/nirholas/three.ws","source": "github"diff --git a/src/agent-detail.css b/src/agent-detail.cssindex cce319bc9..9b0f606a4 100644--- a/src/agent-detail.css+++ b/src/agent-detail.css@@ -1122,3 +1122,167 @@ a { color: inherit; text-decoration: none; }.ad-version-row { grid-template-columns: auto 1fr; }.ad-version-when { grid-column: 2; }}++/* ───────────────────────────────────────────────────────────────────────────+ Holder cohorts panel (agent-detail.js → renderHolderCohorts)+ Live audience segmentation under an agent token: size cohorts, whale share,+ and concentration. Tokens mirror :root; cyan→green fill, no new chroma.+─────────────────────────────────────────────────────────────────────────── */+.ad-cohorts {+ margin-top: 14px;+ padding-top: 12px;+ border-top: 1px solid var(--ad-line);+}+.ad-cohorts-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 10px;+}+.ad-cohorts-title {+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.14em;+ color: var(--ad-muted);+}+.ad-cohorts-count {+ font-size: 15px;+ font-weight: 700;+ color: var(--ad-text);+ font-variant-numeric: tabular-nums;+}+.ad-cohorts-body {+ margin-top: 10px;+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.ad-cohort-row {+ display: grid;+ grid-template-columns: minmax(86px, auto) 1fr auto;+ align-items: center;+ gap: 10px;+ font-size: 12px;+}+.ad-cohort-name {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ color: var(--ad-text);+ white-space: nowrap;+}+.ad-cohort-icon { font-size: 12px; line-height: 1; }+.ad-cohort-bar {+ height: 6px;+ min-width: 40px;+ border-radius: 999px;+ background: var(--ad-line);+ overflow: hidden;+}+.ad-cohort-fill {+ display: block;+ height: 100%;+ border-radius: inherit;+ background: linear-gradient(90deg, var(--ad-cyan), var(--ad-green));+ transition: width 0.5s ease;+}+.ad-cohort-val {+ color: var(--ad-muted);+ font-size: 11px;+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}+.ad-cohorts-conc {+ margin-top: 12px;+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 8px;+}+.ad-conc-chip {+ font-size: 10.5px;+ font-weight: 600;+ letter-spacing: 0.02em;+ padding: 2px 8px;+ border-radius: 999px;+ border: 1px solid var(--ad-line-2);+ color: var(--ad-muted);+}+.ad-conc-healthy {+ color: var(--ad-green);+ border-color: rgba(74, 222, 128, 0.35);+ background: rgba(74, 222, 128, 0.10);+}+.ad-conc-moderate {+ color: var(--ad-cyan);+ border-color: rgba(87, 199, 255, 0.35);+ background: rgba(87, 199, 255, 0.10);+}+.ad-conc-high {+ color: var(--ad-amber);+ border-color: rgba(245, 165, 36, 0.35);+ background: rgba(245, 165, 36, 0.10);+}+.ad-conc-very-high {+ color: #f87171;+ border-color: rgba(248, 113, 113, 0.35);+ background: rgba(248, 113, 113, 0.10);+}+.ad-cohorts-conc-detail {+ color: var(--ad-muted);+ font-size: 11px;+ font-variant-numeric: tabular-nums;+}+.ad-cohorts-note {+ margin-top: 8px;+ font-size: 10.5px;+ line-height: 1.4;+ color: var(--ad-dim);+}+.ad-cohorts-empty {+ margin-top: 10px;+ font-size: 12px;+ color: var(--ad-muted);+}+.ad-cohorts-err {+ margin-top: 10px;+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 12px;+}+.ad-cohorts-retry {+ background: none;+ border: 1px solid var(--ad-line-2);+ color: var(--ad-text);+ border-radius: 7px;+ padding: 3px 10px;+ font-size: 11px;+ cursor: pointer;+ transition: background 0.15s, border-color 0.15s;+}+.ad-cohorts-retry:hover {+ background: rgba(255, 255, 255, 0.04);+ border-color: var(--ad-line-2);+}+.ad-skel {+ position: relative;+ overflow: hidden;+ background: var(--skeleton-base);+ border-radius: var(--skeleton-radius);+}+.ad-skel::after {+ content: '';+ position: absolute;+ inset: 0;+ transform: translateX(-100%);+ background: linear-gradient(90deg, transparent, var(--skeleton-sheen), transparent);+ animation: ad-cohort-shimmer 1.4s infinite;+}+.ad-skel-count { display: inline-block; width: 44px; height: 16px; }+.ad-skel-row { height: 18px; width: 100%; }+@keyframes ad-cohort-shimmer { 100% { transform: translateX(100%); } }+@media (prefers-reduced-motion: reduce) {+ .ad-skel::after { animation: none; }+ .ad-cohort-fill { transition: none; }+}diff --git a/src/agent-detail.js b/src/agent-detail.jsindex c8a4280a2..c7d442d23 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -93,6 +93,143 @@ function pill(text, accent = '') {return el('span', { class: `ad-pill ${accent ? `ad-pill-${accent}` : ''}`, text });}+// ── Holder cohorts panel ─────────────────────────────────────────────────────+// Renders the live holder segmentation for an agent token from+// GET /api/coin/:mint/cohorts. Self-manages loading / empty / error / populated+// states so the caller just hands it a container and a mint.++const COHORT_ICONS = {+ holders: '👥',+ whales: '🐋',+ 'diamond-hands': '💎',+ 'new-buyers': '🌱',+ exited: '🚪',+};++const CONC_LABELS = {+ healthy: 'Healthy spread',+ moderate: 'Moderate',+ high: 'Concentrated',+ 'very-high': 'Highly concentrated',+ none: '—',+};++function fmtInt(n) {+ return Number(n || 0).toLocaleString('en-US');+}++function fmtPct(frac) {+ const v = Number(frac || 0) * 100;+ return `${v >= 10 || v === 0 ? v.toFixed(0) : v.toFixed(1)}%`;+}++function cohortsSkeleton() {+ return el('div', {}, [+ el('div', { class: 'ad-cohorts-head' }, [+ el('span', { class: 'ad-cohorts-title', text: 'HOLDERS' }),+ el('span', { class: 'ad-skel ad-skel-count' }),+ ]),+ el('div', { class: 'ad-cohorts-body' }, [+ el('div', { class: 'ad-skel ad-skel-row' }),+ el('div', { class: 'ad-skel ad-skel-row' }),+ ]),+ ]);+}++function cohortsErrorState(retry) {+ const btn = el('button', { class: 'ad-cohorts-retry', type: 'button', text: 'Retry' });+ btn.addEventListener('click', retry);+ return el('div', { class: 'ad-cohorts-err' }, [+ el('span', { class: 'ad-muted', text: 'Couldn’t load holder cohorts.' }),+ btn,+ ]);+}++function cohortRow(c, frac) {+ const pct = Math.max(0, Math.min(1, frac));+ return el('div', { class: 'ad-cohort-row', title: c.description || c.name }, [+ el('span', { class: 'ad-cohort-name' }, [+ el('span', { class: 'ad-cohort-icon', text: COHORT_ICONS[c.id] || '•' }),+ el('span', { text: c.name }),+ ]),+ el('span', { class: 'ad-cohort-bar' }, [+ el('span', { class: 'ad-cohort-fill', style: `width:${(pct * 100).toFixed(1)}%` }),+ ]),+ el('span', { class: 'ad-cohort-val', text: `${fmtInt(c.count)} · ${fmtPct(frac)}` }),+ ]);+}++function cohortsView(data) {+ const holderCount =+ data.holderCount ?? (data.cohorts || []).find((c) => c.id === 'holders')?.count ?? 0;+ const nodes = [+ el('div', { class: 'ad-cohorts-head' }, [+ el('span', { class: 'ad-cohorts-title', text: 'HOLDERS' }),+ el('span', { class: 'ad-cohorts-count', text: fmtInt(holderCount) }),+ ]),+ ];++ if (!holderCount) {+ nodes.push(el('div', { class: 'ad-cohorts-empty', text: 'No holders yet — be the first.' }));+ return nodes;+ }++ const locked = [];+ const body = el('div', { class: 'ad-cohorts-body' });+ for (const c of data.cohorts || []) {+ if (c.id === 'holders') continue; // the header already shows the total+ if (c.count == null) {+ locked.push(c.name);+ continue;+ }+ body.appendChild(cohortRow(c, holderCount ? c.count / holderCount : 0));+ }+ if (body.childNodes.length) nodes.push(body);++ const con = data.concentration;+ if (con) {+ nodes.push(+ el('div', { class: 'ad-cohorts-conc' }, [+ el('span', {+ class: `ad-conc-chip ad-conc-${con.label || 'none'}`,+ text: CONC_LABELS[con.label] || con.label || '—',+ }),+ el('span', {+ class: 'ad-cohorts-conc-detail',+ text: `Top holder ${fmtPct(con.top1Share)} · Top 10 ${fmtPct(con.top10Share)}`,+ }),+ ]),+ );+ }++ if (locked.length) {+ nodes.push(+ el('div', {+ class: 'ad-cohorts-note',+ text: `${locked.join(' · ')} unlock once holder history is recorded.`,+ }),+ );+ }+ return nodes;+}++async function renderHolderCohorts(box, mint) {+ box.classList.add('ad-cohorts');+ box.replaceChildren(cohortsSkeleton());+ let data;+ try {+ const r = await fetch(`/api/coin/${encodeURIComponent(mint)}/cohorts`, {+ credentials: 'include',+ });+ if (!r.ok) throw new Error(String(r.status));+ data = await r.json();+ } catch {+ box.replaceChildren(cohortsErrorState(() => renderHolderCohorts(box, mint)));+ return;+ }+ box.replaceChildren(...cohortsView(data));+}+function renderService(svc) {const meta = SERVICE_TYPES[svc.type] || { tag: (svc.type || '').toUpperCase() };const head = el('div', { class: 'ad-svc-head' }, [@@ -202,6 +339,12 @@ function render(agent) {text: `View on ${agent.token.cluster === 'devnet' ? 'Solana Explorer' : 'pump.fun'} →`,});$('ad-token-body').appendChild(viewBtn);++ // Live holder segmentation for this token — fire-and-forget; the panel+ // renders its own loading / empty / error / populated states.+ const cohortsBox = el('div', { class: 'ad-cohorts' });+ $('ad-token-body').appendChild(cohortsBox);+ renderHolderCohorts(cohortsBox, agent.token.mint);} else if (agent.isOwner) {$('ad-token-body').classList.remove('ad-muted');$('ad-token-body').textContent = '';diff --git a/tasks/week-2026-06-08/C6-three-live-reconcile.md b/tasks/week-2026-06-08/C6-three-live-reconcile.mddeleted file mode 100644index 08b394d51..000000000--- a/tasks/week-2026-06-08/C6-three-live-reconcile.md+++ /dev/null@@ -1,68 +0,0 @@-# C6 — Reconcile + polish `/three-live` against Task 13 (don't rebuild it)--**Track:** C — build next · **Priority:** P3 · **Effort:** ~half day · **Depends on:** none-(optionally adopts the **C1** store)--## Context--`tasks/wow-sprint/13-onchain-activity-visualization.md` specs a reactive 3D onchain-activity-visualization, and points at `pages/pump-visualizer.html`. But the real $THREE implementation-already exists and is **~80% done**: `pages/three-live.html` ("$THREE Live · Protocol Pulse",-routed at `/three-live` in `vite.config.js`) — a Three.js scene with an `EventSource` trade stream,-particle bursts, whale shockwaves, a reconnect loop, `prefers-reduced-motion` handling, a-`requestAnimationFrame` loop, and a HUD reading `/api/three-token/stats` + `/api/agents/pumpfun-feed`.--Meanwhile `pages/pump-visualizer.html` (routed at `/pump-visualizer`) is a separate **generic**-pump.fun visualizer, not $THREE-scoped. **Do not build a third scene, and do not fork.**--## What to do (reconcile, then polish)--1. **Read both** `pages/three-live.html` and `pages/pump-visualizer.html`, plus- `tasks/wow-sprint/13-onchain-activity-visualization.md`. Produce (in your commit message or a- short note) a clear statement of what Task 13 asked for vs what `three-live.html` already- delivers — i.e. **close the gap, don't restart**.-2. **Decide the canonical surface.** `three-live.html` is the $THREE one — treat it as canonical.- If `pump-visualizer.html` overlaps and is redundant/unmaintained, either keep it explicitly as- the generic-token tool (clearly distinct) or, if it's dead, propose removing it (don't delete- without confirming it's unreferenced — check `vite.config.js`, nav, and links first).-3. **Polish `three-live.html` to fully satisfy Task 13's checklist:** verify every item the doc- lists is present and working — reactive intensity tied to real trade volume, whale emphasis,- reduced-motion path, reconnect resilience, empty/idle state when no trades, HUD accuracy, mobile- behavior, and accessibility. Fix whatever is missing or rough.-4. **Optional:** retrofit the HUD to read from the **C1** store (`src/pump/three-token-data.js`)- instead of its own `/api/three-token/stats` fetch, for consistency. Only if C1 is merged and it's- a clean swap.-5. **Cross-link** `/three-live` from the holder dashboard / token page / nav so it's discoverable- (it's a screenshot-worthy surface — make sure people can find it).--## Acceptance criteria--- [ ] A written reconciliation of Task 13 vs `three-live.html` (what was already done, what you- closed) is captured in the commit message.-- [ ] Every Task 13 checklist item is satisfied by `three-live.html` (verified, not assumed).-- [ ] No third/forked scene introduced; `pump-visualizer.html`'s status (kept-as-generic or- proposed-for-removal) is resolved explicitly.-- [ ] Idle/empty (no trades), reconnect, and reduced-motion states all work; mobile + a11y verified.-- [ ] `/three-live` is reachable from at least one holder surface + nav.-- [ ] No console errors; the trade stream shows real activity and reconnects cleanly.--## Verification--1. `npm run dev`; open `/three-live`. Confirm real trades animate, whales emphasized, HUD matches- `/api/three-token/stats`.-2. Force-disconnect the stream → confirm reconnect; idle period → confirm the no-trades state.-3. Toggle `prefers-reduced-motion` → confirm the reduced path. Test on a narrow viewport.-4. Confirm the cross-links resolve.--## Rules--Obey [CLAUDE.md](../../CLAUDE.md). Only $THREE on this surface. Real trade stream — no synthetic-activity. Don't duplicate an existing surface.--## Completion protocol--1. Re-read your diff (`git diff`) and confirm every line is justified.-2. Delete this file: `tasks/week-2026-06-08/C6-three-live-reconcile.md`.-3. Commit your code **and** this file's deletion together, e.g.:- `git add -A && git commit -m "polish(three-live): satisfy Task 13 checklist + reconcile vs pump-visualizer; close C6"`-4. Do **not** push — the human controls pushes.diff --git a/tests/evm-payment-verify.test.js b/tests/evm-payment-verify.test.jsnew file mode 100644index 000000000..eae191502--- /dev/null+++ b/tests/evm-payment-verify.test.js@@ -0,0 +1,119 @@+// Tests for the EVM USDC payment verifier. We partial-mock viem so the Base+// public client is controllable, but keep the real getAddress / decodeEventLog /+// parseAbiItem so log decoding and checksumming are exercised for real.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const h = vi.hoisted(() => ({+ client: { getTransactionReceipt: vi.fn(), getBlockNumber: vi.fn() },+}));++vi.mock('viem', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, createPublicClient: vi.fn(() => h.client) };+});++import { verifyEvmUsdcPayment } from '../api/_lib/evm-payment-verify.js';++const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';+const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';+const RECIPIENT = '0x1111111111111111111111111111111111111111';+const TX = '0x' + 'a'.repeat(64);++const padAddr = (a) => '0x' + a.slice(2).toLowerCase().padStart(64, '0');+const padU256 = (v) => '0x' + BigInt(v).toString(16).padStart(64, '0');+function transferLog({ address = USDC_BASE, to, value, from = '0x0000000000000000000000000000000000000002' }) {+ return { address, topics: [TRANSFER_TOPIC, padAddr(from), padAddr(to)], data: padU256(value) };+}++beforeEach(() => {+ h.client.getTransactionReceipt.mockReset();+ h.client.getBlockNumber.mockReset();+ h.client.getBlockNumber.mockResolvedValue(1000n); // head far ahead → confirmations satisfied+});++describe('verifyEvmUsdcPayment', () => {+ it('matches when a sufficient USDC transfer reaches the recipient', async () => {+ h.client.getTransactionReceipt.mockResolvedValue({+ status: 'success', blockNumber: 990n,+ logs: [transferLog({ to: RECIPIENT, value: 1_000_000n })],+ });+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('match');+ expect(r.actualAmount).toBe('1000000');+ });++ it('is pending when the tx is not yet mined', async () => {+ h.client.getTransactionReceipt.mockRejectedValue(new Error('not found'));+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('pending');+ });++ it('is pending when confirmations are insufficient', async () => {+ h.client.getBlockNumber.mockResolvedValue(990n); // head == block → 1 confirmation < 2+ h.client.getTransactionReceipt.mockResolvedValue({+ status: 'success', blockNumber: 990n,+ logs: [transferLog({ to: RECIPIENT, value: 1_000_000n })],+ });+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('pending');+ });++ it('rejects a reverted transaction', async () => {+ h.client.getTransactionReceipt.mockResolvedValue({ status: 'reverted', blockNumber: 990n, logs: [] });+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('mismatch');+ });++ it('rejects when the transfer went to a different wallet', async () => {+ h.client.getTransactionReceipt.mockResolvedValue({+ status: 'success', blockNumber: 990n,+ logs: [transferLog({ to: '0x2222222222222222222222222222222222222222', value: 1_000_000n })],+ });+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('mismatch');+ });++ it('reports a short transfer as a mismatch with the actual amount (tip)', async () => {+ h.client.getTransactionReceipt.mockResolvedValue({+ status: 'success', blockNumber: 990n,+ logs: [transferLog({ to: RECIPIENT, value: 400_000n })],+ });+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('mismatch');+ expect(r.actualAmount).toBe('400000');+ });++ it('ignores Transfer events from a non-USDC contract', async () => {+ h.client.getTransactionReceipt.mockResolvedValue({+ status: 'success', blockNumber: 990n,+ logs: [transferLog({ address: '0x9999999999999999999999999999999999999999', to: RECIPIENT, value: 1_000_000n })],+ });+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('mismatch');+ });++ it('rejects a malformed tx hash without calling RPC', async () => {+ const r = await verifyEvmUsdcPayment({ txHash: 'nope', chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('mismatch');+ expect(h.client.getTransactionReceipt).not.toHaveBeenCalled();+ });++ it('rejects an unsupported chain', async () => {+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'fantom', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('mismatch');+ });++ it('sums multiple USDC transfers to the recipient in one tx', async () => {+ h.client.getTransactionReceipt.mockResolvedValue({+ status: 'success', blockNumber: 990n,+ logs: [+ transferLog({ to: RECIPIENT, value: 600_000n }),+ transferLog({ to: RECIPIENT, value: 600_000n }),+ ],+ });+ const r = await verifyEvmUsdcPayment({ txHash: TX, chain: 'base', recipient: RECIPIENT, expectedAmount: '1000000' });+ expect(r.status).toBe('match');+ expect(r.actualAmount).toBe('1200000');+ });+});