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.

7.5 KB
Raw Blame
#!/usr/bin/env node
// Builds the HookForge hook catalog section of docs/uniswap-v4-hooks.md from a
// pinned snapshot of github.com/nirholas/hookforge `packages/registry`.
//
//   node scripts/gen-hookforge-catalog.mjs            regenerate snapshot + doc section
//   node scripts/gen-hookforge-catalog.mjs --check    verify, offline: snapshot count,
//                                                     doc count, and doc text all agree
//   node scripts/gen-hookforge-catalog.mjs --from DIR read packages/registry from a local
//                                                     checkout instead of fetching
//
// The snapshot is pinned by commit SHA (HOOKFORGE_SHA). To move to a newer registry,
// bump the SHA and rerun; the format of index.json and hooks/<slug>.json is validated
// below so a changed shape fails loudly instead of rendering a wrong catalog.

import { readFile, writeFile } from 'node:fs/promises';
import { resolve, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { formatMask, maskFromPermissions } from './lib/v4-hook-flags.mjs';

export const HOOKFORGE_SHA = '4f3102d3ec6a004adb98f07241f4fa994711fc97';
const RAW = `https://raw.githubusercontent.com/nirholas/hookforge/${HOOKFORGE_SHA}/packages/registry`;
const ROOT = resolve(fileURLToPath(import.meta.url), '../..');
const SNAPSHOT = join(ROOT, 'data/hookforge-registry.json');
const DOC = join(ROOT, 'docs/uniswap-v4-hooks.md');
const BEGIN = '<!-- hookforge-catalog:begin -->';
const END = '<!-- hookforge-catalog:end -->';

// Hooks that map to three.ws agent concepts, with the Solana counterpart that already
// exists in this repo where there is one. Solana leads; the hook is the EVM leg.
export const AGENT_NATIVE = {
	'agent-budget': {
		concept: 'Agent spend limits: a budget the principal signs and the venue enforces.',
		solana: { label: 'Wallet policy and custody controls', href: 'custody.md' },
	},
	'reputation-fee': {
		concept: 'Reputation-priced flow: the agent registers its own router, the pool prices it by standing.',
		solana: { label: 'Solana reputation', href: 'solana-reputation.md' },
		local: { label: 'AgentTierHook design note', href: '#agenttierhook-and-reputation-fee' },
	},
	'x402-gate': {
		concept: 'Pay-to-trade: access to a pool gated by an x402-style payment.',
		solana: { label: 'Autonomous x402 loop', href: 'autonomous-x402.md' },
	},
	'anti-snipe-ramp': {
		concept: 'Launch protection: a punitive opening fee that decays, paid to LPs.',
		solana: { label: 'Native launchpad fee scheduler', href: 'native-launchpad.md' },
	},
};

function get(obj, key, hint) {
	if (obj[key] === undefined) throw new Error(`registry shape changed: ${hint} has no "${key}"`);
	return obj[key];
}

async function loadRegistry(fromDir) {
	const read = async (rel) =>
		fromDir
			? JSON.parse(await readFile(join(fromDir, rel), 'utf8'))
			: await fetch(`${RAW}/${rel}`, { signal: AbortSignal.timeout(20000) }).then((r) => {
					if (!r.ok) throw new Error(`${rel}: HTTP ${r.status}`);
					return r.json();
				});
	const index = await read('index.json');
	const chains = await read('chains.json');
	const entries = get(index, 'hooks', 'index.json');
	if (entries.length !== get(index, 'count', 'index.json')) {
		throw new Error(`index.json count ${index.count} != ${entries.length} entries`);
	}
	const hooks = [];
	for (const entry of entries) {
		const manifest = await read(`hooks/${entry.slug}.json`);
		hooks.push({
			slug: entry.slug,
			name: entry.name,
			contract: get(manifest, 'contract', entry.slug),
			family: entry.family,
			summary: entry.summary,
			tags: entry.tags,
			docs: entry.docs,
			repo: entry.repo ?? null,
			mask: formatMask(maskFromPermissions(get(manifest, 'permissions', entry.slug))),
			recommendedChains: manifest.recommendedChains ?? [],
			deployments: entry.deployments,
		});
	}
	return {
		source: 'https://github.com/nirholas/hookforge',
		commit: HOOKFORGE_SHA,
		registryGenerated: index.generated,
		count: hooks.length,
		poolManagers: Object.fromEntries(chains.chains.map((c) => [c.chainId, c.poolManager])),
		hooks,
	};
}

const cell = (s) => String(s).replace(/\|/g, '\\|');

export function renderCatalog(snapshot) {
	const families = new Map();
	for (const hook of snapshot.hooks) {
		if (!families.has(hook.family)) families.set(hook.family, []);
		families.get(hook.family).push(hook);
	}
	const deployed = snapshot.hooks.filter((h) => h.deployments.length).length;
	const lines = [
		BEGIN,
		`<!-- Generated by scripts/gen-hookforge-catalog.mjs from data/hookforge-registry.json. Edit the generator, not this block. -->`,
		'',
		`**${snapshot.count} hooks**, ${deployed} with mined CREATE2 addresses, from the HookForge registry`,
		`([\`nirholas/hookforge\`](${snapshot.source}) at commit \`${snapshot.commit.slice(0, 10)}\`,`,
		`registry generated ${snapshot.registryGenerated}). The \`mask\` column is the 14-bit permission mask that a`,
		`deployed address must carry in its low bits, which the census script decodes. Hooks that map to three.ws`,
		`agent concepts are marked **agent-native**; the Solana counterpart comes first where one exists.`,
		'',
		'### Maps to three.ws agent concepts',
		'',
		'| Hook | Concept | Solana counterpart |',
		'|---|---|---|',
	];
	for (const [slug, info] of Object.entries(AGENT_NATIVE)) {
		const hook = snapshot.hooks.find((h) => h.slug === slug);
		if (!hook) throw new Error(`AGENT_NATIVE names "${slug}", which is not in the registry`);
		const links = [`[${info.solana.label}](${info.solana.href})`];
		if (info.local) links.push(`[${info.local.label}](${info.local.href})`);
		lines.push(`| [\`${hook.name}\`](${hook.docs}) | ${cell(info.concept)} | ${links.join('; ')} |`);
	}
	for (const [family, hooks] of families) {
		lines.push('', `### ${family} (${hooks.length})`, '', '| Hook | Mask | What it does |', '|---|---|---|');
		for (const h of hooks) {
			const tag = AGENT_NATIVE[h.slug] ? ' **agent-native**' : '';
			lines.push(`| [\`${h.name}\`](${h.docs})${tag} | \`${h.mask}\` | ${cell(h.summary)} |`);
		}
	}
	lines.push('', END);
	return lines.join('\n');
}

function spliceDoc(doc, block) {
	const start = doc.indexOf(BEGIN);
	const end = doc.indexOf(END);
	if (start === -1 || end === -1) throw new Error('catalog markers missing from docs/uniswap-v4-hooks.md');
	return doc.slice(0, start) + block + doc.slice(end + END.length);
}

export function countCatalogRows(doc) {
	const section = doc.slice(doc.indexOf(BEGIN), doc.indexOf(END));
	const afterAgentNative = section.slice(section.indexOf('### Maps to'));
	const familyTables = afterAgentNative.slice(afterAgentNative.indexOf('\n### ', 1));
	return (familyTables.match(/^\| \[`/gm) || []).length;
}

async function main() {
	const args = process.argv.slice(2);
	const doc = await readFile(DOC, 'utf8');
	if (args.includes('--check')) {
		const snapshot = JSON.parse(await readFile(SNAPSHOT, 'utf8'));
		const rows = countCatalogRows(doc);
		const fresh = spliceDoc(doc, renderCatalog(snapshot)) === doc;
		const ok = snapshot.count === snapshot.hooks.length && snapshot.count === rows && fresh;
		console.log(
			JSON.stringify({ registryCount: snapshot.count, snapshotHooks: snapshot.hooks.length, docRows: rows, docUpToDate: fresh }),
		);
		process.exit(ok ? 0 : 1);
	}
	const fromIdx = args.indexOf('--from');
	const snapshot = await loadRegistry(fromIdx === -1 ? null : resolve(args[fromIdx + 1]));
	await writeFile(SNAPSHOT, JSON.stringify(snapshot, null, '\t') + '\n');
	await writeFile(DOC, spliceDoc(doc, renderCatalog(snapshot)));
	console.log(`wrote ${snapshot.count} hooks at ${snapshot.commit.slice(0, 10)}`);
}

if (process.argv[1] === fileURLToPath(import.meta.url)) await main();