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(skill-import): generate skill bundles from Anchor IDLs with a runtime decoder
nirholasb00ee311a912
diff --git a/packages/skill-import/src/anchor-idl.js b/packages/skill-import/src/anchor-idl.jsnew file mode 100644index 000000000..d6135d958--- /dev/null+++ b/packages/skill-import/src/anchor-idl.js@@ -0,0 +1,421 @@+// Anchor IDL -> skill bundle (specs/SKILL_SPEC.md), the Solana counterpart of+// the OpenAPI importer. For one program IDL it generates:+//+// read_<account> decode an account of that type by address (read-only)+// preview_<ix> build the unsigned instruction: accounts, data, summary,+// risk. Never signs.+// send_<ix> the same payload plus status "confirmation_required",+// for the host's confirm-gated wallet flow. Marked+// destructiveHint; the skill never holds or requests a key.+//+// The handlers are self-contained (IDL embedded as a JSON literal, codec from+// anchor-runtime.js appended as text) because the skill sandbox allows no+// imports. Every string taken from the IDL lands in JSON literals or in the+// SKILL.md prose, never in executable positions.++import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { inflateSync } from 'node:zlib';+import { PublicKey } from '@solana/web3.js';+import { assertValidBundle } from './validate.js';++export class AnchorIdlError extends Error {}++const RUNTIME_SRC = readFileSync(new URL('./anchor-runtime.js', import.meta.url), 'utf8');+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const snake = (s) =>+ String(s)+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')+ .replace(/[^A-Za-z0-9]+/g, '_')+ .replace(/^_+|_+$/g, '')+ .toLowerCase();++const sha8 = (text) => [...createHash('sha256').update(text).digest().subarray(0, 8)];++function normalizeType(t) {+ if (t === 'publicKey') return 'pubkey';+ if (!t || typeof t !== 'object') return t;+ if (t.vec) return { vec: normalizeType(t.vec) };+ if (t.option) return { option: normalizeType(t.option) };+ if (t.coption) return { coption: normalizeType(t.coption) };+ if (t.array) return { array: [normalizeType(t.array[0]), t.array[1]] };+ if (t.defined) return { defined: { name: typeof t.defined === 'string' ? t.defined : t.defined.name } };+ return t;+}++function normalizeFields(fields) {+ if (!fields) return fields;+ return fields.map((f) => (f && typeof f === 'object' && f.name ? { ...f, type: normalizeType(f.type) } : normalizeType(f)));+}++function normalizeTypeDef(def) {+ const type = { ...def.type };+ if (type.fields) type.fields = normalizeFields(type.fields);+ if (type.variants) type.variants = type.variants.map((v) => ({ ...v, fields: normalizeFields(v.fields) }));+ return { ...def, type };+}++function normalizeAccountItems(items) {+ return items.map((a) => {+ if (a.accounts) return { ...a, accounts: normalizeAccountItems(a.accounts) };+ const out = { name: snake(a.name) };+ if (a.writable ?? a.isMut) out.writable = true;+ if (a.signer ?? a.isSigner) out.signer = true;+ if (a.address) out.address = a.address;+ if (a.docs) out.docs = a.docs;+ return out;+ });+}++/**+ * Accepts the Anchor >=0.30 IDL shape (explicit discriminators, `address`) and+ * the legacy shape (isMut/isSigner, `metadata.address`, accounts that embed+ * their struct), and returns the 0.30 shape the generated runtime reads.+ */+export function normalizeIdl(raw, { programId } = {}) {+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.instructions)) {+ throw new AnchorIdlError('not an Anchor IDL: missing instructions array');+ }+ const address = raw.address || raw.metadata?.address || programId;+ if (!address || !BASE58_RE.test(address)) {+ throw new AnchorIdlError('IDL has no program address; pass program_id alongside idl_url');+ }+ if (programId && raw.address && raw.address !== programId) {+ throw new AnchorIdlError(`IDL address ${raw.address} does not match program_id ${programId}`);+ }+ const name = raw.metadata?.name || raw.name;+ if (!name) throw new AnchorIdlError('IDL has no program name');++ const legacy = !raw.instructions.every((i) => Array.isArray(i.discriminator));+ const types = (raw.types || []).map(normalizeTypeDef);+ const accounts = [];+ for (const a of raw.accounts || []) {+ if (a.type && !types.some((t) => t.name === a.name)) types.push(normalizeTypeDef({ name: a.name, type: a.type }));+ accounts.push({ name: a.name, discriminator: a.discriminator || sha8(`account:${a.name}`) });+ }++ return {+ address,+ metadata: {+ name: snake(name),+ version: raw.metadata?.version || raw.version || '0.1.0',+ description: raw.metadata?.description || raw.docs?.[0] || '',+ },+ instructions: raw.instructions.map((i) => ({+ name: snake(i.name),+ discriminator: i.discriminator || sha8(`global:${snake(i.name)}`),+ docs: i.docs || [],+ accounts: normalizeAccountItems(i.accounts || []),+ args: (i.args || []).map((a) => ({ name: a.name, type: normalizeType(a.type) })),+ })),+ accounts,+ types,+ legacy,+ };+}++function flatten(list, prefix = '') {+ return list.flatMap((a) => (a.accounts ? flatten(a.accounts, `${prefix}${a.name}.`) : [{ ...a, name: prefix + a.name }]));+}++const TOKEN_PROGRAMS = new Set([+ 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA',+ 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb',+]);+const AUTHORITY_IX = /(^|_)(set|update|change|transfer|propose|accept|renounce|revoke|grant)_(authority|admin|owner|minter|delegate|upgrade_authority|ownership|freeze|operator|manager)(_|$)|^(set|update)_.*(authority|admin|owner|minter)$/;+const MOVES_IX = /(^|_)(transfer|withdraw|deposit|pay|swap|stake|unstake|claim|redeem|mint|burn|buy|sell|send|fund|invoke|settle|refund|distribute)(_|$)/;+const CLOSE_IX = /(^|_)(close|burn|delete|destroy|revoke|reclaim)(_|$)/;++/**+ * Static risk read of one instruction from the IDL alone. IDLs do not carry+ * Anchor constraints (`close`, `has_one`), so this is name- and shape-based+ * and says so in the panel: a flag is a prompt to read the program, and the+ * absence of a flag is not an audit.+ */+export function analyzeInstructionRisk(ix) {+ const accounts = flatten(ix.accounts);+ const flags = [];+ const usesTokenProgram =+ accounts.some((a) => TOKEN_PROGRAMS.has(a.address)) || accounts.some((a) => /token_program/.test(a.name));+ if (usesTokenProgram || MOVES_IX.test(ix.name)) {+ flags.push({+ code: 'moves_tokens',+ severity: 'medium',+ label: usesTokenProgram ? 'invokes the token program (mints, burns or moves tokens)' : 'name suggests it moves value',+ });+ }+ if (accounts.some((a) => a.address === '11111111111111111111111111111111') && accounts.some((a) => a.signer && a.writable)) {+ flags.push({ code: 'spends_lamports', severity: 'medium', label: 'a writable signer pays through the system program (SOL leaves that wallet)' });+ }+ if (CLOSE_IX.test(ix.name) || accounts.some((a) => /(^|_)(close|rent_receiver|destination)(_|$)/.test(a.name))) {+ flags.push({ code: 'closes_accounts', severity: 'high', label: 'may close or invalidate accounts and release their lamports' });+ }+ const authorityArg = ix.args.some((a) => a.type === 'pubkey' && /(authority|admin|owner|minter|delegate|^new_)/.test(a.name));+ if (AUTHORITY_IX.test(ix.name) || authorityArg) {+ flags.push({ code: 'changes_authority', severity: 'high', label: 'can change who controls the program state or a privileged role' });+ }+ const level = flags.some((f) => f.severity === 'high') ? 'high' : flags.length ? 'medium' : 'low';+ return { level, flags };+}++const accountToolName = (name) => `read_${snake(name)}`;+const previewToolName = (name) => `preview_${name}`;+const sendToolName = (name) => `send_${name}`;++function pubkeySchema(description) {+ return { type: 'string', pattern: '^[1-9A-HJ-NP-Za-km-z]{32,44}$', description };+}++const CLUSTER_PROP = {+ type: 'string',+ enum: ['mainnet-beta', 'devnet'],+ description: 'Cluster to read from. Defaults to mainnet-beta.',+};++function argSchema(type) {+ if (typeof type === 'string') {+ if (type === 'bool') return { type: 'boolean' };+ if (type === 'string') return { type: 'string' };+ if (type === 'pubkey') return pubkeySchema('Base58 address');+ if (type === 'bytes') return { type: 'string', description: 'Hex string' };+ if (type === 'f32' || type === 'f64') return { type: 'number' };+ return { type: ['integer', 'string'], description: `${type} (use a string above 2^53)` };+ }+ if (type.vec) return { type: 'array', items: argSchema(type.vec) };+ if (type.option) return { ...argSchema(type.option), description: 'Optional; omit or null for none' };+ if (type.array) {+ return type.array[0] === 'u8'+ ? { type: 'string', description: `Hex string of ${type.array[1]} bytes` }+ : { type: 'array', items: argSchema(type.array[0]), minItems: type.array[1], maxItems: type.array[1] };+ }+ return { description: `${type.defined?.name || 'custom'} value, shaped as in the IDL` };+}++function instructionSchema(ix) {+ const accountProps = {};+ const accountRequired = [];+ for (const a of flatten(ix.accounts)) {+ if (a.address) continue;+ accountProps[a.name] = pubkeySchema(`${a.signer ? 'Signer. ' : ''}${a.writable ? 'Writable. ' : ''}${(a.docs || []).join(' ')}`.trim() || 'Account address');+ accountRequired.push(a.name);+ }+ const argProps = {};+ for (const a of ix.args) argProps[a.name] = argSchema(a.type);+ const properties = {+ accounts: { type: 'object', properties: accountProps, required: accountRequired, additionalProperties: false },+ args: { type: 'object', properties: argProps, required: ix.args.map((a) => a.name), additionalProperties: false },+ };+ return { type: 'object', properties, required: ['accounts', 'args'] };+}++function describe(ix, risk) {+ const doc = ix.docs.join(' ').trim();+ const flagText = risk.flags.length ? ` Risk ${risk.level}: ${risk.flags.map((f) => f.label).join('; ')}.` : '';+ return { doc, flagText };+}++export function generateAnchorTools(idl) {+ const risks = Object.fromEntries(idl.instructions.map((ix) => [ix.name, analyzeInstructionRisk(ix)]));+ const tools = [];+ for (const acct of idl.accounts) {+ tools.push({+ name: accountToolName(acct.name),+ description: `Fetch and decode a ${acct.name} account of program ${idl.address} by address.`,+ input_schema: {+ type: 'object',+ properties: { address: pubkeySchema(`Address of the ${acct.name} account`), cluster: CLUSTER_PROP },+ required: ['address'],+ },+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },+ });+ }+ for (const ix of idl.instructions) {+ const { doc, flagText } = describe(ix, risks[ix.name]);+ tools.push({+ name: previewToolName(ix.name),+ description: `Preview ${ix.name} without signing: returns the accounts, instruction data, a plain summary and a risk read. ${doc}${flagText}`.trim(),+ input_schema: instructionSchema(ix),+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ });+ tools.push({+ name: sendToolName(ix.name),+ description: `Prepare ${ix.name} for the wallet owner's confirmation. Returns the unsigned instruction and a confirmation summary; it signs and sends nothing. ${doc}${flagText}`.trim(),+ input_schema: instructionSchema(ix),+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },+ });+ }+ return { tools, risks };+}++export function generateAnchorHandlers(idl, risks) {+ const exported = [+ ...idl.accounts.map(+ (a) => `export async function ${accountToolName(a.name)}(args, ctx) {\n\treturn readAccountTool(${JSON.stringify(a.name)}, args, ctx);\n}`+ ),+ ...idl.instructions.flatMap((ix) => [+ `export async function ${previewToolName(ix.name)}(args) {\n\treturn previewTool(${JSON.stringify(ix.name)}, args);\n}`,+ `export async function ${sendToolName(ix.name)}(args) {\n\treturn sendTool(${JSON.stringify(ix.name)}, args);\n}`,+ ]),+ ].join('\n\n');++ const slim = {+ address: idl.address,+ instructions: idl.instructions.map(({ docs, ...rest }) => rest),+ accounts: idl.accounts,+ types: idl.types,+ };+ return `// Generated by @three-ws/skill-import from an Anchor IDL. Do not hand-edit: regenerate from the IDL instead.++const IDL = ${JSON.stringify(slim)};++const RISK = ${JSON.stringify(risks)};++${RUNTIME_SRC}+${exported}+`;+}++function riskPanel(idl, risks) {+ const rows = idl.instructions.map((ix) => {+ const r = risks[ix.name];+ return `| \`${ix.name}\` | ${r.level} | ${r.flags.map((f) => f.label).join('; ') || 'none detected'} |`;+ });+ return [+ '## Risk panel',+ '',+ 'Static read of the IDL: names, account shapes and well-known programs. Anchor constraints are not in an IDL, so a flag is a prompt to read the program and a clean row is not an audit.',+ '',+ '| Instruction | Risk | Flags |',+ '| --- | --- | --- |',+ ...rows,+ ].join('\n');+}++function generateAnchorSkillMd(manifest, idl, tools, risks) {+ const lines = [+ '---',+ `name: ${manifest.name}`,+ `description: ${JSON.stringify(manifest.description)}`,+ '---',+ '',+ `# ${manifest.name}`,+ '',+ manifest.description,+ '',+ `Program: \`${idl.address}\``,+ '',+ '## How to use',+ '',+ '- `read_*` tools fetch and decode an account by address.',+ '- `preview_*` tools build the instruction without signing. Always preview first and show the summary and risk to the user.',+ '- `send_*` tools return the unsigned instruction for the confirm-gated wallet flow. They never sign or send, and need the wallet owner\'s explicit yes.',+ '',+ '## Tools',+ '',+ ...tools.tools.map((t) => `- \`${t.name}\`${t.annotations.destructiveHint ? ' (destructive, needs confirmation)' : ''}`),+ '',+ riskPanel(idl, risks),+ '',+ ];+ return lines.join('\n');+}++/**+ * @param {object} rawIdl Anchor IDL (parsed JSON)+ * @param {{sourceUrl?: string, programId?: string}} opts+ */+export function generateAnchorBundle(rawIdl, { sourceUrl, programId } = {}) {+ const idl = normalizeIdl(rawIdl, { programId });+ if (!idl.instructions.length && !idl.accounts.length) throw new AnchorIdlError('IDL declares no instructions or accounts');++ const tools = generateAnchorTools(idl);+ const description = (idl.metadata.description || `Read accounts and prepare instructions for Solana program ${idl.address}.`).slice(0, 500);+ const manifest = {+ spec: 'skill/0.1',+ name: idl.metadata.name.replace(/_/g, '-').slice(0, 64),+ version: idl.metadata.version,+ description,+ author: 'imported',+ license: 'unknown',+ tags: ['imported', 'anchor', 'solana'],+ requires: { rig: ['any'], runtime: '>=0.1.0', tools: [], secrets: [] },+ dependencies: {},+ provides: {+ tools: tools.tools.map((t) => t.name),+ triggers: ['imported', idl.metadata.name],+ },+ source: { type: 'anchor-idl', url: sourceUrl || null, program_id: idl.address },+ risk: tools.risks,+ };+ const handlersSrc = generateAnchorHandlers(idl, tools.risks);+ const skillMd = generateAnchorSkillMd(manifest, idl, { tools: tools.tools }, tools.risks);+ const toolsJson = { tools: tools.tools };+ assertValidBundle(+ { manifest, skillMd, tools: toolsJson, handlersSrc },+ { allowAddresses: [idl.address, ...idl.instructions.flatMap((ix) => flatten(ix.accounts).map((a) => a.address).filter(Boolean))] }+ );+ return { manifest, skillMd, tools: toolsJson, handlersSrc, sourceUrl: sourceUrl || `solana:${idl.address}` };+}++/**+ * Fetch the IDL Anchor publishes on chain for a program: the account at+ * createWithSeed(base, "anchor:idl", program) holding a zlib-compressed JSON+ * document after a 44-byte header.+ *+ * @param {string} programId+ * @param {{rpc: (method: string, params: unknown[]) => Promise<any>}} opts+ */+export async function fetchOnchainIdl(programId, { rpc }) {+ if (!BASE58_RE.test(programId || '')) throw new AnchorIdlError('program_id must be a base58 address');+ const program = new PublicKey(programId);+ const [base] = PublicKey.findProgramAddressSync([], program);+ const idlAddress = await PublicKey.createWithSeed(base, 'anchor:idl', program);+ const result = await rpc('getAccountInfo', [idlAddress.toBase58(), { encoding: 'base64', commitment: 'confirmed' }]);+ if (!result?.value) {+ throw new AnchorIdlError(`no on-chain IDL for ${programId}: the program has not published one, pass idl_url instead`);+ }+ const data = Buffer.from(result.value.data[0], 'base64');+ if (data.length < 44) throw new AnchorIdlError('on-chain IDL account is truncated');+ const len = data.readUInt32LE(40);+ try {+ return JSON.parse(inflateSync(data.subarray(44, 44 + len)).toString('utf8'));+ } catch {+ throw new AnchorIdlError('on-chain IDL account does not hold a valid compressed IDL');+ }+}++/**+ * @param {{idl_url?: string, program_id?: string, cluster?: string}} input+ * @param {{fetchUrl: typeof fetch, rpcUrls: Record<string,string>}} opts+ */+export async function importFromAnchorIdl({ idl_url: idlUrl, program_id: programId, cluster = 'mainnet-beta' }, { fetchUrl, rpcUrls }) {+ if (typeof fetchUrl !== 'function') throw new Error('importFromAnchorIdl requires opts.fetchUrl');+ if (idlUrl) {+ const res = await fetchUrl(idlUrl);+ if (!res.ok) throw new AnchorIdlError(`failed to fetch ${idlUrl}: ${res.status}`);+ let raw;+ try {+ raw = JSON.parse(await res.text());+ } catch {+ throw new AnchorIdlError(`${idlUrl} is not valid JSON`);+ }+ return generateAnchorBundle(raw, { sourceUrl: idlUrl, programId });+ }+ if (!programId) throw new AnchorIdlError('idl_url or program_id is required');+ const endpoint = rpcUrls?.[cluster];+ if (!endpoint) throw new AnchorIdlError(`cluster must be one of ${Object.keys(rpcUrls || {}).join(', ')}`);+ const rpc = async (method, params) => {+ const res = await fetchUrl(endpoint, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ });+ if (!res.ok) throw new AnchorIdlError(`Solana RPC returned ${res.status}`);+ const body = JSON.parse(await res.text());+ if (body.error) throw new AnchorIdlError(`Solana RPC error: ${body.error.message}`);+ return body.result;+ };+ const raw = await fetchOnchainIdl(programId, { rpc });+ return generateAnchorBundle(raw, { sourceUrl: `solana:${cluster}:${programId}`, programId });+}diff --git a/packages/skill-import/src/anchor-runtime.js b/packages/skill-import/src/anchor-runtime.jsnew file mode 100644index 000000000..b26fdea19--- /dev/null+++ b/packages/skill-import/src/anchor-runtime.js@@ -0,0 +1,389 @@+// Runtime half of a generated Anchor skill. This file is NOT imported: its+// text is appended verbatim to a generated handlers.js (see anchor-idl.js),+// which declares `IDL` and `RISK` constants above it. It must stay free of+// imports and of Node/browser globals beyond BigInt, TextEncoder/Decoder and+// atob/btoa so it runs inside the skill sandbox, where only `ctx.*` exists.+//+// Nothing here signs. Previews build an unsigned instruction; write tools+// return that instruction plus a confirmation table for the host's+// confirm-gated wallet flow and never hold or request a key.++const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+const RPC_URLS = {+ 'mainnet-beta': 'https://api.mainnet-beta.solana.com',+ devnet: 'https://api.devnet.solana.com',+};++function b58encode(bytes) {+ let n = 0n;+ for (const b of bytes) n = (n << 8n) | BigInt(b);+ let out = '';+ while (n > 0n) {+ out = B58[Number(n % 58n)] + out;+ n /= 58n;+ }+ for (const b of bytes) {+ if (b !== 0) break;+ out = '1' + out;+ }+ return out;+}++function b58decode(str) {+ let n = 0n;+ for (const ch of str) {+ const i = B58.indexOf(ch);+ if (i < 0) throw new Error(`invalid base58 character "${ch}"`);+ n = n * 58n + BigInt(i);+ }+ const bytes = [];+ while (n > 0n) {+ bytes.unshift(Number(n & 0xffn));+ n >>= 8n;+ }+ let zeros = 0;+ for (const ch of str) {+ if (ch !== '1') break;+ zeros += 1;+ }+ return Uint8Array.from([...new Array(zeros).fill(0), ...bytes]);+}++function pubkeyBytes(value, label) {+ if (typeof value !== 'string') throw new Error(`${label} must be a base58 address`);+ let bytes;+ try {+ bytes = b58decode(value);+ } catch (err) {+ throw new Error(`${label}: ${err.message}`);+ }+ if (bytes.length !== 32) throw new Error(`${label} must decode to 32 bytes, got ${bytes.length}`);+ return bytes;+}++function toBase64(bytes) {+ let s = '';+ for (const b of bytes) s += String.fromCharCode(b);+ return btoa(s);+}++function fromBase64(text) {+ const s = atob(text);+ const out = new Uint8Array(s.length);+ for (let i = 0; i < s.length; i += 1) out[i] = s.charCodeAt(i);+ return out;+}++function toHex(bytes) {+ return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');+}++const INT_SIZES = { u8: 1, u16: 2, u32: 4, u64: 8, u128: 16, u256: 32, i8: 1, i16: 2, i32: 4, i64: 8, i128: 16, i256: 32 };++function definedName(type) {+ const d = type.defined;+ return typeof d === 'string' ? d : d.name;+}++function findType(name) {+ const t = (IDL.types || []).find((x) => x.name === name);+ if (!t) throw new Error(`IDL type "${name}" is not defined`);+ return t.type;+}++class Reader {+ constructor(bytes) {+ this.bytes = bytes;+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ this.pos = 0;+ }+ take(n) {+ if (this.pos + n > this.bytes.length) throw new Error('account data ended before the IDL layout did');+ const out = this.bytes.subarray(this.pos, this.pos + n);+ this.pos += n;+ return out;+ }+}++function readInt(r, kind) {+ const size = INT_SIZES[kind];+ const signed = kind[0] === 'i';+ const raw = r.take(size);+ let n = 0n;+ for (let i = size - 1; i >= 0; i -= 1) n = (n << 8n) | BigInt(raw[i]);+ if (signed && raw[size - 1] & 0x80) n -= 1n << BigInt(size * 8);+ return size <= 4 ? Number(n) : n.toString();+}++function decodeValue(r, type) {+ if (typeof type === 'string') {+ if (type in INT_SIZES) return readInt(r, type);+ if (type === 'bool') return r.take(1)[0] !== 0;+ if (type === 'pubkey' || type === 'publicKey') return b58encode(r.take(32));+ if (type === 'string') {+ const len = readInt(r, 'u32');+ return new TextDecoder().decode(r.take(len));+ }+ if (type === 'bytes') return toHex(r.take(readInt(r, 'u32')));+ if (type === 'f32') return new DataView(r.take(4).slice().buffer).getFloat32(0, true);+ if (type === 'f64') return new DataView(r.take(8).slice().buffer).getFloat64(0, true);+ throw new Error(`unsupported IDL type "${type}"`);+ }+ if (type.vec) {+ const len = readInt(r, 'u32');+ return Array.from({ length: len }, () => decodeValue(r, type.vec));+ }+ if (type.option || type.coption) {+ const inner = type.option || type.coption;+ const flag = type.coption ? readInt(r, 'u32') : r.take(1)[0];+ return flag ? decodeValue(r, inner) : null;+ }+ if (type.array) {+ const [inner, len] = type.array;+ if (inner === 'u8') return toHex(r.take(len));+ return Array.from({ length: len }, () => decodeValue(r, inner));+ }+ if (type.defined) return decodeDefined(r, findType(definedName(type)));+ throw new Error(`unsupported IDL type ${JSON.stringify(type)}`);+}++function decodeDefined(r, def) {+ if (def.kind === 'struct') {+ const fields = def.fields || [];+ if (fields.length && typeof fields[0] === 'object' && fields[0].name) {+ const out = {};+ for (const f of fields) out[f.name] = decodeValue(r, f.type);+ return out;+ }+ return fields.map((t) => decodeValue(r, t));+ }+ if (def.kind === 'enum') {+ const idx = r.take(1)[0];+ const variant = def.variants[idx];+ if (!variant) throw new Error(`enum variant index ${idx} is out of range`);+ if (!variant.fields) return variant.name;+ const fields = variant.fields;+ if (typeof fields[0] === 'object' && fields[0].name) {+ const out = {};+ for (const f of fields) out[f.name] = decodeValue(r, f.type);+ return { [variant.name]: out };+ }+ return { [variant.name]: fields.map((t) => decodeValue(r, t)) };+ }+ throw new Error(`unsupported IDL type kind "${def.kind}"`);+}++function writeInt(out, kind, value) {+ const size = INT_SIZES[kind];+ let n;+ try {+ n = BigInt(value);+ } catch {+ throw new Error(`${kind} argument must be an integer, got ${JSON.stringify(value)}`);+ }+ const bits = BigInt(size * 8);+ const signed = kind[0] === 'i';+ const min = signed ? -(1n << (bits - 1n)) : 0n;+ const max = signed ? (1n << (bits - 1n)) - 1n : (1n << bits) - 1n;+ if (n < min || n > max) throw new Error(`${kind} argument ${n} is out of range`);+ if (n < 0n) n += 1n << bits;+ for (let i = 0; i < size; i += 1) {+ out.push(Number(n & 0xffn));+ n >>= 8n;+ }+}++function encodeValue(out, type, value, label) {+ if (typeof type === 'string') {+ if (type in INT_SIZES) return writeInt(out, type, value);+ if (type === 'bool') {+ if (typeof value !== 'boolean') throw new Error(`${label} must be a boolean`);+ return out.push(value ? 1 : 0);+ }+ if (type === 'pubkey' || type === 'publicKey') {+ return out.push(...pubkeyBytes(value, label));+ }+ if (type === 'string') {+ if (typeof value !== 'string') throw new Error(`${label} must be a string`);+ const bytes = new TextEncoder().encode(value);+ writeInt(out, 'u32', bytes.length);+ return out.push(...bytes);+ }+ if (type === 'bytes') {+ const bytes = hexBytes(value, label);+ writeInt(out, 'u32', bytes.length);+ return out.push(...bytes);+ }+ throw new Error(`unsupported IDL type "${type}"`);+ }+ if (type.vec) {+ if (!Array.isArray(value)) throw new Error(`${label} must be an array`);+ writeInt(out, 'u32', value.length);+ return value.forEach((v, i) => encodeValue(out, type.vec, v, `${label}[${i}]`));+ }+ if (type.option) {+ if (value === null || value === undefined) return out.push(0);+ out.push(1);+ return encodeValue(out, type.option, value, label);+ }+ if (type.array) {+ const [inner, len] = type.array;+ if (inner === 'u8') {+ const bytes = hexBytes(value, label);+ if (bytes.length !== len) throw new Error(`${label} must be ${len} bytes (hex), got ${bytes.length}`);+ return out.push(...bytes);+ }+ if (!Array.isArray(value) || value.length !== len) throw new Error(`${label} must be an array of ${len}`);+ return value.forEach((v, i) => encodeValue(out, inner, v, `${label}[${i}]`));+ }+ if (type.defined) return encodeDefined(out, findType(definedName(type)), value, label);+ throw new Error(`unsupported IDL type ${JSON.stringify(type)}`);+}++function hexBytes(value, label) {+ if (Array.isArray(value)) return Uint8Array.from(value);+ if (typeof value !== 'string' || value.length % 2 || /[^0-9a-fA-F]/.test(value)) {+ throw new Error(`${label} must be a hex string`);+ }+ const bytes = new Uint8Array(value.length / 2);+ for (let i = 0; i < bytes.length; i += 1) bytes[i] = parseInt(value.slice(i * 2, i * 2 + 2), 16);+ return bytes;+}++function encodeDefined(out, def, value, label) {+ if (def.kind === 'struct') {+ const fields = def.fields || [];+ if (fields.length && typeof fields[0] === 'object' && fields[0].name) {+ if (!value || typeof value !== 'object') throw new Error(`${label} must be an object`);+ for (const f of fields) encodeValue(out, f.type, value[f.name], `${label}.${f.name}`);+ return;+ }+ if (!Array.isArray(value)) throw new Error(`${label} must be an array`);+ return fields.forEach((t, i) => encodeValue(out, t, value[i], `${label}[${i}]`));+ }+ if (def.kind === 'enum') {+ const name = typeof value === 'string' ? value : value && Object.keys(value)[0];+ const idx = def.variants.findIndex((v) => v.name === name);+ if (idx < 0) throw new Error(`${label} must be one of ${def.variants.map((v) => v.name).join(', ')}`);+ out.push(idx);+ const variant = def.variants[idx];+ if (!variant.fields) return;+ const payload = value[name];+ if (typeof variant.fields[0] === 'object' && variant.fields[0].name) {+ return variant.fields.forEach((f) => encodeValue(out, f.type, payload?.[f.name], `${label}.${name}.${f.name}`));+ }+ return variant.fields.forEach((t, i) => encodeValue(out, t, payload?.[i], `${label}.${name}[${i}]`));+ }+ throw new Error(`unsupported IDL type kind "${def.kind}"`);+}++function flattenAccounts(list, prefix = '') {+ const out = [];+ for (const a of list) {+ const name = prefix + a.name;+ if (a.accounts) out.push(...flattenAccounts(a.accounts, `${name}.`));+ else out.push({ ...a, name });+ }+ return out;+}++function rpcUrl(args, ctx) {+ const override = ctx?.secrets?.SOLANA_RPC_URL;+ if (override) return override;+ const cluster = args?.cluster || 'mainnet-beta';+ const url = RPC_URLS[cluster];+ if (!url) throw new Error(`cluster must be one of ${Object.keys(RPC_URLS).join(', ')}`);+ return url;+}++async function fetchAccount(address, args, ctx) {+ pubkeyBytes(address, 'address');+ const res = await ctx.fetch(rpcUrl(args, ctx), {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'getAccountInfo',+ params: [address, { encoding: 'base64', commitment: 'confirmed' }],+ }),+ });+ if (!res.ok) throw new Error(`Solana RPC returned ${res.status}`);+ const body = JSON.parse(await res.text());+ if (body.error) throw new Error(`Solana RPC error: ${body.error.message}`);+ const value = body.result?.value;+ if (!value) throw new Error(`account ${address} does not exist on ${args?.cluster || 'mainnet-beta'}`);+ return { owner: value.owner, lamports: value.lamports, data: fromBase64(value.data[0]) };+}++async function readAccountTool(typeName, args, ctx) {+ const address = args?.address;+ const meta = IDL.accounts.find((a) => a.name === typeName);+ const acct = await fetchAccount(address, args, ctx);+ if (acct.owner !== IDL.address) {+ throw new Error(`account ${address} is owned by ${acct.owner}, not program ${IDL.address}`);+ }+ const disc = acct.data.subarray(0, 8);+ if (disc.length < 8 || meta.discriminator.some((b, i) => disc[i] !== b)) {+ const other = IDL.accounts.find((a) => a.discriminator.every((b, i) => disc[i] === b));+ throw new Error(+ other+ ? `account ${address} is a ${other.name}, not a ${typeName}`+ : `account ${address} does not carry the ${typeName} discriminator`+ );+ }+ const r = new Reader(acct.data.subarray(8));+ const decoded = decodeDefined(r, findType(typeName));+ return { address, type: typeName, program_id: IDL.address, lamports: acct.lamports, data: decoded };+}++function buildInstruction(name, args) {+ const ix = IDL.instructions.find((i) => i.name === name);+ const accountInput = args?.accounts && typeof args.accounts === 'object' ? args.accounts : {};+ const argInput = args?.args && typeof args.args === 'object' ? args.args : {};++ const accounts = flattenAccounts(ix.accounts).map((a) => {+ const pubkey = a.address || accountInput[a.name];+ if (!pubkey) throw new Error(`accounts.${a.name} is required`);+ pubkeyBytes(pubkey, `accounts.${a.name}`);+ return { name: a.name, pubkey, isSigner: Boolean(a.signer), isWritable: Boolean(a.writable) };+ });++ const out = [...ix.discriminator];+ for (const a of ix.args) encodeValue(out, a.type, argInput[a.name], `args.${a.name}`);+ const data = Uint8Array.from(out);++ const risk = RISK[name];+ const summary = [+ `${name} on program ${IDL.address}`,+ ix.args.length ? `args: ${ix.args.map((a) => `${a.name}=${JSON.stringify(argInput[a.name])}`).join(', ')}` : 'no args',+ `signers: ${accounts.filter((a) => a.isSigner).map((a) => `${a.name} (${a.pubkey})`).join(', ') || 'none'}`,+ `writable: ${accounts.filter((a) => a.isWritable).map((a) => a.name).join(', ') || 'none'}`,+ risk.flags.length ? `risk ${risk.level}: ${risk.flags.map((f) => f.label).join('; ')}` : 'risk low: no token movement, account closure or authority change detected',+ ].join('\n');++ return {+ program_id: IDL.address,+ instruction: name,+ accounts,+ data_base64: toBase64(data),+ data_hex: toHex(data),+ summary,+ risk,+ };+}++function previewTool(name, args) {+ return { ...buildInstruction(name, args), signed: false };+}++function sendTool(name, args) {+ const built = buildInstruction(name, args);+ return {+ status: 'confirmation_required',+ signed: false,+ message:+ 'Nothing was signed or sent. Show the summary to the wallet owner and submit this instruction through the confirm-gated wallet flow; it executes only after their explicit yes.',+ ...built,+ };+}