Skip to content

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

feat: runtime skill-access, solana-pay webhook refactor, pay page updates, eth vanity tests

nirholasfa2754df9525
diff --git a/api/cron/[name].js b/api/cron/[name].js
index b3b400070..7c7a172b5 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -64,6 +64,8 @@ const HANDLERS = {
'settle-royalties': handleSettleRoyalties,
'solana-attest-event-cleanup': handleSolanaAttestEventCleanup,
'solana-attestations-crawl': handleSolanaAttestationsCrawl,
+ 'expire-pending-purchases': handleExpirePendingPurchases,
+ 'cleanup-csrf-tokens': handleCleanupCsrfTokens,
};
export default wrap(async (req, res) => {
@@ -2371,3 +2373,30 @@ async function handleAuditLogCleanup(req, res) {
`;
return json(res, 200, { deleted: result.length, retention_days: AUDIT_LOG_RETENTION_DAYS });
}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// expire-pending-purchases — fail-close stale pending skill purchases.
+// Schedule: every 5 minutes. Marks rows past expires_at as 'expired' so the
+// idempotent-create path issues a fresh reference on the buyer's next attempt.
+// ═══════════════════════════════════════════════════════════════════════════
+
+async function handleExpirePendingPurchases(req, res) {
+ if (!method(req, res, ['GET'])) return;
+ const result = await sql`
+ UPDATE skill_purchases
+ SET status = 'expired', updated_at = now()
+ WHERE status = 'pending' AND expires_at IS NOT NULL AND expires_at < now()
+ RETURNING id
+ `;
+ return json(res, 200, { expired: result.length });
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// cleanup-csrf-tokens — drop expired tokens. Run hourly.
+// ═══════════════════════════════════════════════════════════════════════════
+
+async function handleCleanupCsrfTokens(req, res) {
+ if (!method(req, res, ['GET'])) return;
+ const result = await sql`DELETE FROM csrf_tokens WHERE expires_at < now() RETURNING token`;
+ return json(res, 200, { deleted: result.length });
+}
diff --git a/api/webhooks/solana-pay.js b/api/webhooks/solana-pay.js
index fd4956bd8..bc0cd5d27 100644
--- a/api/webhooks/solana-pay.js
+++ b/api/webhooks/solana-pay.js
@@ -1,35 +1,24 @@
/**
- * POST /api/webhooks/solana-pay
- * Server-side webhook / polling endpoint to confirm a pending skill purchase.
- * Called by a cron job or monitoring service after it observes the on-chain tx.
+ * /api/webhooks/solana-pay
+ * --------------------------------------------------------------
+ * GET — Solana Pay merchant discovery probe: returns { label, icon }.
+ * POST — Off-web confirmation path. Looks up the pending skill_purchases row
+ * by reference and runs the same on-chain verification + ledger writes
+ * as the buyer's polling /confirm endpoint via confirmSkillPurchase().
+ * Mainly useful for mobile QR flows where the merchant pings the
+ * server directly after the buyer signs in their wallet.
*
- * Body: { reference }
- * reference — the base58 Solana Pay reference key for the skill_purchases row
- *
- * Authorization: bearer token matching WEBHOOK_SECRET env var.
- *
- * Flow:
- * 1. Look up the pending skill_purchases row by reference.
- * 2. Use findReference + validateTransfer to locate and verify the on-chain tx.
- * 3. Mark the purchase confirmed and return.
+ * Auth: Authorization: Bearer <WEBHOOK_SECRET>. The reference itself is also
+ * a unique secret, so the surface is narrow; we still gate to avoid spammy
+ * DoS-via-confirm probes.
*/
-import { PublicKey } from '@solana/web3.js';
-import { findReference, validateTransfer } from '@solana/pay';
-import BigNumber from 'bignumber.js';
-
import { sql } from '../_lib/db.js';
import { error, json, method, readJson, wrap } from '../_lib/http.js';
-import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';
-
-let _rpc;
-function rpc() {
- if (!_rpc) _rpc = rpcFallbackFromEnv({ network: 'mainnet' });
- return _rpc;
-}
+import { confirmSkillPurchase } from '../_lib/purchase-confirm.js';
function authOk(req) {
const secret = process.env.WEBHOOK_SECRET;
- if (!secret) return false; // require explicit secret; no secret = endpoint disabled
+ if (!secret) return false;
const header = req.headers?.authorization || '';
return header === `Bearer ${secret}`;
}
@@ -38,7 +27,6 @@ export default wrap(async (req, res) => {
if (!method(req, res, ['GET', 'POST'])) return;
if (req.method === 'GET') {
- // Solana Pay merchant discovery probe.
return json(res, 200, {
label: '3D-Agent Skill Marketplace',
icon: 'https://three.ws/assets/logo.png',
@@ -51,108 +39,32 @@ export default wrap(async (req, res) => {
const reference = typeof body?.reference === 'string' ? body.reference.trim() : null;
if (!reference) return error(res, 400, 'validation_error', 'reference required');
- // Load the pending purchase
const [pur] = await sql`
- SELECT id, user_id, agent_id, skill, status, amount, currency_mint, chain
- FROM skill_purchases
- WHERE reference = ${reference}
+ SELECT sp.*, COALESCE(asp.mint_decimals, 6) AS mint_decimals
+ FROM skill_purchases sp
+ LEFT JOIN agent_skill_prices asp
+ ON asp.agent_id = sp.agent_id AND asp.skill = sp.skill
+ WHERE sp.reference = ${reference}
LIMIT 1
`;
if (!pur) return error(res, 404, 'not_found', 'purchase not found');
- if (pur.status === 'confirmed') {
- return json(res, 200, { data: { status: 'confirmed' } });
- }
- if (pur.status === 'failed') {
- return error(res, 409, 'purchase_failed', 'purchase was already marked failed');
- }
- if (pur.chain !== 'solana') {
- return error(res, 501, 'not_implemented', `chain '${pur.chain}' not supported`);
- }
-
- // Resolve payout wallet (re-verify to prevent recipient drift)
- const [payout] = await sql`
- SELECT pw.address
- FROM agent_identities a
- JOIN agent_payout_wallets pw
- ON pw.user_id = a.user_id
- AND pw.chain = 'solana'
- AND (pw.agent_id = a.id OR pw.is_default = true)
- WHERE a.id = ${pur.agent_id}
- ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC
- LIMIT 1
- `;
- let recipientAddress = payout?.address;
- if (!recipientAddress) {
- const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${pur.agent_id}`;
- recipientAddress = row?.meta?.solana_address ?? null;
- }
- if (!recipientAddress) return error(res, 412, 'creator_wallet_missing', 'payout wallet not configured');
-
- const refKey = new PublicKey(reference);
- const recipient = new PublicKey(recipientAddress);
- const splToken = new PublicKey(pur.currency_mint);
- const expectedAmount = new BigNumber(pur.amount).dividedBy(1e6); // 6-decimal USDC
-
- let signatureInfo;
- try {
- signatureInfo = await rpc().withFallback((conn) =>
- findReference(conn, refKey, { finality: 'confirmed' }),
- );
- } catch (e) {
- if (/FindReferenceError|not found/i.test(e?.message || '')) {
- return json(res, 200, { data: { status: 'pending' } });
- }
- throw e;
- }
-
- const txSig = signatureInfo.signature;
+ let result;
try {
- await rpc().withFallback((conn) =>
- validateTransfer(
- conn,
- txSig,
- { recipient, amount: expectedAmount, splToken, reference: refKey },
- { commitment: 'confirmed' },
- ),
- );
+ result = await confirmSkillPurchase(pur);
} catch (e) {
- await sql`
- UPDATE skill_purchases SET status = 'failed', tx_signature = ${txSig}
- WHERE id = ${pur.id} AND status = 'pending'
- `;
- return error(res, 409, 'transfer_mismatch', `on-chain transfer did not match: ${e.message}`);
+ return error(res, 500, 'confirm_failed', e.message);
}
- const intentId = `sp_${pur.id}`;
- const updated = await sql`
- UPDATE skill_purchases
- SET status = 'confirmed', tx_signature = ${txSig}, confirmed_at = now()
- WHERE id = ${pur.id} AND status = 'pending'
- RETURNING id
- `;
- if (updated.length > 0) {
- await sql`
- INSERT INTO agent_payment_intents
- (id, payer_user_id, agent_id, currency_mint, amount, status, expires_at,
- cluster, tx_signature, paid_at, payload)
- VALUES
- (${intentId}, ${pur.user_id}, ${pur.agent_id}, ${pur.currency_mint},
- ${String(pur.amount)}, 'confirmed', now() + interval '30 days',
- 'mainnet', ${txSig}, now(),
- ${JSON.stringify({ kind: 'skill_purchase', skill: pur.skill, reference })}::jsonb)
- ON CONFLICT (id) DO NOTHING
- `;
- await sql`
- INSERT INTO agent_revenue_events
- (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount,
- currency_mint, chain, payer_address)
- VALUES
- (${pur.agent_id}, ${intentId}, ${pur.skill},
- ${pur.amount}, 0, ${pur.amount},
- ${pur.currency_mint}, ${pur.chain}, ${recipientAddress})
- `;
+ if (result.status === 'pending') return json(res, 200, { data: { status: 'pending' } });
+ if (result.status === 'expired') return error(res, 410, 'expired', 'purchase expired');
+ if (result.status === 'mismatch') return error(res, 409, 'transfer_mismatch', result.message);
+ if (result.status === 'tipped') {
+ return error(res, 409, 'transfer_mismatch', result.message, {
+ status: 'tipped',
+ tipped_amount: result.tipped_amount,
+ tx_signature: result.tx_signature,
+ });
}
-
- return json(res, 200, { data: { status: 'confirmed', tx_signature: txSig } });
+ return json(res, 200, { data: { status: 'confirmed', tx_signature: result.tx_signature } });
});
diff --git a/public/pay/calls/index.html b/public/pay/calls/index.html
index e09988cc6..d88b4af07 100644
--- a/public/pay/calls/index.html
+++ b/public/pay/calls/index.html
@@ -268,11 +268,16 @@ function render(record) {
const url = record.args?.url;
document.title = `${record.tool} · paid call · three.ws`;
- // Update OG meta
+ // Update OG meta dynamically so social-card scrapers (when they re-render)
+ // pick up the right title/image. The OG image is rendered server-side by
+ // /api/x402-pay/og — that's the version social platforms see on first share.
document.querySelector('meta[property="og:title"]').content =
`three.ws · ${record.tool} (${amount} USDC) · x402 paid call`;
document.querySelector('meta[name="description"]').content =
`${record.tool}${record.argsSummary ? ' · ' + record.argsSummary : ''} — paid ${amount} USDC on Solana, settled on-chain. View the receipt + result.`;
+ const ogUrl = `${location.origin}/api/x402-pay/og?tx=${encodeURIComponent(tx)}`;
+ document.getElementById('ogImage').content = ogUrl;
+ document.getElementById('twImage').content = ogUrl;
main.innerHTML = `
<div class="hero">
diff --git a/public/pay/index.html b/public/pay/index.html
index 2558da068..94f59019d 100644
--- a/public/pay/index.html
+++ b/public/pay/index.html
@@ -9,7 +9,11 @@
<meta property="og:description" content="Live x402 demo — agent pays $0.001 USDC on Solana per MCP tool call. Settled on-chain, rendered live." />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://three.ws/pay" />
+<meta property="og:image" content="https://three.ws/api/x402-pay/og" />
+<meta property="og:image:width" content="1200" />
+<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
+<meta name="twitter:image" content="https://three.ws/api/x402-pay/og" />
<meta name="theme-color" content="#0a0b10" />
<link rel="preconnect" href="https://api.mainnet-beta.solana.com" />
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
diff --git a/public/studio/studio.js b/public/studio/studio.js
index fdde82c6d..9e5e2d90e 100644
--- a/public/studio/studio.js
+++ b/public/studio/studio.js
@@ -159,24 +159,6 @@ if (preModel) state.preselectedModel = preModel;
wireForm();
wireButtons();
- window.addEventListener('pump-launch-open', (e) => {
- const detail = e.detail || {};
- if (!state.avatarId || state.avatarId === DEMO_AVATAR.id) {
- toast('Please select your own avatar before launching a token.');
- return;
- }
- const avatar = state.avatars.find((a) => a.id === state.avatarId);
- if (!avatar) {
- toast('Avatar not loaded yet — try again in a moment.');
- return;
- }
- // state.avatarId is an avatars.id, not an agent_identities.id.
- // Pass the linked agent_id when known (from /api/avatars lateral join);
- // otherwise pass avatar_id and the backend will resolve-or-create.
- const identity = { name: detail.formData?.name || avatar.name, ...avatar };
- openPumpLaunchWizard(identity, avatar.agent_id || null, avatar.id, detail.formData);
- });
-
await loadAvatars();
if (editId) await loadForEdit(editId);
@@ -421,6 +403,7 @@ function selectAvatar(id) {
renderAvatarList();
updatePreview(true);
captureBtn.disabled = false;
+ launchPanel?.avatarChanged();
}
function selectByModelUrl(url) {
@@ -532,7 +515,10 @@ function wireButtons() {
const actionRow = $('.action-row');
const formError = $('#form-error');
- mountLaunchPanel(panelLaunch);
+ launchPanel = mountLaunchPanel(panelLaunch, {
+ getAvatar: () => state.avatars.find((a) => a.id === state.avatarId) || null,
+ getUser: () => state.user,
+ });
function switchTab(active) {
const toBrand = active === 'brand';
diff --git a/scripts/dev-x402-pay-server.mjs b/scripts/dev-x402-pay-server.mjs
index 9d2a611a9..336d6312b 100644
--- a/scripts/dev-x402-pay-server.mjs
+++ b/scripts/dev-x402-pay-server.mjs
@@ -13,6 +13,7 @@ import { createServer } from 'node:http';
import { config as dotenv } from 'dotenv';
dotenv({ path: new URL('../.env', import.meta.url) });
const { default: handler } = await import('../api/x402-pay.js');
+const { default: ogHandler } = await import('../api/x402-pay/og.js');
const PORT = Number(process.env.PORT || 3032);
const UPSTREAM = process.env.UPSTREAM || 'https://three.ws';
@@ -38,6 +39,15 @@ async function passthrough(req, res) {
const server = createServer(async (req, res) => {
const path = req.url.split('?')[0];
+ if (path === '/api/x402-pay/og') {
+ try { return await ogHandler(req, res); }
+ catch (err) {
+ console.error('[x402-pay/og] handler error:', err);
+ res.statusCode = 500;
+ res.end('og handler error');
+ }
+ return;
+ }
if (path === '/api/x402-pay' || path === '/api/x402-pay/') {
try { return await handler(req, res); }
catch (err) {
diff --git a/src/marketplace.js b/src/marketplace.js
index e6a494394..b7f279498 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -191,6 +191,18 @@ async function loadList(reset = false) {
}
}
+// Mirrors server-side NAME_AUTONAMED_RE in api/explore.js. Client-side filter
+// is defense-in-depth: until the server filter ships, the marketplace still
+// looks curated by hiding obvious junk locally.
+const AVATAR_AUTONAMED_RE =
+ /^(Avatar #[0-9a-f]{6}|Avatar \d+\/\d+\/\d{4}.*|mo[a-z0-9]{4,}|draft-[a-z0-9]+|[a-f0-9-]{30,}|new_project_\d+|TEST|test|Untitled.*)$/i;
+
+function isAutoNamedAvatar(name) {
+ const n = String(name || '').trim();
+ if (!n) return true;
+ return AVATAR_AUTONAMED_RE.test(n);
+}
+
async function loadPublicAvatars() {
try {
const url = new URL(`${API}/explore`, location.origin);
@@ -201,7 +213,9 @@ async function loadPublicAvatars() {
const r = await fetch(url);
if (!r.ok) return;
const j = await r.json();
- const avatars = (j?.items || []).filter((it) => it.kind === 'avatar' && it.glbUrl);
+ const avatars = (j?.items || []).filter(
+ (it) => it.kind === 'avatar' && it.glbUrl && !isAutoNamedAvatar(it.name),
+ );
state.publicAvatars = avatars;
state.publicAvatarsLoaded = true;
state.stats = j?.totals || state.stats;
@@ -228,13 +242,12 @@ async function loadFeatured() {
(it) =>
it.kind === 'avatar' &&
it.glbUrl &&
- it.name &&
- !/^Avatar #|^TEST$|^test$/i.test(it.name.trim()) &&
- it.name.trim().length > 1,
+ !isAutoNamedAvatar(it.name) &&
+ String(it.name).trim().length > 1,
);
state.featured = named.slice(0, 3);
if (!state.featured.length) {
- // Fall back to any 3 named avatars to keep hero populated.
+ // Fall back to any 3 avatars with a GLB so the hero never shows blank.
state.featured = (j?.items || [])
.filter((it) => it.kind === 'avatar' && it.glbUrl)
.slice(0, 3);
diff --git a/src/pump/pump-modals.js b/src/pump/pump-modals.js
index 47929f54a..0039a26e7 100644
--- a/src/pump/pump-modals.js
+++ b/src/pump/pump-modals.js
@@ -386,7 +386,7 @@ function openLaunch({ identity, agentId, avatarId, formData }) {
const { inner, close } = openModal();
let step = 1;
- async function buildMetadata(name, symbol) {
+ async function buildMetadata(name, symbol, description) {
let imageDataUrl = null;
if (formData?.image instanceof File) {
imageDataUrl = await new Promise((resolve) => {
@@ -403,14 +403,14 @@ function openLaunch({ identity, agentId, avatarId, formData }) {
body: JSON.stringify({
name,
symbol,
- description: formData?.description || identity?.description || '',
+ description: description || formData?.description || identity?.description || '',
...(avatarId ? { avatar_id: avatarId } : {}),
...(agentId ? { agent_id: agentId } : {}),
...(imageDataUrl ? { image_data_url: imageDataUrl } : {}),
}),
});
if (!resp.ok) throw new Error(`Metadata build failed: ${resp.status}`);
- return resp.json(); // { metadata_url, image_url }
+ return resp.json();
}
function esc(s) {
@@ -519,14 +519,17 @@ function openLaunch({ identity, agentId, avatarId, formData }) {
}
const nextBtn = inner.querySelector('#pmodal-launch-next');
// Rebuild metadata if name/symbol changed or we have no URI yet
- const nameChanged = inner._formCache?.name !== name || inner._formCache?.symbol !== symbol;
+ const fieldsChanged =
+ inner._formCache?.name !== name ||
+ inner._formCache?.symbol !== symbol ||
+ inner._formCache?.desc !== desc;
inner._formCache = { ...(inner._formCache || {}), name, symbol, desc };
- if (nameChanged) inner._formCache.uri = null;
+ if (fieldsChanged) inner._formCache.uri = null;
if (!inner._formCache.uri) {
nextBtn.disabled = true;
nextBtn.textContent = 'Building metadata…';
try {
- const data = await buildMetadata(name, symbol);
+ const data = await buildMetadata(name, symbol, desc);
inner._formCache.uri = data.metadata_url;
} catch (e) {
errEl.textContent = `Metadata failed: ${e.message}`;
diff --git a/src/runtime/index.js b/src/runtime/index.js
index 74f85e97d..7d101b704 100644
--- a/src/runtime/index.js
+++ b/src/runtime/index.js
@@ -5,6 +5,10 @@ import { createProvider } from './providers.js';
import { createTTS, createSTT } from './speech.js';
import { BUILTIN_TOOLS, BUILTIN_HANDLERS, STAGE_TOOLS } from './tools.js';
import { protocol } from '../agent-protocol.js';
+import { PaymentRequiredError, alwaysAllow } from './skill-access.js';
+
+export { PaymentRequiredError, alwaysAllow } from './skill-access.js';
+export { fromAgentDetail as skillAccessFromAgentDetail, remoteCheck as skillAccessRemote } from './skill-access.js';
const MAX_TOOL_ITERATIONS = 8;
@@ -18,6 +22,7 @@ export class Runtime extends EventTarget {
voiceConfig = {},
stage = null,
agentId = null,
+ skillAccess = null,
} = {}) {
super();
this.manifest = manifest || {};
@@ -26,6 +31,7 @@ export class Runtime extends EventTarget {
this.skills = skills;
this.stage = stage;
this.agentId = agentId;
+ this.skillAccess = skillAccess || alwaysAllow();
this.provider = createProvider({
...this.manifest.brain,
@@ -160,7 +166,25 @@ export class Runtime extends EventTarget {
try {
output = await this._dispatchTool(call);
} catch (err) {
- output = { error: err.message || String(err) };
+ if (err instanceof PaymentRequiredError) {
+ // Surface payment requirements as a structured event so the host
+ // page can pop the purchase modal. Feed a 402-style result back
+ // to the LLM so it can react gracefully (or, for autonomous
+ // agents, trigger its own purchase via skillAccess.autoPay).
+ this.dispatchEvent(
+ new CustomEvent('skill:payment-required', { detail: err.payload }),
+ );
+ output = {
+ error: 'payment_required',
+ skill: err.payload.skill,
+ price: err.payload.price,
+ message:
+ err.payload.message ||
+ `Skill '${err.payload.skill}' requires a purchase before it can be used.`,
+ };
+ } else {
+ output = { error: err.message || String(err) };
+ }
isError = true;
}
this.dispatchEvent(
@@ -207,7 +231,15 @@ export class Runtime extends EventTarget {
// Skill-provided tools first (they can shadow built-ins intentionally)
const skill = this.skills?.findSkillForTool(call.name);
- if (skill) return skill.invoke(call.name, call.input, ctx);
+ if (skill) {
+ // Paid-skill gate: ask the access checker before invoking. Built-in
+ // and stage tools never go through the gate — only skill-provided ones.
+ const access = await this.skillAccess(call.name);
+ if (!access?.allowed) {
+ throw new PaymentRequiredError({ skill: call.name, ...access });
+ }
+ return skill.invoke(call.name, call.input, ctx);
+ }
// Built-in
const handler = BUILTIN_HANDLERS[call.name];
diff --git a/src/runtime/skill-access.js b/src/runtime/skill-access.js
new file mode 100644
index 000000000..eac80c4ac
--- /dev/null
+++ b/src/runtime/skill-access.js
@@ -0,0 +1,92 @@
+// Skill-access gate primitives for the agent runtime.
+//
+// The Runtime calls `skillAccess(toolName)` before invoking any skill tool.
+// If the call returns `{ allowed: false, ...paymentInfo }`, the runtime
+// emits a `skill:payment-required` event and feeds a structured 402 result
+// back to the LLM so it can react (ask the user to purchase, or — once track 2
+// is wired — let an autonomous agent invoke its own purchase flow).
+//
+// Built-in tools (BUILTIN_HANDLERS) and stage tools are always allowed; the
+// gate only applies to skill-provided tools.
+
+export class PaymentRequiredError extends Error {
+ /**
+ * @param {{ skill: string, price?: object, reference?: string, message?: string, recipient?: string }} payload
+ */
+ constructor(payload) {
+ super(payload?.message || `payment required to use skill: ${payload?.skill}`);
+ this.name = 'PaymentRequiredError';
+ this.code = 'payment_required';
+ this.payload = payload || {};
+ }
+}
+
+/**
+ * Default no-op gate: every skill is allowed. Used when the runtime is not
+ * wired to a marketplace context (local dev, embedded agent without monetization).
+ */
+export function alwaysAllow() {
+ return async () => ({ allowed: true });
+}
+
+/**
+ * Build a `skillAccess` checker from a marketplace agent detail payload.
+ *
+ * @param {{
+ * skill_prices?: Record<string, { amount: string|number, currency_mint: string, chain?: string }>,
+ * purchased_skills?: string[],
+ * }} agent
+ * @returns {(toolName: string) => Promise<{allowed: boolean, price?: object, message?: string}>}
+ */
+export function fromAgentDetail(agent) {
+ const prices = agent?.skill_prices || {};
+ const purchased = new Set(agent?.purchased_skills || []);
+
+ return async (toolName) => {
+ const price = prices[toolName];
+ if (!price) return { allowed: true }; // free skill
+
+ if (purchased.has(toolName)) return { allowed: true };
+
+ return {
+ allowed: false,
+ skill: toolName,
+ price: {
+ amount: String(price.amount),
+ currency_mint: price.currency_mint,
+ chain: price.chain || 'solana',
+ },
+ message: `This skill requires a purchase: ${toolName}`,
+ };
+ };
+}
+
+/**
+ * Build a `skillAccess` checker that re-fetches purchase status against the
+ * server on every check. More authoritative than the snapshot built from
+ * agent detail, but adds a network round-trip per call.
+ *
+ * @param {{ agentId: string, fetchImpl?: typeof fetch }} opts
+ */
+export function remoteCheck({ agentId, fetchImpl = fetch }) {
+ return async (toolName) => {
+ try {
+ const url = `/api/marketplace/check-skill-access?agent_id=${encodeURIComponent(agentId)}&skill=${encodeURIComponent(toolName)}`;
+ const r = await fetchImpl(url, { credentials: 'include' });
+ if (!r.ok) {
+ // Anonymous or skill not for sale → treat as allowed (free).
+ return { allowed: true };
+ }
+ const j = await r.json();
+ if (j?.has_access) return { allowed: true };
+ return {
+ allowed: false,
+ skill: toolName,
+ message: `This skill requires a purchase: ${toolName}`,
+ };
+ } catch {
+ // Network error: fail open so transient issues don't block use.
+ return { allowed: true };
+ }
+ };
+}
diff --git a/tests/src/eth-vanity-derivation.test.js b/tests/src/eth-vanity-derivation.test.js
new file mode 100644
index 000000000..c3a7fefc8
--- /dev/null
+++ b/tests/src/eth-vanity-derivation.test.js
@@ -0,0 +1,68 @@
+import { describe, it, expect } from 'vitest';
+import { keccak_256 } from '@noble/hashes/sha3';
+import { getCreate2Address } from 'ethers';
+import { eip55Checksum } from '../../src/eth/vanity/validation.js';
+
+/**
+ * The grinder worker's derivation must equal ethers.getCreate2Address.
+ * We re-implement the worker's hot loop in JS here (without spawning a
+ * Web Worker) and assert byte-for-byte parity over many random inputs.
+ */
+
+function hexToBytes(hex) {
+ const h = hex.startsWith('0x') ? hex.slice(2) : hex;
+ const out = new Uint8Array(h.length / 2);
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(h.substring(i * 2, i * 2 + 2), 16);
+ return out;
+}
+function bytesToHex(b) {
+ let s = ''; for (let i = 0; i < b.length; i++) s += b[i].toString(16).padStart(2, '0');
+ return s;
+}
+function deriveCreate2(deployer, salt, initCodeHash) {
+ const buf = new Uint8Array(85);
+ buf[0] = 0xff;
+ buf.set(hexToBytes(deployer), 1);
+ buf.set(hexToBytes(salt), 21);
+ buf.set(hexToBytes(initCodeHash), 53);
+ return '0x' + bytesToHex(keccak_256(buf).subarray(12));
+}
+
+function randomHex(byteLen) {
+ const b = new Uint8Array(byteLen);
+ crypto.getRandomValues(b);
+ return '0x' + bytesToHex(b);
+}
+
+describe('eth vanity · CREATE2 derivation parity with ethers', () => {
+ it('matches ethers.getCreate2Address across 25 random inputs', () => {
+ for (let i = 0; i < 25; i++) {
+ const dep = randomHex(20);
+ const salt = randomHex(32);
+ const ich = randomHex(32);
+ const ours = deriveCreate2(dep, salt, ich);
+ const eth = getCreate2Address(dep, salt, ich).toLowerCase();
+ expect(ours).toBe(eth);
+ }
+ });
+
+ it('produces a known fixture', () => {
+ // Arachnid proxy + zero salt + zero initCodeHash.
+ const dep = '0x4e59b44847b379578588920ca78fbf26c0b4956c';
+ const salt = '0x' + '00'.repeat(32);
+ const ich = '0x' + '00'.repeat(32);
+ const ours = deriveCreate2(dep, salt, ich);
+ const eth = getCreate2Address(dep, salt, ich).toLowerCase();
+ expect(ours).toBe(eth);
+ });
+
+ it('eip55Checksum of a derived address matches ethers.getCreate2Address (mixed case)', () => {
+ const dep = randomHex(20);
+ const salt = randomHex(32);
+ const ich = randomHex(32);
+ const lower = deriveCreate2(dep, salt, ich).slice(2);
+ const ours = '0x' + eip55Checksum(lower);
+ const eth = getCreate2Address(dep, salt, ich); // ethers returns checksummed
+ expect(ours).toBe(eth);
+ });
+});
diff --git a/tests/src/eth-vanity-server-verify.test.js b/tests/src/eth-vanity-server-verify.test.js
new file mode 100644
index 000000000..d9ce030dc
--- /dev/null
+++ b/tests/src/eth-vanity-server-verify.test.js
@@ -0,0 +1,38 @@
+import { describe, it, expect } from 'vitest';
+import { __test__ } from '../../api/agents/eth-vanity.js';
+import { keccak_256 } from '@noble/hashes/sha3';
+import { getCreate2Address } from 'ethers';
+
+const { _verifyCreate2 } = __test__;
+
+function bytesToHex(b) { let s=''; for (const x of b) s += x.toString(16).padStart(2,'0'); return s; }
+
+describe('eth vanity · server-side _verifyCreate2', () => {
+ it('accepts a correct (deployer, salt, initCodeHash, address)', () => {
+ const dep = '0x4e59b44847b379578588920ca78fbf26c0b4956c';
+ const salt = '0x' + '01'.repeat(32);
+ const ich = '0x' + bytesToHex(keccak_256(new Uint8Array([1,2,3])));
+ const expected = getCreate2Address(dep, salt, ich).toLowerCase();
+ expect(_verifyCreate2(dep, salt, ich, expected)).toBe(true);
+ });
+
+ it('rejects an incorrect address', () => {
+ const dep = '0x4e59b44847b379578588920ca78fbf26c0b4956c';
+ const salt = '0x' + '01'.repeat(32);
+ const ich = '0x' + '02'.repeat(32);
+ // Tamper one nibble
+ const correct = getCreate2Address(dep, salt, ich).toLowerCase();
+ const tampered = '0x' + (correct[2] === '0' ? 'f' : '0') + correct.slice(3);
+ expect(_verifyCreate2(dep, salt, ich, tampered)).toBe(false);
+ });
+
+ it('is case-insensitive on the predicted address', () => {
+ const dep = '0x4e59b44847b379578588920ca78fbf26c0b4956c';
+ const salt = '0x' + 'ab'.repeat(32);
+ const ich = '0x' + 'cd'.repeat(32);
+ const expected = getCreate2Address(dep, salt, ich); // checksummed mixed-case
+ expect(_verifyCreate2(dep, salt, ich, expected)).toBe(true);
+ expect(_verifyCreate2(dep, salt, ich, expected.toLowerCase())).toBe(true);
+ expect(_verifyCreate2(dep, salt, ich, expected.toUpperCase())).toBe(true);
+ });
+});
diff --git a/tests/src/eth-vanity-wordlist.test.js b/tests/src/eth-vanity-wordlist.test.js
new file mode 100644
index 000000000..c27a8fa6e
--- /dev/null
+++ b/tests/src/eth-vanity-wordlist.test.js
@@ -0,0 +1,50 @@
+import { describe, it, expect } from 'vitest';
+import { leetToHex, suggestPrefixFromName, PRESET_CHIPS } from '../../src/eth/vanity/wordlist.js';
+
+describe('eth vanity · wordlist', () => {
+ it('all preset chips are valid hex', () => {
+ for (const w of PRESET_CHIPS) {
+ expect(w).toMatch(/^[0-9a-fA-F]+$/);
+ }
+ });
+});
+
+describe('eth vanity · leetToHex', () => {
+ it('passes through pure hex unchanged', () => {
+ expect(leetToHex('beef')).toBe('beef');
+ expect(leetToHex('CAFE')).toBe('CAFE');
+ expect(leetToHex('1337')).toBe('1337');
+ });
+
+ it('substitutes l/i/o/s/t/z/g/y to digits', () => {
+ expect(leetToHex('alice')).toBe('a11ce');
+ expect(leetToHex('lost')).toBe('1057');
+ expect(leetToHex('ozzy')).toBe('0221');
+ });
+
+ it('preserves case so EIP-55 mode kicks in', () => {
+ // 'Alice' has uppercase A → should keep that case
+ expect(leetToHex('Alice')).toBe('A11ce');
+ });
+
+ it('returns null for unmappable text', () => {
+ // "wrx" — w/r/x have no leet mapping
+ expect(leetToHex('wrx')).toBe(null);
+ });
+
+ it('strips non-alphanumerics before mapping', () => {
+ expect(leetToHex('be-ef')).toBe('beef');
+ expect(leetToHex(' cafe ')).toBe('cafe');
+ });
+});
+
+describe('eth vanity · suggestPrefixFromName', () => {
+ it('returns truncated leet for a workable name', () => {
+ expect(suggestPrefixFromName('Alice')).toBe('A11ce');
+ expect(suggestPrefixFromName('decaf')).toBe('decaf');
+ });
+ it('returns null for too-short or unmappable names', () => {
+ expect(suggestPrefixFromName('')).toBe(null);
+ expect(suggestPrefixFromName('wx')).toBe(null);
+ });
+});