### Installing Dependencies and Starting Lumos Example (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/packages/transaction-manager/examples/chained-transfer-example/README.md These commands are used to install the necessary project dependencies and then execute the Lumos chained transfer example. `yarn install` or `npm install` fetches packages, while `yarn start` or `npm run start` runs the application. ```sh yarn install / npm install yarn start / npm run start ``` -------------------------------- ### Building and Starting Lumos MetaMask Example Source: https://github.com/ckb-js/lumos/blob/develop/examples/omni-lock-metamask/README.md These commands are used to build the Lumos project, create a release, navigate into the specific 'omni-lock-metamask' example directory, and then start the example application. This sequence is a prerequisite for running the Lumos-MetaMask integration demonstration. ```Shell npm run build npm run build-release cd examples/omni-lock-metamask npm start ``` -------------------------------- ### Starting Next.js Development Server (Bash) Source: https://github.com/ckb-js/lumos/blob/develop/examples/nextjs/README.md This snippet provides commands to initiate the Next.js development server using various package managers. Running one of these commands starts the application locally, making it accessible for development and testing, typically at `http://localhost:3000`. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Quick Start for Docusaurus Website (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/website/README.md This shell script provides the necessary commands to quickly set up and run the Docusaurus 2 website locally. It first installs all project dependencies using `pnpm install` and then starts the development server with `pnpm start`. ```sh pnpm install pnpm start ``` -------------------------------- ### Starting the SUDT Exchange Example Application (Bash) Source: https://github.com/ckb-js/lumos/blob/develop/examples/exchange-sudt-for-ckb/README.md This command initiates the local development server for the SUDT exchange example application. Running this command is a necessary prerequisite to access the web interface at http://localhost:1234 and proceed with issuing SUDT and exchanging it for CKB. ```bash npm start ``` -------------------------------- ### Starting Lumos PW-Lock MetaMask Example Source: https://github.com/ckb-js/lumos/blob/develop/examples/pw-lock-metamask/README.md This snippet provides the necessary shell commands to navigate into the `pw-lock-metamask` example directory and initiate the application using npm. It assumes that the main Lumos project has been built prior to execution. ```Shell cd examples/pw-lock-metamask npm start ``` -------------------------------- ### Building and Running Omnilock Example with Lumos (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/examples/omni-lock-secp256k1-blake160/README.md This snippet provides the command-line instructions to prepare and execute the Lumos Omnilock example. It involves building the main Lumos project, navigating into the specific example directory, and then starting the example application. ```Shell npm run build cd examples/omni-lock-own-signature npm start ``` -------------------------------- ### Installing Dependencies and Starting Lumos Project Source: https://github.com/ckb-js/lumos/blob/develop/examples/joyid/README.md This snippet provides the necessary commands to set up the Lumos project for the JoyID integration example. It involves installing project dependencies and then starting the application. ```Shell pnpm install pnpm start ``` -------------------------------- ### Building Production Bundle with Create React App (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/examples/create-react-app/README.md This command builds the React application for production, optimizing and minifying the code into the `build` folder. The output is ready for deployment, with filenames including hashes for caching. ```Shell npm run build ``` -------------------------------- ### Starting Development Server with Create React App (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/examples/create-react-app/README.md This command runs the React application in development mode, typically opening it in a web browser at http://localhost:3000. It enables live reloading on code changes and displays lint errors in the console. ```Shell npm start ``` -------------------------------- ### Building Lumos Project (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/examples/README.md This snippet provides the shell commands to clone the Lumos repository, navigate into its directory, install dependencies using pnpm, and build the project. It's a prerequisite for local development and testing. ```sh git clone https://github.com/ckb-js/lumos.git cd lumos pnpm install pnpm run build ``` -------------------------------- ### Running Lumos Omnilock UniSat Example (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/examples/omni-lock-unisat/README.md This snippet provides the shell commands required to set up and run the Lumos Omnilock UniSat example. It involves building the main Lumos project, navigating into the specific example directory, and then starting the application to demonstrate the integration. ```Shell npm run build cd examples/omni-lock-unisat npm start ``` -------------------------------- ### Ejecting Create React App Configuration (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/examples/create-react-app/README.md This command removes the single build dependency from the project, copying all configuration files (webpack, Babel, ESLint, etc.) directly into the project. This provides full control over the build setup but is a one-way operation. ```Shell npm run eject ``` -------------------------------- ### Setting up Local Verdaccio Registry (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/devtools/README.md This shell script installs Verdaccio globally, starts a local registry instance using a specified configuration file and port, and then configures npm to use this local registry with a fake authentication token. This setup is crucial for testing package publication workflows in a controlled local environment. ```sh npm install -g verdaccio verdaccio --config ./devtools/verdaccio.yaml --listen=4873 npm config set registry http://localhost:4873 npm config set //localhost:4873/:_authToken fake ``` -------------------------------- ### Initializing Lumos Project with Bun Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-tutorial-issue-and-transfer-xudt.md This snippet demonstrates how to set up a new project directory, initialize it using Bun, and install the `@ckb-lumos/lumos` library. It prepares the development environment for CKB interactions. ```sh mkdir xudt-from-scratch cd xudt-from-scratch bun init -y # try running the ts file created by default bun index.ts # based on the @ckb-lumos/lumos@0.0.0-canary-84521a5-20240530061434 bun install @ckb-lumos/lumos@canary ``` -------------------------------- ### Launching Test Runner with Create React App (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/examples/create-react-app/README.md This command launches the test runner in an interactive watch mode, allowing developers to run tests and see results as code changes. It's used for unit and integration testing of the React application. ```Shell npm test ``` -------------------------------- ### Running Codec Examples with ts-node (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/packages/codec/examples/README.md This snippet provides the command-line instruction to execute a TypeScript example file using `ts-node`. `ts-node` enables direct execution of TypeScript files without requiring a separate compilation step, which is useful for quick testing and running scripts. ```Shell ts-node mixed-codec-godwoken-v1-withdrawal-args.ts ``` -------------------------------- ### Launching CKB Indexer for Data Sync (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/packages/testkit/README.md This command starts the CKB indexer, configuring it to connect to the previously launched mock RPC server at `http://127.0.0.1:8118/rpc`. It specifies the indexer's local listening address as `127.0.0.1:8116` and designates `indexer-store-tmp` as the directory for storing synced block data. This setup enables the indexer to build a local, queryable database of CKB chain information. ```Shell ckb-indexer -c http://127.0.0.1:8118/rpc -l 127.0.0.1:8116 -s indexer-store-tmp ``` -------------------------------- ### Initializing Yarn Project (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md This command initializes a new Node.js project using Yarn. Similar to `npm init`, it guides the user through creating a `package.json` file for project configuration and dependency management. ```Shell yarn init ``` -------------------------------- ### Installing Lumos with Yarn (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md This command installs the `@ckb-lumos/lumos` package and its dependencies into the current project using Yarn. It provides the necessary tools for CKB blockchain development. ```Shell yarn add @ckb-lumos/lumos ``` -------------------------------- ### Installing Node.js and pnpm (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/README.md This snippet provides shell commands to update package lists, install Node.js, and then install pnpm globally using npm. These are prerequisites for building and running Lumos. ```Shell sudo apt-get update sudo apt install nodejs npm install -g pnpm ``` -------------------------------- ### Lumos DAO Transaction Example (TypeScript) Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-from-ckb-sdk-core.md This comprehensive example demonstrates how to interact with the CKB DAO using the Lumos library. It covers initializing the Lumos configuration, generating SECP256K1 accounts, fetching cell details by outpoint, and performing deposit, withdraw, and unlock operations. The example also includes transaction sealing and sending to the CKB testnet. ```TypeScript import { BI, OutPoint, Cell, config, Indexer, RPC, hd, commons } from "@ckb-lumos/lumos" import { TransactionSkeleton, encodeToAddress, sealTransaction } from "@ckb-lumos/helpers" // ckt const CKB_RPC_URL = "https://testnet.ckb.dev/rpc" const CKB_INDEXER_URL = "https://testnet.ckb.dev/indexer" const rpc = new RPC(CKB_RPC_URL) const indexer = new Indexer(CKB_INDEXER_URL, CKB_RPC_URL) const CONFIG = config.createConfig({ PREFIX: "ckt", SCRIPTS: { ...config.predefined.AGGRON4.SCRIPTS, }, }) config.initializeConfig(CONFIG) export const generateSECP256K1Account = (privKey: string) => { const pubKey = hd.key.privateToPublic(privKey) const args = hd.key.publicKeyToBlake160(pubKey) const template = CONFIG.SCRIPTS["SECP256K1_BLAKE160"]! const lockScript = { codeHash: template.CODE_HASH, hashType: template.HASH_TYPE, args: args, } const address = encodeToAddress(lockScript, { config: CONFIG }) return { lockScript, address, pubKey, privKey, } } export const getCellByOutPoint = async (outpoint: OutPoint): Promise => { const tx = await rpc.get_transaction(outpoint.txHash) if (!tx) { throw new Error(`not found tx: ${outpoint.txHash}`) } const block = await rpc.getBlock(tx.txStatus.blockHash!) return { cellOutput: tx.transaction.outputs[0], data: tx.transaction.outputsData[0], outPoint: outpoint, blockHash: tx.txStatus.blockHash, blockNumber: block!.header.number, } } export const deposit = async (fromAddress: string, privKey: string) => { let txSkeleton = TransactionSkeleton({ cellProvider: indexer }) txSkeleton = await commons.dao.deposit(txSkeleton, fromAddress, fromAddress, BigInt(1000 * 10 ** 8)) txSkeleton = await commons.secp256k1Blake160.payFee(txSkeleton, fromAddress, BigInt(1 * 10 ** 8)) txSkeleton = commons.common.prepareSigningEntries(txSkeleton) const message = txSkeleton.get("signingEntries").get(0)?.message const Sig = hd.key.signRecoverable(message!, privKey) const tx = sealTransaction(txSkeleton, [Sig]) const hash = await rpc.sendTransaction(tx, "passthrough") return hash } export const withdraw = async (depositOutpoint: OutPoint, fromAddress: string, privKey: string) => { let txSkeleton = TransactionSkeleton({ cellProvider: indexer }) const depositCell = await getCellByOutPoint(depositOutpoint) txSkeleton = await commons.dao.withdraw(txSkeleton, depositCell, fromAddress) txSkeleton = await commons.secp256k1Blake160.payFee(txSkeleton, fromAddress, BigInt(1 * 10 ** 8)) txSkeleton = commons.common.prepareSigningEntries(txSkeleton) const message = txSkeleton.get("signingEntries").get(0)?.message const Sig = hd.key.signRecoverable(message!, privKey) const tx = sealTransaction(txSkeleton, [Sig]) const hash = await rpc.sendTransaction(tx, "passthrough") return hash } export const unlock = async ( depositOutpoint: OutPoint, withdrawOutpoint: OutPoint, fromAddress: string, privKey: string ) => { let txSkeleton = TransactionSkeleton({ cellProvider: indexer }) const depositCell = await getCellByOutPoint(depositOutpoint) const withdrawCell = await getCellByOutPoint(withdrawOutpoint) txSkeleton = await commons.dao.unlock(txSkeleton, depositCell, withdrawCell, fromAddress, fromAddress) txSkeleton = await commons.secp256k1Blake160.payFee(txSkeleton, fromAddress, BI.from(1 * 10 ** 8)) txSkeleton = commons.common.prepareSigningEntries(txSkeleton) const message = txSkeleton.get("signingEntries").get(0)?.message const Sig = hd.key.signRecoverable(message!, privKey) const tx = sealTransaction(txSkeleton, [Sig]) const hash = await rpc.sendTransaction(tx, "passthrough") return hash } const bootstrap = async () => { const alice = generateSECP256K1Account("0xd00c06bfd800d27397002dca6fb0993d5ba6399b4238b2f29ee9deb97593d2bc") const depositTx = await deposit(alice.address, alice.privKey) const depositOutpoint = { txHash: depositTx, index: "0x0" } const withdrawTx = await withdraw(depositOutpoint, alice.address, alice.privKey) const withdrawOutpoint = { txHash: withdrawTx, index: "0x0" } // wait 180 epoch const unlockTx = await unlock(depositOutpoint, withdrawOutpoint, alice.address, alice.privKey) console.log("unlockTx is", unlockTx) } bootstrap() ``` -------------------------------- ### Installing Dependencies for lumos-molecule-codegen (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/packages/molecule/README.md This shell command snippet outlines the necessary npm installations for utilizing the lumos-molecule-codegen CLI tool. It specifies installing @ckb-lumos/molecule as a development dependency and @ckb-lumos/codec as a regular dependency, which are prerequisites for code generation. ```Shell npm install -D @ckb-lumos/molecule npm install @ckb-lumos/codec ``` -------------------------------- ### Building and Running Lumos Solana Example Source: https://github.com/ckb-js/lumos/blob/develop/examples/omni-lock-solana/README.md This snippet provides the necessary shell commands to build the Lumos project and then navigate into and execute the 'omni-lock-solana' example. These steps are prerequisites for running the demonstration of Omnilock and Phantom integration. ```Shell npm run build cd examples/omni-lock-solana npm start ``` -------------------------------- ### Installing JoyID CKB Package with npm Source: https://github.com/ckb-js/lumos/blob/develop/packages/joyid/README.md This snippet demonstrates how to install the `@joyid/ckb` package, which is a prerequisite for using `@ckb-lumos/joyid`. It specifies a particular version to ensure compatibility. ```sh npm install @joyid/ckb #@0.0.6 ``` -------------------------------- ### Using Root Lumos Package for Configuration and Address Parsing in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/01-run-lumos-in-the-browser.md This TypeScript example demonstrates the convenience of the new `@ckb-lumos/lumos` root package, which consolidates various subpackages. It shows how to import and use `helpers` for address parsing and `config` for initializing network configurations, simplifying imports and usage. ```ts import { Script, Indexer, helpers, config } from "@ckb-lumos/lumos" config.initializeConfig(config.predefined.AGGRON4) const address = "ckt1qyqxgftlqzmtv05cwcyl4xlz6ryx6dgsyrasjrp27t" const lock: Script = helpers.parseAddress(address) ``` -------------------------------- ### Releasing to Verdaccio in GitHub Actions (YAML) Source: https://github.com/ckb-js/lumos/blob/develop/devtools/README.md This YAML snippet defines a step for a GitHub Actions workflow, designed to test package releases by publishing to a local Verdaccio registry within the CI/CD pipeline. It installs Verdaccio, configures npm for the local registry, and starts Verdaccio in the background, allowing for automated testing of the release process. ```yaml # TODO remove me when ready - name: Release to Verdaccio run: | npm install -g verdaccio npm config set registry http://localhost:4873 npm config set //localhost:4873/:_authToken fake nohup verdaccio --config ./devtools/verdaccio.yaml --listen=4873 >/dev/null 2>&1 & ``` -------------------------------- ### Installing Lumos with npm (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md This command installs the `@ckb-lumos/lumos` package and its dependencies into the current project using npm. Lumos is the primary library for interacting with the CKB blockchain in JavaScript/TypeScript. ```Shell npm install @ckb-lumos/lumos ``` -------------------------------- ### Loading and Saving XPubs with Lumos HD Source: https://github.com/ckb-js/lumos/blob/develop/packages/hd/README.md This example illustrates the usage of `XPubStore` from `@ckb-lumos/hd` for managing extended public keys. It shows how to load an XPub from a file, convert it into an `AccountExtendedPublicKey` for derivation purposes, and save the XPub back to a specified path, facilitating read-only access to account structures. ```javascript const { XPubStore } = require("@ckb-lumos/hd") // load from xpub file. const xpub = XPubStore.load("you path") // to AccountExtendedPublicKey const accountExtendedPublicKey = xpub.toAccountExtendedPublicKey() // save xpub file. xpub.save("your path") ``` -------------------------------- ### Checking Lumos Build (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/examples/README.md This command executes a TypeScript file using `npx ts-node` to verify if the Lumos project build was successful. It's a quick way to confirm the development environment is set up correctly. ```sh npx ts-node misc/config-manager.ts ``` -------------------------------- ### Migrating `CacheManager.loadFromKeystore` in JavaScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-to-v0.23.md The `CacheManager.loadFromKeystore` method has been deprecated. Users should migrate to `loadFromKeystoreJson` and provide the parsed JSON content of the keystore file directly, instead of just the file path, requiring manual file reading and parsing. ```JavaScript JSON.parse(fs.readFileSync(path).toString()) ``` -------------------------------- ### Installing Lumos Package with npm Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/01-run-lumos-in-the-browser.md This snippet provides the command to install the `@ckb-lumos/lumos` package, which is the consolidated package containing all subpackages, making it easier to use Lumos in web projects. It supports both npm and yarn package managers. ```shell npm install @ckb-lumos/lumos ``` -------------------------------- ### Getting CKB Balance with Lumos Indexer in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/01-run-lumos-in-the-browser.md This TypeScript example demonstrates how to use `@ckb-lumos/lumos` to connect to a CKB RPC and Indexer, collect cells associated with a specific lock script, and calculate the total CKB balance. It utilizes the `Indexer` and `BI` (BigInt) classes for network interaction and large number arithmetic. ```ts import { Script, Indexer, BI } from "@ckb-lumos/lumos" async function main(): Promise { const lock = { code_hash: "0x...", hash_type: "type", args: "0x..." } const CKB_RPC_URL = "https://testnet.ckb.dev/rpc" const CKB_INDEXER_URL = "https://testnet.ckb.dev/indexer" const indexer = new Indexer(CKB_INDEXER_URL, CKB_RPC_URL) const collector = indexer.collector({ lock }) let balance: BI = BI.from(0) for await (const cell of collector.collect()) { balance = balance.add(cell.cell_output.capacity) } return balance } main() ``` -------------------------------- ### Performing Prefix Search on Script Arguments (JavaScript) Source: https://github.com/ckb-js/lumos/blob/develop/packages/ckb-indexer/README.md This example demonstrates how to perform a prefix search on script arguments using the `argsLen` option. By providing a truncated `args` value and setting `argsLen` to the desired prefix length, the `CellCollector` can find cells whose script arguments start with the specified prefix. ```jsx cellCollector = new CellCollector(indexer, { lock: { code_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hash_type: "type", args: "0xa528f2b9a51118b193178db4cf2f3db92e7df3", // truncate the last byte of orignal args: 0xa528f2b9a51118b193178db4cf2f3db92e7df323 }, argsLen: 20, // default option is -1 fromBlock: "0x253b40", // "0x" + 2440000n.toString(16) toBlock: "0x253f28", // "0x" + 2441000n.toString(16) order: "desc", // default option is "asc" skip: 300, }); for await (const cell of cellCollector.collect()) { console.log(cell); } ``` -------------------------------- ### SUDT Transaction Example with Lumos in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-from-ckb-sdk-core.md This comprehensive example demonstrates how to perform SUDT (Simple User Defined Token) operations using the Lumos library. It covers initializing the Lumos configuration, generating SECP256K1 accounts, issuing new SUDT tokens, and transferring existing SUDT tokens between addresses. It utilizes `TransactionSkeleton` for transaction building and `commons` for common operations like `issueToken`, `transfer`, and `payFee`. ```TypeScript import { config, Indexer, RPC, hd, commons } from "@ckb-lumos/lumos" import { TransactionSkeleton, encodeToAddress, sealTransaction } from "@ckb-lumos/helpers" const CKB_RPC_URL = "https://testnet.ckb.dev/rpc" const CKB_INDEXER_URL = "https://testnet.ckb.dev/indexer" const rpc = new RPC(CKB_RPC_URL) const indexer = new Indexer(CKB_INDEXER_URL, CKB_RPC_URL) const CONFIG = config.createConfig({ PREFIX: "ckt", SCRIPTS: { ...config.predefined.AGGRON4.SCRIPTS, ANYONE_CAN_PAY: { CODE_HASH: "0x3419a1c09eb2567f6552ee7a8ecffd64155cffe0f1796e6e61ec088d740c1356", HASH_TYPE: "type", TX_HASH: "0xec26b0f85ed839ece5f11c4c4e837ec359f5adc4420410f6453b1f6b60fb96a6", INDEX: "0x0", DEP_TYPE: "code" } } }) config.initializeConfig(CONFIG) export const generateSECP256K1Account = (privKey: string) => { const pubKey = hd.key.privateToPublic(privKey) const args = hd.key.publicKeyToBlake160(pubKey) const template = CONFIG.SCRIPTS["SECP256K1_BLAKE160"]! const lockScript = { codeHash: template.CODE_HASH, hashType: template.HASH_TYPE, args: args } const address = encodeToAddress(lockScript, { config: CONFIG }) return { lockScript, address, pubKey, privKey } } export const issueToken = async (fromAddress: string, privKey: string) => { let txSkeleton = TransactionSkeleton({ cellProvider: indexer }) txSkeleton = await commons.sudt.issueToken(txSkeleton, fromAddress, BigInt(10000)) txSkeleton = await commons.secp256k1Blake160.payFee(txSkeleton, fromAddress, BigInt(1 * 10 ** 8)) txSkeleton = commons.common.prepareSigningEntries(txSkeleton) const message = txSkeleton.get("signingEntries").get(0)?.message const Sig = hd.key.signRecoverable(message!, privKey) const tx = sealTransaction(txSkeleton, [Sig]) const hash = await rpc.sendTransaction(tx, "passthrough") return hash } export const transferToken = async (fromAddress: string, toAddress: string, privKey: string) => { const token = commons.sudt.ownerForSudt(fromAddress) let txSkeleton = TransactionSkeleton({ cellProvider: indexer }) txSkeleton = await commons.sudt.transfer(txSkeleton, [fromAddress], token, toAddress, BigInt(1000)) txSkeleton = await commons.secp256k1Blake160.payFee(txSkeleton, fromAddress, BigInt(1 * 10 ** 8)) txSkeleton = commons.common.prepareSigningEntries(txSkeleton) const message = txSkeleton.get("signingEntries").get(0)?.message const Sig = hd.key.signRecoverable(message!, privKey) const tx = sealTransaction(txSkeleton, [Sig]) const hash = await rpc.sendTransaction(tx, "passthrough") return hash } const bootstrap = async () => { const alice = generateSECP256K1Account("0xd00c06bfd800d27397002dca6fb0993d5ba6399b4238b2f29ee9deb97593d2bc") const bob = generateSECP256K1Account("0x63d86723e08f0f813a36ce6aa123bb2289d90680ae1e99d4de8cdb334553f24d") const issueTxHash = await issueToken(bob.address, bob.privKey) console.log("issueTxHash is", issueTxHash) // Wait a minute. const transferTxHash = await transferToken(alice.address, bob.address, alice.privKey) console.log("transferTxHash is", transferTxHash) } bootstrap() ``` -------------------------------- ### Initializing CKB Indexer in JavaScript/JSX Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/01-run-lumos-in-the-browser.md This JavaScript/JSX snippet shows how to initialize the `@ckb-lumos/ckb-indexer` in a browser environment. It specifies the URIs for the CKB Indexer and Node RPC, providing the necessary setup for interacting with the CKB blockchain from a web application. ```jsx const { Indexer } = require("@ckb-lumos/ckb-indexer") const nodeUri = "https://testnet.ckb.dev/rpc" const indexUri = "https://testnet.ckb.dev/indexer" const indexer = new Indexer(indexUri, nodeUri) ``` -------------------------------- ### Example: Checking Alice's SUDT Balance in Lumos (TypeScript) Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md This snippet demonstrates how to use the getTokenAmount function to check a user's SUDT balance. It initializes privateKey, issuerAddress, and aliceAddress, then computes the scriptLockHash for the SUDT args and calls getTokenAmount to log Alice's balance. ```TypeScript import { utils } from '@ckb-lumos/lumos'; const privateKey = '0x9ab62c912c48d615a030318af514758e8c7b9f03d37a95dd1b89e775b669e0c3'; const issuerAddress = getAddressByPrivateKey(privateKey); const aliceAddress = 'ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsq2x0z0rmc44ek25rmdk7dky5wnhdlrmqncyhcvkp'; const scriptLockHash = utils.computeScriptHash(helpers.parseAddress(issuerAddress)) getTokenAmount(aliceAddress, scriptLockHash).then((v) => {console.log('SUDT balance:', v.toString())}) ``` -------------------------------- ### Initializing LightClientRPC and Getting Tip Header (TypeScript) Source: https://github.com/ckb-js/lumos/blob/develop/packages/light-client/README.md This snippet demonstrates how to initialize the `LightClientRPC` instance by providing the light client's RPC endpoint. It then calls the `getTipHeader()` method to retrieve the current tip header of the CKB blockchain, logging the result to the console. This requires the `@ckb-lumos/light-client` package. ```TypeScript import { LightClientRPC } from "@ckb-lumos/light-client"; const lightClientRPC = new LightClientRPC("http://localhost:9000"); lightClientRPC.getTipHeader().then(console.log); ``` -------------------------------- ### Starting CKB Mock RPC Server (Shell) Source: https://github.com/ckb-js/lumos/blob/develop/packages/testkit/README.md This command initiates a mock CKB RPC server by executing the `example-ckb-nodes.ts` script using `ts-node`. It simulates a CKB node, typically listening on port 8118, providing a local environment for dApp testing without requiring a full CKB node. This server acts as the data source for the CKB indexer. ```Shell ts-node packages/testkit/example-ckb-nodes.ts ``` -------------------------------- ### Creating Cell with Minimal Capacity using Lumos Source: https://github.com/ckb-js/lumos/blob/develop/packages/experiment-tx-assembler/README.md This example showcases the `createCellWithMinimalCapacity` function, which automatically calculates and assigns the minimum required capacity for a new cell based on its lock script. This simplifies cell creation by removing the need for manual capacity calculation. ```ts const lock: Script = { codeHash: "0x79f90bb5e892d80dd213439eeab551120eb417678824f282b4ffb5f21bad2e1e", hashType: "type", args: "0x01a08bcc398854db4eaffd9c28b881c65f91e3a28b00" }; const cell = createCellWithMinimalCapacity({ lock: lock }); ``` -------------------------------- ### Managing HD Cache and Collecting Cells with Lumos in JavaScript Source: https://github.com/ckb-js/lumos/blob/develop/packages/hd-cache/README.md This snippet demonstrates how to initialize `CacheManager` from a keystore, start syncing cache data from an indexer, and retrieve HD wallet public key information. It also shows how to use `CellCollector` and `CellCollectorWithQueryOptions` to iterate over cells and calculate the total balance. Dependencies include `@ckb-lumos/hd-cache` and `@ckb-lumos/ckb-indexer`. ```javascript const { CacheManager, CellCollector, CellCollectorWithQueryOptions, getBalance, } = require("@ckb-lumos/hd-cache"); const { Indexer } = require("@ckb-lumos/ckb-indexer"); const indexer = new Indexer("http://localhost:8114"); const cacheManger = CacheManager.loadFromKeystore( indexer, "You keystore path", "You password" ); // start to sync cache from indexer cacheManager.startForever(); // if your keystore is from ckb-cli or you set needMasterPublicKey to true, you can get you master public key info by cacheManager.getMasterPublicKeyInfo(); // ckb-cli using this key by default // now you can using following methods cacheManager.getNextReceivingPublicKeyInfo(); cacheManager.getNextChangePublicKeyInfo(); // or collect cells by CellCollectors const cellCollector = new CellCollector(cacheManager); // or with queryOptions const cellCollector = new CellCollectorWithQueryOptions( new CellCollector(cacheManger), queryOptions ); for await (const cell of cellCollector.collect()) { console.log(cell); } // get HD wallet balance await getBalance(cellCollector); ``` -------------------------------- ### Handling Batch RPC Requests - Diff Source: https://github.com/ckb-js/lumos/blob/develop/packages/ckb-indexer/mirgation.md This `diff` snippet shows the updated method for obtaining a `batchRpc` object. Since the indexer no longer exposes RPC directly, users must now import `RPC` from `@ckb-lumos/toolkit` and create a new `RPC` instance with the `URL` to access the `batch()` method. ```Diff import {RPC} from '@ckb-lumos/toolkit'; ... -batchRpc = indexer.rpc.batch(); +batchRpc = new PRC(URL).batch() ... ``` -------------------------------- ### Initializing CellCollector with Block Hash - JSX Source: https://github.com/ckb-js/lumos/blob/develop/packages/ckb-indexer/mirgation.md This snippet demonstrates how to initialize a `CellCollector` instance to include `blockHash` in the returned cell data. It requires passing an `otherQueryOptions` object with `withBlockHash` set to `true` and `ckbRpcUrl` to the constructor, along with the `indexer` instance and query parameters like `lock`. ```JSX const otherQueryOptions: OtherQueryOptions = { withBlockHash: true, ckbRpcUrl: nodeUri, }; const cellCollector = new CellCollector( indexer, { lock: type } otherQueryOptions ); ``` -------------------------------- ### Serializing Dynamic Vectors with Lumos Codec in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-form-ckb-sdk-utils.md This snippet demonstrates how to serialize a dynamic vector of byte strings. The 'before' example uses `serializeDynVec` from `ckb-sdk-utils`, while the 'after' example utilizes `dynvec` and `createBytesCodec` from `@ckb-lumos/codec` to achieve the same result with a more structured codec approach. It highlights the process of defining a codec for the vector's elements. ```TypeScript import { serializeDynVec } from "@nervosnetwork/ckb-sdk-utils" import { dynvec } from "@ckb-lumos/codec/lib/molecule/layout" import { bytes, createBytesCodec } from "@ckb-lumos/codec" // before serializeDynVec([]) // 0x04000000 serializeDynVec(["0x02001234"]) // 0x0c0000000800000002001234 serializeDynVec(["0x02001234", "0x00000000", "0x02000567", "0x01000089", "0x0300abcdef"]) // 0x2d000000180000001c000000200000002400000028000000020012340000000002000567010000890300abcdef ``` ```TypeScript import { serializeDynVec } from "@nervosnetwork/ckb-sdk-utils" import { dynvec } from "@ckb-lumos/codec/lib/molecule/layout" import { bytes, createBytesCodec } from "@ckb-lumos/codec" // after const bytesCodec = createBytesCodec({ pack: (hex) => bytes.bytify(hex), unpack: (buf) => bytes.hexify(buf), }) const dynvecCodec = dynvec(bytesCodec) bytes.hexify(dynvecCodec.pack([])) // 0x00000000 bytes.hexify(dynvecCodec.pack(["0x02001234"])) // 0x0c0000000800000002001234 bytes.hexify(dynvecCodec.pack(["0x02001234", "0x00000000", "0x02000567", "0x01000089", "0x0300abcdef"])) // 0x2d000000180000001c000000200000002400000028000000020012340000000002000567010000890300abcdef ``` -------------------------------- ### Creating Input Cell with Lumos `createCell` Source: https://github.com/ckb-js/lumos/blob/develop/packages/experiment-tx-assembler/README.md This example illustrates how to construct an input cell for a CKB transaction using the `createCell` function. It requires defining the cell's lock script, capacity, and an `outPoint` to reference an existing unspent transaction output. ```ts const lock: Script = { codeHash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", args: "0x159890a7cacb44a95bef0743064433d763de229c", hashType: "type" }; const outPoint = { txHash: "0x942c23f72f0a2558a0029522b1dea2a7c64ba5196aed829ab6bfe4b6c3270958", index: "0x0" }; const cell = createCell({ lock: lock, capacity: BI.from("10000000000"), outPoint: outPoint }); ``` -------------------------------- ### Serializing Molecule Tables with Lumos Codec in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-form-ckb-sdk-utils.md This snippet demonstrates the serialization of Molecule tables. The 'before' example uses `serializeTable` from `ckb-sdk-utils` with a Map, while the 'after' example leverages the `table` codec from `@ckb-lumos/codec`. The new approach requires defining the structure of the table with specific codecs for each field, providing better type safety and clarity. ```TypeScript import { serializeTable } from "@nervosnetwork/ckb-sdk-utils" import { table } from "@ckb-lumos/codec/lib/molecule/layout" import { bytes, number, createBytesCodec } from "@ckb-lumos/codec" // before serializeTable( new Map([ ["f1", "0xab"], ["f2", "0x04030201"], ]) ) // 0x110000000c0000000d000000ab04030201 ``` ```TypeScript import { serializeTable } from "@nervosnetwork/ckb-sdk-utils" import { table } from "@ckb-lumos/codec/lib/molecule/layout" import { bytes, number, createBytesCodec } from "@ckb-lumos/codec" // after const bytesCodec = createBytesCodec({ pack: (hex) => bytes.bytify(hex), unpack: (buf) => bytes.hexify(buf), }) const tableCodec = table({ f1: bytesCodec, f2: bytesCodec }, ["f1", "f2"]) bytes.hexify(tableCodec.pack({ f1: "0xab", f2: "0x04030201" })) // 0x110000000c0000000d000000ab04030201 ``` -------------------------------- ### Serializing CKB Script Arguments with Lumos Base in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-form-ckb-sdk-utils.md This snippet demonstrates the serialization of CKB script arguments. The 'before' example uses `serializeArgs` from `ckb-sdk-utils`, while the 'after' example utilizes `blockchain.Bytes.pack` from `@ckb-lumos/base`. This migration standardizes argument serialization using the generic `Bytes` type provided by Lumos. ```TypeScript import { serializeArgs } from "@nervosnetwork/ckb-sdk-utils" import { blockchain } from "@ckb-lumos/base" import { bytes } from "@ckb-lumos/codec" const args = "0x8536c9d5d908bd89fc70099e4284870708b6632356aad98734fcf43f6f71c304" // before serializeArgs(args) // 0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88 ``` ```TypeScript import { serializeArgs } from "@nervosnetwork/ckb-sdk-utils" import { blockchain } from "@ckb-lumos/base" import { bytes } from "@ckb-lumos/codec" const args = "0x8536c9d5d908bd89fc70099e4284870708b6632356aad98734fcf43f6f71c304" // after bytes.hexify(blockchain.Bytes.pack(args)) // 0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88 ``` -------------------------------- ### Starting New Prerelease Cycle - Changesets CLI - Shell Source: https://github.com/ckb-js/lumos/blob/develop/docs/DEVELOPMENT.md This shell command is used by administrators to initiate a new prerelease cycle for the Lumos project. Executing `npx changeset pre enter next` prepares the repository to publish 'next' versions, allowing for testing of upcoming features before a stable release. ```sh npx changeset pre enter next ``` -------------------------------- ### Serializing CKB Hash Types with Lumos Base in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-form-ckb-sdk-utils.md This snippet demonstrates the serialization of CKB script hash types ('data' or 'type'). The 'before' example uses `serializeHashType` from `ckb-sdk-utils`, while the 'after' example utilizes `blockchain.HashType.pack` from `@ckb-lumos/base`. This change aligns with Lumos's structured representation of blockchain primitives. ```TypeScript import { serializeHashType } from "@nervosnetwork/ckb-sdk-utils" import { blockchain } from "@ckb-lumos/base" import { bytes } from "@ckb-lumos/codec" // before serializeHashType("data") // 0x00 serializeHashType("type") // 0x01 ``` ```TypeScript import { serializeHashType } from "@nervosnetwork/ckb-sdk-utils" import { blockchain } from "@ckb-lumos/base" import { bytes } => "@ckb-lumos/codec" // after bytes.hexify(blockchain.HashType.pack("data")) // 0x00 bytes.hexify(blockchain.HashType.pack("type")) // 0x01 ``` -------------------------------- ### Serializing Optional Values with Lumos Codec in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-form-ckb-sdk-utils.md This snippet demonstrates how to serialize optional values, which can either be present or absent. The 'before' example uses `serializeOption` from `ckb-sdk-utils`, while the 'after' example utilizes the `option` codec from `@ckb-lumos/codec`. This new approach allows for explicit definition of the optional type and its underlying codec. ```TypeScript import { serializeOption } from "@nervosnetwork/ckb-sdk-utils" import { option } from "@ckb-lumos/codec/lib/molecule/layout" import { bytes, createBytesCodec } from "@ckb-lumos/codec" // before serializeOption() // 0x serializeOption("0x") // 0x serializeOption("0x0c0000000800000000000000") // 0x0c0000000800000000000000 ``` ```TypeScript import { serializeOption } from "@nervosnetwork/ckb-sdk-utils" import { option } from "@ckb-lumos/codec/lib/molecule/layout" import { bytes, createBytesCodec } from "@ckb-lumos/codec" // after const bytesCodec = createBytesCodec({ pack: (hex) => bytes.bytify(hex), unpack: (buf) => bytes.hexify(buf), }) const optionCodec = option(bytesCodec) bytes.hexify(optionCodec.pack()) // 0x bytes.hexify(optionCodec.pack("0x")) // 0x bytes.hexify(optionCodec.pack("0x0c0000000800000000000000")) // 0x0c0000000800000000000000 ``` -------------------------------- ### Serializing CKB Code Hashes with Lumos Base in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-form-ckb-sdk-utils.md This snippet demonstrates the serialization of a CKB code hash. The 'before' example uses `serializeCodeHash` from `ckb-sdk-utils`, while the 'after' example utilizes `blockchain.Byte32.pack` from `@ckb-lumos/base`. This change promotes the use of specific blockchain types for serialization, ensuring consistency with CKB's data structures. ```TypeScript import { serializeCodeHash } from "@nervosnetwork/ckb-sdk-utils" import { blockchain } from "@ckb-lumos/base" import { bytes } from "@ckb-lumos/codec" const hash = "0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88" // before serializeCodeHash(hash) // 0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88 ``` ```TypeScript import { serializeCodeHash } from "@nervosnetwork/ckb-sdk-utils" import { blockchain } from "@ckb-lumos/base" import { bytes } from "@ckb-lumos/codec" const hash = "0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88" // after bytes.hexify(blockchain.Byte32.pack(hash)) // 0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88 ``` -------------------------------- ### Serializing CKB Scripts with Lumos Base in TypeScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-form-ckb-sdk-utils.md This snippet demonstrates the serialization of a complete CKB script object. The 'before' example uses `serializeScript` from `ckb-sdk-utils`, while the 'after' example utilizes `blockchain.Script.pack` from `@ckb-lumos/base`. This migration centralizes script serialization within the Lumos `blockchain` module, providing a consistent and type-safe way to handle CKB script structures. ```TypeScript import { serializeScript } from "@nervosnetwork/ckb-sdk-utils" import { blockchain } from "@ckb-lumos/base" import { bytes } from "@ckb-lumos/codec" // before serializeScript({ codeHash: "0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88", args: "0x3954acece65096bfa81258983ddb83915fc56bd8", hashType: "type", }) // 0x4900000010000000300000003100000068d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e8801140000003954acece65096bfa81258983ddb83915fc56bd8 ``` ```TypeScript import { serializeScript } from "@nervosnetwork/ckb-sdk-utils" import { blockchain } from "@ckb-lumos/base" import { bytes } from "@ckb-lumos/codec" // after bytes.hexify( blockchain.Script.pack({ codeHash: "0x68d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e88", args: "0x3954acece65096bfa81258983ddb83915fc56bd8", hashType: "type", }) ) // 0x4900000010000000300000003100000068d5438ac952d2f584abf879527946a537e82c7f3c1cbf6d8ebf9767437d8e8801140000003954acece65096bfa81258983ddb83915fc56bd8 ``` -------------------------------- ### Updating TransactionCollector Constructor - Diff Source: https://github.com/ckb-js/lumos/blob/develop/packages/ckb-indexer/mirgation.md This `diff` snippet highlights a change in the `TransactionCollector` constructor. A new `nodeUri` parameter is introduced as the third argument, shifting the original `options` parameter to the fourth position. This update is crucial for adapting to the new constructor signature. ```Diff const transactionCollector = new TransactionCollector( indexer, query, + nodeUri, options ); ``` -------------------------------- ### Converting TransactionSkeleton to/from JavaScript Objects (JavaScript) Source: https://github.com/ckb-js/lumos/blob/develop/packages/helpers/README.md This snippet shows how to convert a `TransactionSkeleton` object to a plain JavaScript object using `transactionSkeletonToObject` and vice-versa using `objectToTransactionSkeleton`. It also provides an example of how to serialize the resulting object to a JSON file. When converting from an object back to `TransactionSkeleton`, it's crucial to ensure `cellProvider` is properly configured if the object originated from a JSON file. ```javascript // Convert TransactionSkeleton to js object const obj = transactionSkeletonToObject(txSkeleton); // then your can write to json file fs.writeFileSync("your file", JSON.stringify(obj)); // Or convert js object to TransactionSkeleton // If your object is from json file, make sure `cellProvider` is working properly. const txSkeleton = objectToTransactionSkeleton(obj); ``` -------------------------------- ### Collecting Live Cells with RPCCollector in CKB-JS Source: https://github.com/ckb-js/lumos/blob/develop/packages/toolkit/README.md This example demonstrates how to use the `RPCCollector` from `ckb-js-toolkit` within a Node.js REPL environment to query and retrieve live cells from a CKB node. It initializes an RPC client, creates a collector instance with a specific lock script hash, and then iterates asynchronously over the collected cells, printing their details. ```JavaScript node --experimental-repl-await Welcome to Node.js v13.9.0. Type ".help" for more information. > const toolkit = require("ckb-js-toolkit"); undefined > const rpc = new toolkit.RPC("http://127.0.0.1:9115/rpc") undefined > const collector = new toolkit.cell_collectors.RPCCollector(rpc, "0x7c7232c0af4a7261674a45e14916f926ecec64b911f539e573fb4bb7817d001e") undefined > for await (const cell of collector.collect()) { console.log(cell); } { cell_output: { capacity: '0x3faa252260000', lock: { args: '0xfa3afa2134319f9471cf21024f032831bc4651ad', code_hash: '0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8', hash_type: 'type' }, type: null }, out_point: { index: '0x7', tx_hash: '0xe2fb199810d49a4d8beec56718ba2593b665db9d52299a0f9e6e75416d73ff5c' }, block_hash: '0x92b197aa1fba0f63633922c61c92375c9c074a93e85963554f5499fe1450d0e5', data: null, block_number: '0x0' } ``` -------------------------------- ### Using `cellHelper` to Create CKB Cells in JavaScript Source: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-to-v0.23.md This snippet demonstrates how to use `cellHelper.create` from `@ckb-lumos/helpers` to construct a CKB cell object with a specified lock. It also illustrates how to assert the cell's capacity using `BI.from` for BigInt comparisons, ensuring the cell's value is correctly set to 61 CKB. ```JavaScript import { cellHelper } from "@ckb-lumos/helpers" const cell = cellHelper.create({ lock: "ckb1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqgqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq5m759c" }) const _61CKB = 61 * 10 ** 8 asserts(BI.from(cell.cellOutput.capacity).eq(_61CKB)) // 61 CKB ```