TITLE: Using Supported ES Module Imports JavaScript DESCRIPTION: ckb-js-vm exclusively supports ECMAScript Module (ESM) syntax for importing modules. These examples show the correct syntax for importing the entire module, named exports, and default exports using the `import` keyword. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-vm.md#_snippet_3 LANGUAGE: javascript CODE: ``` // Importing the entire module import * as bindings from "@ckb-js-std/bindings"; // Named imports import { hex } from "@ckb-js-std/bindings"; // Default import (if the module has a default export) import defaultExport from "module-name"; ``` ---------------------------------------- TITLE: Testing CKB Scripts with ckb-testtool in TypeScript DESCRIPTION: This snippet demonstrates how to write unit tests for CKB scripts using ckb-testtool in TypeScript. It shows setting up resources, creating transactions, deploying script binaries ('alwaysSuccess' and 'alwaysFailure'), mocking input cells, adding inputs and outputs, and using the Verifier to assert the expected execution outcome (success or failure). SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/unit-tests.md#_snippet_0 LANGUAGE: typescript CODE: ``` describe("example", () => { test("alwaysSuccess", () => { const resource = Resource.default(); const tx = Transaction.default(); // deploy a cell with risc-v binary, return a script. const lockScript = resource.deployCell( hexFrom(readFileSync(DEFAULT_SCRIPT_ALWAYS_SUCCESS)), tx, false, ); // update args lockScript.args = "0xEEFF"; // mock a input cell with the created script as lock script const inputCell = resource.mockCell(lockScript); // add input cell to the transaction tx.inputs.push(Resource.createCellInput(inputCell)); // add output cell to the transaction tx.outputs.push(Resource.createCellOutput(lockScript)); // add output data to the transaction tx.outputsData.push(hexFrom("0x")); // verify the transaction const verifier = Verifier.from(resource, tx); verifier.verifySuccess(); }); test("alwaysFailure", () => { const resource = Resource.default(); const tx = Transaction.default(); const lockScript = resource.deployCell( hexFrom(readFileSync(DEFAULT_SCRIPT_ALWAYS_FAILURE)), tx, false, ); const inputCell = resource.mockCell(lockScript); tx.inputs.push(Resource.createCellInput(inputCell)); const verifier = Verifier.from(resource, tx); verifier.verifyFailure(); verifier.verifyFailure(-1); }); }); ``` ---------------------------------------- TITLE: Verifying CKB Transaction with ckb-testtool in TypeScript DESCRIPTION: This snippet demonstrates the basic workflow for using ckb-testtool to test a CKB transaction. It initializes resources and a transaction, deploys a simple test script, mocks an input cell using that script, adds the input and output cells to the transaction, and finally uses a Verifier to assert successful execution. This requires the `ckb-testtool` and `@ckb-ccc/core` libraries installed, plus `ckb-debugger` available in the system's PATH. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/ckb-testtool/README.md#_snippet_0 LANGUAGE: typescript CODE: ``` import { DEFAULT_SCRIPT_ALWAYS_SUCCESS, Resource, Verifier, } from "ckb-testtool"; import { hexFrom, Transaction } from "@ckb-ccc/core"; import { readFileSync } from "fs"; const resource = Resource.default(); const tx = Transaction.default(); // deploy a cell with risc-v binary, return a script. const lockScript = resource.deployCell( hexFrom(readFileSync(DEFAULT_SCRIPT_ALWAYS_SUCCESS)), tx, false, ); // update args lockScript.args = "0xEEFF"; // mock a input cell with the created script as lock script const inputCell = resource.mockCell(lockScript); // add input cell to the transaction tx.inputs.push(Resource.createCellInput(inputCell)); // add output cell to the transaction tx.outputs.push(Resource.createCellOutput(lockScript)); // add output data to the transaction tx.outputsData.push(hexFrom("0x")); // verify the transaction const verifier = Verifier.from(resource, tx); verifier.verifySuccess(true); ``` ---------------------------------------- TITLE: Correctly Returning Exit Code with bindings.exit (JS) DESCRIPTION: This JavaScript code demonstrates the correct method for returning an explicit exit code in ckb-js-vm. By calling `bindings.exit()` with the desired status code, the program ensures that the intended exit code is propagated, overcoming the limitations of QuickJS module evaluation. It depends on the `@ckb-js-std/bindings` package providing the `exit` function. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/security.md#_snippet_1 LANGUAGE: JavaScript CODE: ``` function main() { // ... return -100; } bindings.exit(main()); ``` ---------------------------------------- TITLE: Creating CKB-JS-VM App Project (Bash) DESCRIPTION: Use the pnpm package manager to quickly initialize a new project using the create-ckb-js-vm-app template. This is the recommended way to start a new ckb-js-vm project. Requires pnpm version 10.4 or higher. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/README.md#_snippet_0 LANGUAGE: bash CODE: ``` pnpm create ckb-js-vm-app ``` ---------------------------------------- TITLE: Bootstrapping CKB Script Project using pnpm (Bash) DESCRIPTION: This command executes the `create` command via pnpm to run the `ckb-js-vm-app` package, which interactively guides the user through setting up a new CKB script project with TypeScript support. It requires pnpm to be installed and configured. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/create-app/README.md#_snippet_0 LANGUAGE: bash CODE: ``` pnpm create ckb-js-vm-app ``` ---------------------------------------- TITLE: Creating Project using create-ckb-js-vm-app Bash DESCRIPTION: Initialize a new ckb-js-vm project using the `create-ckb-js-vm-app` scaffolding tool via pnpm. This command sets up the basic project structure for developing on-chain scripts and tests, requiring `pnpm` and `ckb-debugger` prerequisites. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/getting-started.md#_snippet_0 LANGUAGE: bash CODE: ``` pnpm create ckb-js-vm-app ``` ---------------------------------------- TITLE: Example of Safer Dynamic Module Loading (JS) DESCRIPTION: This JavaScript function `loadModule` provides a safer pattern for dynamic module loading using `bindings.evalJsScript`. It wraps the potentially untrusted `moduleSource` within an Immediately Invoked Function Expression (IIFE) to limit its scope and pass only explicitly allowed APIs (`allowedAPIs`), mitigating risks associated with executing arbitrary code. It relies on `bindings.evalJsScript` from `@ckb-js-std/bindings`. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/security.md#_snippet_2 LANGUAGE: JavaScript CODE: ``` // Example of safer dynamic loading with basic validation function loadModule(moduleSource, allowedAPIs) { const wrappedSource = ` (function(restrictedBindings) { ${moduleSource} })({ ...allowedAPIs }); `; return bindings.evalJsScript(wrappedSource); } ``` ---------------------------------------- TITLE: Performing Reproducible Build using Bash DESCRIPTION: This command executes the `reproducible_build.sh` script. This script is designed to build the on-chain script in a way that produces an identical binary output every time it's run, ensuring reproducibility. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/deployment.md#_snippet_0 LANGUAGE: bash CODE: ``` bash reproducible_build.sh ``` ---------------------------------------- TITLE: Testing ckb-js-vm Project Bash DESCRIPTION: Execute the test suite for the ckb-js-vm project using pnpm. This command runs the off-chain tests defined in `packages/on-chain-script-tests` to verify the correctness and expected behavior of the compiled on-chain script. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/getting-started.md#_snippet_2 LANGUAGE: bash CODE: ``` pnpm test ``` ---------------------------------------- TITLE: Running CKB JS VM Tests - Bash DESCRIPTION: Execute this command in the project's root directory to run the test suite. This command uses the pnpm package manager to invoke the configured test script, which typically targets the main source file like `src/index.ts` as mentioned in the document. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/create-app/templates/packages/on-chain-script-tests/README.md#_snippet_0 LANGUAGE: bash CODE: ``` pnpm test ``` ---------------------------------------- TITLE: Running CKB VM Tests with pnpm DESCRIPTION: Executes the standard unit test suite for the CKB VM JavaScript scripts using pnpm. This command runs all tests defined in the project. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/tests/ts/README.md#_snippet_0 LANGUAGE: Shell CODE: ``` pnpm test ``` ---------------------------------------- TITLE: Building ckb-js-vm Project Bash DESCRIPTION: Build the on-chain script project using pnpm. This command compiles the TypeScript source code located in `packages/on-chain-script` into bundled JavaScript (`index.js`) and optimized CKB bytecode (`index.bc`), preparing the script for deployment. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/getting-started.md#_snippet_1 LANGUAGE: bash CODE: ``` pnpm build ``` ---------------------------------------- TITLE: Build CKB JS VM On-Chain Script (Bash) DESCRIPTION: This command initiates the build process for the on-chain script project using the pnpm package manager. It compiles the source code into the executable artifact intended for deployment on the CKB blockchain. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/create-app/templates/README.md#_snippet_0 LANGUAGE: bash CODE: ``` pnpm build ``` ---------------------------------------- TITLE: Running Full CKB JS VM Build Pipeline - Bash DESCRIPTION: This command represents the complete build pipeline for the CKB JavaScript VM project as executed by `pnpm build`. It chains three distinct steps: TypeScript type checking, JavaScript bundling with esbuild, and QuickJS bytecode compilation via `ckb-debugger`. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/core-concepts.md#_snippet_0 LANGUAGE: bash CODE: ``` tsc --noEmit && esbuild --platform=neutral --minify --bundle --external:@ckb-js-std/bindings --target=es2022 src/index.ts --outfile=dist/index.js && ckb-debugger --read-file dist/index.js --bin ../../build/ckb-js-vm -- -c dist/index.bc ``` ---------------------------------------- TITLE: Deploying Pre-compiled Script Binary in TypeScript Test DESCRIPTION: This example demonstrates a basic pattern for using a pre-compiled CKB script binary within a test case. It shows how to import the binary content from a file path, convert it to a hex string, and then deploy it as a cell script within a simulated transaction using the ckb-testtool resource object. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/unit-tests.md#_snippet_1 LANGUAGE: typescript CODE: ``` // Import the binary const alwaysSuccessScript = hexFrom(readFileSync(DEFAULT_SCRIPT_ALWAYS_SUCCESS)); // Deploy it in your test const lockScript = resource.deployCell(alwaysSuccessScript, tx, false); ``` ---------------------------------------- TITLE: Building and Starting Project (bash) DESCRIPTION: This snippet shows the necessary bash commands to first build the project using pnpm, and then execute the start command. These commands are typically run in the project's root directory to prepare and launch the application. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/create-app/templates/packages/on-chain-script/README.md#_snippet_0 LANGUAGE: bash CODE: ``` pnpm build pnpm start ``` ---------------------------------------- TITLE: Handling Index Out of Bounds Error in TypeScript Iterator DESCRIPTION: Demonstrates a pattern for gracefully handling the CKB_INDEX_OUT_OF_BOUND error (accessible via bindings.INDEX_OUT_OF_BOUND) within a TypeScript iterator's `next` method. This specific error is caught to signal the end of the iteration (returning { done: true }), while other exceptions are re-thrown with additional context. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-std.md#_snippet_1 LANGUAGE: typescript CODE: ``` next(): IteratorResult { try { const item = this.queryFn(this.index, this.source); this.index += 1; return { value: item, done: false }; } catch (err: any) { if (err.errorCode === bindings.INDEX_OUT_OF_BOUND) { // End iteration gracefully when we've reached the end of available items return { value: undefined, done: true }; } // Re-throw any other errors with additional context throw new Error(`QueryIter error: ${err.message || err}`); } } ``` ---------------------------------------- TITLE: Test CKB JS VM On-Chain Script (Bash) DESCRIPTION: This command executes the test suite for the on-chain script project using the pnpm package manager. It verifies the functionality and correctness of the built script before deployment. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/create-app/templates/README.md#_snippet_1 LANGUAGE: bash CODE: ``` pnpm test ``` ---------------------------------------- TITLE: Packing Files into Simple File System using ckb-fs-packer DESCRIPTION: This shell command uses the `ckb-fs-packer` tool to create a Simple File System binary (`fib.fs`) from specified source JavaScript files (`index.js` and `fib_module.js`) in the current directory. The output file `fib.fs` can then be used with ckb-js-vm. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/file-system.md#_snippet_2 LANGUAGE: Shell CODE: ``` npx ckb-fs-packer pack fib.fs index.js fib_module.js ``` ---------------------------------------- TITLE: Bundling JavaScript Code with Esbuild - Bash DESCRIPTION: This command utilizes esbuild to bundle the project's JavaScript source code. Key options include `--minify` for size optimization, `--external` to skip specific dependencies, and `--target` to specify the ECMAScript version supported by QuickJS. The output is a single bundled JavaScript file. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/core-concepts.md#_snippet_2 LANGUAGE: bash CODE: ``` esbuild --platform=neutral --minify --bundle --external:@ckb-js-std/bindings --target=es2022 src/index.ts --outfile=dist/index.js ``` ---------------------------------------- TITLE: Compiling JS to QuickJS Bytecode - Bash DESCRIPTION: This command uses the `ckb-debugger` tool along with a custom `ckb-js-vm` binary to compile the bundled JavaScript file (`dist/index.js`) into QuickJS bytecode (`dist/index.bc`). This step is crucial for generating the final binary that will be executed efficiently on the CKB VM. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/core-concepts.md#_snippet_3 LANGUAGE: bash CODE: ``` ckb-debugger --read-file dist/index.js --bin ../../build/ckb-js-vm -- -c dist/index.bc ``` ---------------------------------------- TITLE: Packing Files with Renaming using ckb-fs-packer DESCRIPTION: This shell command demonstrates using `ckb-fs-packer` to package local files (`1.js`, `2.js`) into a Simple File System (`archive.fs`) while renaming them within the file system (`lib/1.js`, `lib/2.js`) using the `source:destination` syntax. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/file-system.md#_snippet_3 LANGUAGE: Shell CODE: ``` npx ckb-fs-packer pack archive.fs 1.js:lib/1.js 2.js:lib/2.js ``` ---------------------------------------- TITLE: Defining CKB VM Binding Error Codes DESCRIPTION: Defines the standard error codes returned by the low-level CKB VM bindings functions, such as CKB_INDEX_OUT_OF_BOUND (1) and CKB_ITEM_MISSING (2), which represent specific error conditions that application code should be prepared to handle. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-std.md#_snippet_0 LANGUAGE: plaintext CODE: ``` CKB_INDEX_OUT_OF_BOUND 1 CKB_ITEM_MISSING 2 ``` ---------------------------------------- TITLE: Compiling JavaScript to Bytecode with ckb-debugger Bash DESCRIPTION: This command demonstrates compiling a JavaScript file (`hello.js`) into QuickJS bytecode (`hello.bc`) using ckb-debugger and the ckb-js-vm binary. The `--read-file` option provides the source, and the `-c` option passed after `--` tells ckb-js-vm to compile. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-vm.md#_snippet_2 LANGUAGE: bash CODE: ``` ckb-debugger --read-file hello.js --bin build/ckb-js-vm -- -c hello.bc ``` ---------------------------------------- TITLE: Defining Main Entrypoint JavaScript DESCRIPTION: This JavaScript snippet serves as the main entry file (`index.js`) for a Simple File System. It demonstrates importing a function from another module (`fib_module.js`) and using it. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/file-system.md#_snippet_0 LANGUAGE: JavaScript CODE: ``` // File index.js import { fib } from "./fib_module.js"; console.log("fib(10)=", fib(10)); ``` ---------------------------------------- TITLE: Performing TypeScript Type Checking - Bash DESCRIPTION: This command uses the TypeScript compiler (`tsc`) to perform static type checking on the project's source code. The `--noEmit` flag ensures that no output files are generated, making it purely a validation step to catch errors early. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/core-concepts.md#_snippet_1 LANGUAGE: bash CODE: ``` tsc --noEmit ``` ---------------------------------------- TITLE: Build and Run Lock/UDT Scripts - Bash DESCRIPTION: These bash commands build the `src/simple_udt.ts` and `src/secp256k1_blake160_lock.ts` lock scripts separately and then run tests that likely utilize these built scripts. This shows the process for compiling and testing specific lock script examples. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/examples/README.md#_snippet_1 LANGUAGE: bash CODE: ``` pnpm run build:lock pnpm run build:simple_udt pnpm test ``` ---------------------------------------- TITLE: Build and Run Index Script - Bash DESCRIPTION: These bash commands are used to build the `src/index.ts` example script and then execute it using pnpm. It demonstrates the basic workflow for running a single script example. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/examples/README.md#_snippet_0 LANGUAGE: bash CODE: ``` pnpm build pnpm start ``` ---------------------------------------- TITLE: Unpacking Simple File System using ckb-fs-packer DESCRIPTION: This shell command uses the `ckb-fs-packer` tool to extract the contents of an existing Simple File System binary (`fib.fs`) into a specified destination directory (`.`, representing the current directory). SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/file-system.md#_snippet_4 LANGUAGE: Shell CODE: ``` npx ckb-fs-packer unpack fib.fs . ``` ---------------------------------------- TITLE: Illustrating Code Execution Order Due to Hoisting (JavaScript) DESCRIPTION: This JavaScript snippet shows the effective execution order of the previous example due to hoisting. All `import` statements are processed first, potentially causing a file system access error if the mount operation has not occurred before the imports resolve. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/file-system.md#_snippet_8 LANGUAGE: JavaScript CODE: ``` import * as bindings from "@ckb-js-std/bindings"; import * as module from './fib_module.js'; bindings.mount(2, bindings.SOURCE_CELL_DEP, "/") ``` ---------------------------------------- TITLE: Running CKB-JS-VM Example (Shell) DESCRIPTION: Navigate into the packages/examples directory and execute the start script to run the provided example project. This demonstrates how to execute a built ckb-js-vm project. Requires pnpm and previously built packages. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/README.md#_snippet_3 LANGUAGE: shell CODE: ``` cd packages/examples pnpm run start ``` ---------------------------------------- TITLE: Demonstrating Module Hoisting Issue Before File System Mount (JavaScript) DESCRIPTION: This JavaScript snippet illustrates a potential issue where `import` statements, subject to hoisting, might attempt to load modules (`./fib_module.js`) before the necessary file system (`bindings.mount`) is initialized, leading to errors. This highlights the need for an `init.js` file. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/file-system.md#_snippet_7 LANGUAGE: JavaScript CODE: ``` import * as bindings from "@ckb-js-std/bindings"; bindings.mount(2, bindings.SOURCE_CELL_DEP, "/") import * as module from './fib_module.js'; ``` ---------------------------------------- TITLE: Defining Helper Module JavaScript DESCRIPTION: This JavaScript snippet defines a module (`fib_module.js`) exporting a simple function. It is intended to be included in a Simple File System and imported by the main entrypoint. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/file-system.md#_snippet_1 LANGUAGE: JavaScript CODE: ``` // File fib_module.js export function fib(n) { if (n <= 0) return 0; else if (n == 1) return 1; else return fib(n - 1) + fib(n - 2); } ``` ---------------------------------------- TITLE: Incorrectly Returning Exit Code in QuickJS Module (JS) DESCRIPTION: This JavaScript code shows an attempt to return an exit code from the `main` function. However, due to QuickJS treating files as modules and returning promises, this pattern fails to produce the expected non-zero exit code (-100) and instead results in a zero exit code. It relies on the standard JavaScript function execution. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/security.md#_snippet_0 LANGUAGE: JavaScript CODE: ``` function main() { // ... return -100; } main(); ``` ---------------------------------------- TITLE: Demonstrating Unsupported CommonJS Exports JavaScript DESCRIPTION: This JavaScript snippet demonstrates the CommonJS `module.exports` syntax for exporting values from a module. This syntax is explicitly not supported by ckb-js-vm and attempting to use it will result in runtime errors. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-vm.md#_snippet_5 LANGUAGE: javascript CODE: ``` // ❌ This will also not work module.exports = { /* ... */ }; ``` ---------------------------------------- TITLE: Demonstrating Unsupported CommonJS Require JavaScript DESCRIPTION: This JavaScript snippet demonstrates the CommonJS `require()` syntax for importing modules. This syntax is explicitly not supported by ckb-js-vm and attempting to use it will result in runtime errors. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-vm.md#_snippet_4 LANGUAGE: javascript CODE: ``` // ❌ This will not work in ckb-js-vm const bindings = require("@ckb-js-std/bindings"); ``` ---------------------------------------- TITLE: Running CKB VM Tests Verbose with Jest DESCRIPTION: Executes the unit test suite with Jest, enabling verbose output. This is particularly useful for viewing on-chain script logs during test execution for detailed debugging. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/tests/ts/README.md#_snippet_1 LANGUAGE: Shell CODE: ``` pnpm jest --verbose ``` ---------------------------------------- TITLE: Implementing an IPC Client in TypeScript DESCRIPTION: This TypeScript code shows how to create an IPC client that communicates with a server spawned in a CKB cell. It demonstrates how to spawn the server, establish a channel using the communication pipes, and send a request to receive a response. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/ipc/README.md#_snippet_2 LANGUAGE: TypeScript CODE: ``` import { SCRIPT_HASH_TYPE_TYPE } from "@ckb-js-std/bindings"; import { Channel, RequestPacket, spawnCellServer } from "@ckb-js-std/ipc"; function main() { let jsVmCodeHash = ... // Your ckb-js-vm code hash let serverCodeHash = ... // Your server code hash // spawn server let [readPipe, writePipe] = spawnCellServer( jsVmCodeHash.buffer, SCRIPT_HASH_TYPE_TYPE, ["-t", serverCodeHash], ); let channel = new Channel(readPipe, writePipe); let req = new RequestPacket(new Uint8Array([1, 2, 3])); let res = channel.call(req); } main(); ``` ---------------------------------------- TITLE: Implementing a Basic IPC Server in TypeScript DESCRIPTION: This TypeScript code demonstrates how to create a simple IPC server using @ckb-js-std/ipc. It defines a RequestHandler class that serves requests by returning a predefined response and starts the server using the runServer function. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/ipc/README.md#_snippet_1 LANGUAGE: TypeScript CODE: ``` import { runServer, RequestHandler, RequestPacket, ResponsePacket, } from "@ckb-js-std/ipc"; class Serve implements RequestHandler { serve(req: RequestPacket): ResponsePacket { return new ResponsePacket(0, new Uint8Array([42])); } } function main() { log.setLevel(log.LogLevel.Debug); runServer(new Serve()); } main(); ``` ---------------------------------------- TITLE: Installing @ckb-js-std/ipc with pnpm DESCRIPTION: This command shows how to install the @ckb-js-std/ipc library using the pnpm package manager. It is a required step before using the library in a project. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/packages/ipc/README.md#_snippet_0 LANGUAGE: Bash CODE: ``` pnpm install @ckb-js-std/ipc ``` ---------------------------------------- TITLE: CommonJS Require Workaround for ckb-js-std/core using globalThis DESCRIPTION: Provides a workaround demonstrated in TypeScript to enable the use of CommonJS `require` for the @ckb-js-std/core library. It works by importing the module using ES modules first, storing it on the globalThis object, and then redefining the global require function to look up specified modules like @ckb-js-std/core from globalThis. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-std.md#_snippet_3 LANGUAGE: typescript CODE: ``` import * as core from '@ckb-js-std/core'; globalThis.__ckb_core = core; require = function (name) { if (name === '@ckb-js-std/core') { return globalThis.__ckb_module_core; }\n throw new Error('cannot find the module: ' + name); } ``` ---------------------------------------- TITLE: Illustrating QuickJS Null Termination Requirement (JavaScript) DESCRIPTION: This simple JavaScript snippet is used to illustrate the QuickJS requirement for null-terminated source code strings. Even though the visible code is 17 characters, ckb-js-vm adds a null byte (`\0`) at the end when providing it to QuickJS. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/file-system.md#_snippet_6 LANGUAGE: JavaScript CODE: ``` console.log("hi") ``` ---------------------------------------- TITLE: Building CKB-JS-STD Packages (Shell) DESCRIPTION: Commands to install Node.js dependencies using pnpm and build the ckb-js-std TypeScript helper packages. This is part of the manual installation process. Requires pnpm and Node.js. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/README.md#_snippet_2 LANGUAGE: shell CODE: ``` pnpm install pnpm build ``` ---------------------------------------- TITLE: Performing Reproducible Build for ckb-js-vm Bash DESCRIPTION: This command executes a script designed to perform a reproducible build of the ckb-js-vm binary. A reproducible build ensures the same binary output regardless of the build environment. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-vm.md#_snippet_1 LANGUAGE: bash CODE: ``` bash reproducible_build.sh ``` ---------------------------------------- TITLE: Building ckb-js-vm Binary Bash DESCRIPTION: These commands build the ckb-js-vm binary locally. The first command initializes and updates submodules, and the second compiles the project. clang-18 is a required dependency for compilation. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-vm.md#_snippet_0 LANGUAGE: bash CODE: ``` git submodule update --init make all ``` ---------------------------------------- TITLE: Building CKB-JS-VM Runtime (Shell) DESCRIPTION: Commands to update Git submodules and build the core ckb-js-vm runtime engine from source. This is required for manual installation. Requires Git, make, and clang-18. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/README.md#_snippet_1 LANGUAGE: shell CODE: ``` git submodule update --init make all ``` ---------------------------------------- TITLE: Requiring ckb-js-std/bindings using CommonJS in JavaScript DESCRIPTION: Shows the standard way to import the @ckb-js-std/bindings library using the CommonJS `require` syntax in a JavaScript environment. This library provides direct low-level access to the C implementation and is often embedded directly within ckb-js-vm. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/ckb-js-std.md#_snippet_2 LANGUAGE: javascript CODE: ``` const bindings = require("@ckb-js-std/bindings"); ``` ---------------------------------------- TITLE: Defining Simple File System On-disk Structure (C-like) DESCRIPTION: These C-like struct definitions describe the binary format of the Simple File System on disk. It outlines the structure for file metadata (name/content offset/length) and the overall file system layout including file count, metadata array, and payload bytes. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/src/file-system.md#_snippet_5 LANGUAGE: C CODE: ``` struct Blob { uint32_t offset; uint32_t length; } struct Metadata { struct Blob file_name; struct Blob file_content; } struct SimpleFileSystem { uint32_t file_count; struct Metadata metadata[..]; uint8_t payload[..]; } ``` ---------------------------------------- TITLE: Building and Opening mdBook Documentation (Shell) DESCRIPTION: This shell command builds the mdBook project, compiling the source files into HTML documentation, and then automatically opens the output in your default web browser for local preview. It requires mdbook to be installed and run within the root directory of an mdbook project. SOURCE: https://github.com/nervosnetwork/ckb-js-vm/blob/main/docs/tutorial/README.md#_snippet_0 LANGUAGE: shell CODE: ``` mdbook build --open ```