compile_tolk
Compile Tolk smart contract source code into executable TON blockchain bytecode, generating Fift code, BoC, and code hash for deployment.
Instructions
Compiles Tolk smart contract source code using @ton/tolk-js. Provide source files as a map of filename->content. The entrypoint file must be included. Standard library imports (@stdlib/*) are resolved automatically. Returns compiled Fift code, BoC (Bag of Cells) in base64, and the code hash.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| entrypointFileName | Yes | The main .tolk file to compile (e.g., "main.tolk") | |
| sources | Yes | Object mapping filename -> source code content. Must include the entrypoint file. Example: {"main.tolk": "fun main(): int { return 0; }"} | |
| optimizationLevel | No | Optimization level 0-2 (default: 2) | |
| withStackComments | No | Include stack layout comments in Fift output |
Implementation Reference
- src/tools.ts:89-145 (handler)The main handler function for compile_tolk tool that validates input sources, calls the Tolk compiler via @ton/tolk-js runTolkCompiler, and returns formatted output with Fift code, BoC base64, and code hash on success, or error messages on failure.
async (args) => { const { sources, entrypointFileName } = args; const validationError = validateSources(sources, entrypointFileName); if (validationError) { return { content: [{ type: "text", text: `Validation error: ${validationError}` }], isError: true, }; } try { const result = await runTolkCompiler({ entrypointFileName, fsReadCallback: makeFsReadCallback(sources), optimizationLevel: args.optimizationLevel ?? 2, withStackComments: args.withStackComments ?? false, experimentalOptions: undefined, }); if (result.status === "error") { return { content: [{ type: "text", text: `Compilation error:\n\n${result.message}` }], isError: true, }; } const bocBytes = Buffer.from(result.codeBoc64, "base64"); const lines: string[] = [ `## Compilation Successful`, "", `**Code hash:** \`${result.codeHashHex}\``, `**BoC size:** ${bocBytes.length} bytes`, "", "### Fift output", "```fift", result.fiftCode, "```", "", "### BoC (base64)", "```", result.codeBoc64, "```", ]; if (result.stderr && result.stderr.length > 0) { lines.push("", "### Compiler warnings", "```", result.stderr, "```"); } return { content: [{ type: "text", text: lines.join("\n") }] }; } catch (err: any) { return { content: [{ type: "text", text: `Unexpected compiler error: ${err.message}` }], isError: true, }; } }, - src/tools.ts:78-88 (schema)Zod schema definition for compile_tolk tool inputs: entrypointFileName (string), sources (record mapping filenames to content), optional optimizationLevel (0-2), and optional withStackComments boolean.
{ entrypointFileName: z.string().describe('The main .tolk file to compile (e.g., "main.tolk")'), sources: z .record(z.string(), z.string()) .describe( "Object mapping filename -> source code content. Must include the entrypoint file. " + 'Example: {"main.tolk": "fun main(): int { return 0; }"}', ), optimizationLevel: z.number().int().min(0).max(2).optional().describe("Optimization level 0-2 (default: 2)"), withStackComments: z.boolean().optional().describe("Include stack layout comments in Fift output"), }, - src/tools.ts:72-146 (registration)Registration of the compile_tolk tool using server.tool() with tool name, description, input schema, and handler function.
server.tool( "compile_tolk", "Compiles Tolk smart contract source code using @ton/tolk-js. " + "Provide source files as a map of filename->content. The entrypoint file must be included. " + "Standard library imports (@stdlib/*) are resolved automatically. " + "Returns compiled Fift code, BoC (Bag of Cells) in base64, and the code hash.", { entrypointFileName: z.string().describe('The main .tolk file to compile (e.g., "main.tolk")'), sources: z .record(z.string(), z.string()) .describe( "Object mapping filename -> source code content. Must include the entrypoint file. " + 'Example: {"main.tolk": "fun main(): int { return 0; }"}', ), optimizationLevel: z.number().int().min(0).max(2).optional().describe("Optimization level 0-2 (default: 2)"), withStackComments: z.boolean().optional().describe("Include stack layout comments in Fift output"), }, async (args) => { const { sources, entrypointFileName } = args; const validationError = validateSources(sources, entrypointFileName); if (validationError) { return { content: [{ type: "text", text: `Validation error: ${validationError}` }], isError: true, }; } try { const result = await runTolkCompiler({ entrypointFileName, fsReadCallback: makeFsReadCallback(sources), optimizationLevel: args.optimizationLevel ?? 2, withStackComments: args.withStackComments ?? false, experimentalOptions: undefined, }); if (result.status === "error") { return { content: [{ type: "text", text: `Compilation error:\n\n${result.message}` }], isError: true, }; } const bocBytes = Buffer.from(result.codeBoc64, "base64"); const lines: string[] = [ `## Compilation Successful`, "", `**Code hash:** \`${result.codeHashHex}\``, `**BoC size:** ${bocBytes.length} bytes`, "", "### Fift output", "```fift", result.fiftCode, "```", "", "### BoC (base64)", "```", result.codeBoc64, "```", ]; if (result.stderr && result.stderr.length > 0) { lines.push("", "### Compiler warnings", "```", result.stderr, "```"); } return { content: [{ type: "text", text: lines.join("\n") }] }; } catch (err: any) { return { content: [{ type: "text", text: `Unexpected compiler error: ${err.message}` }], isError: true, }; } }, ); - src/tools.ts:9-33 (helper)validateSources helper function that checks sources record is non-empty, doesn't exceed file count limit (50), contains the entrypoint file, and total size doesn't exceed 1MB. Returns null on success or error message string.
function validateSources(sources: Record<string, string>, entrypointFileName: string): string | null { const keys = Object.keys(sources); if (keys.length === 0) { return "sources is empty. Provide at least the entrypoint file."; } if (keys.length > MAX_FILE_COUNT) { return `Too many source files (${keys.length}). Maximum is ${MAX_FILE_COUNT}.`; } if (!(entrypointFileName in sources)) { return `Entrypoint file "${entrypointFileName}" not found in sources. ` + `Available files: ${keys.join(", ")}`; } let totalSize = 0; for (const content of Object.values(sources)) { totalSize += new TextEncoder().encode(content).byteLength; } if (totalSize > MAX_TOTAL_SIZE) { return `Total sources size (${totalSize} bytes) exceeds limit of ${MAX_TOTAL_SIZE} bytes.`; } return null; } - src/tools.ts:35-45 (helper)makeFsReadCallback helper function that creates a filesystem read callback for the Tolk compiler, normalizing paths and throwing descriptive errors when files are not found.
function makeFsReadCallback(sources: Record<string, string>) { return (path: string): string => { const normalized = path.startsWith("./") ? path.slice(2) : path; if (sources[normalized] !== undefined) return sources[normalized]; if (sources[path] !== undefined) return sources[path]; throw new Error( `File not found: ${path} (available: ${Object.keys(sources).join(", ")}). ` + `Note: @stdlib/* imports are resolved automatically by the compiler.`, ); }; }