TITLE: Initializing Lumos Configuration and Importing Modules DESCRIPTION: This snippet imports necessary modules from @ckb-lumos packages, including common scripts, indexer, config manager, and helpers. It then initializes the Lumos configuration to use the AGGRON4 predefined network, which is crucial for subsequent operations. SOURCE: https://github.com/ckb-js/lumos/blob/develop/packages/common-scripts/README.md#_snippet_3 LANGUAGE: JavaScript CODE: ``` const { generateDeployWithDataTx, generateDeployWithTypeIdTx, generateUpgradeTypeIdDataTx, payFee } = require("@ckb-lumos/common-scripts"); const { Indexer } = require("@ckb-lumos/ckb-indexer"); const { initializeConfig, predefined } = require("@ckb-lumos/config-manager"); const { parseAddress } = require("@ckb-lumos/helpers"); initializeConfig(predefined.AGGRON4); ``` ---------------------------------------- TITLE: Installing Lumos Package with npm DESCRIPTION: 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. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/01-run-lumos-in-the-browser.md#_snippet_0 LANGUAGE: shell CODE: ``` npm install @ckb-lumos/lumos ``` ---------------------------------------- TITLE: Complete CKB Wallet Functions with Lumos (TypeScript) DESCRIPTION: This comprehensive snippet provides a full set of wallet functionalities using Lumos, including generating HD private keys, deriving addresses from private keys, querying CKB capacities (balance), and executing a complete CKB transfer transaction. It integrates the steps for building, fee payment, signing, and sending transactions into a single `transfer` function, demonstrating a practical wallet implementation. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md#_snippet_15 LANGUAGE: TypeScript CODE: ``` import { BI, hd, config, helpers, RPC, Indexer, commons, Address, HexString } from '@ckb-lumos/lumos'; const { mnemonic, ExtendedPrivateKey } = hd; config.initializeConfig(config.predefined.AGGRON4); 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); export const generateFirstHDPrivateKey = () => { const m = mnemonic.generateMnemonic() const seed = mnemonic.mnemonicToSeedSync(m) console.log('my mnemonic ', seed); const extendedPrivKey = ExtendedPrivateKey.fromSeed(seed); return extendedPrivKey.privateKeyInfo( AddressType.Receving, 0, ).privateKey } const getAddressByPrivateKey = (privateKey: string) => { const args = hd.key.privateKeyToBlake160(privateKey); const template = config.predefined.AGGRON4.SCRIPTS["SECP256K1_BLAKE160"]!; const lockScript = { codeHash: template.CODE_HASH, hashType: template.HASH_TYPE, args: args, }; return helpers.encodeToAddress(lockScript); } export async function getCapacities(address: string): Promise { const collector = indexer.collector({ lock: helpers.parseAddress(address), }); let capacities = BI.from(0); for await (const cell of collector.collect()) { capacities = capacities.add(cell.cellOutput.capacity); } return capacities; } const transfer = async(from: Address, to: Address, capacity: number, privateKey: HexString) => { let txSkeleton = helpers.TransactionSkeleton({ cellProvider: indexer }); txSkeleton = await commons.common.transfer( txSkeleton, [from], to, BigInt(capacity), ); txSkeleton = await commons.common.payFeeByFeeRate( txSkeleton, [from], 1000, ); txSkeleton = commons.common.prepareSigningEntries(txSkeleton); const message = txSkeleton.get("signingEntries").get(0)?.message; const Sig = hd.key.signRecoverable(message!, privateKey); const tx = helpers.sealTransaction(txSkeleton, [Sig]); return rpc.sendTransaction(tx, "passthrough"); } // input your privateKey or generate a new privateKey const privateKey = `0x9ab62c912c48d615a030318af514758e8c7b9f03d37a95dd1b89e775b669e0c3` const address = getAddressByPrivateKey(privateKey); const bobAddress = 'ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqgy5rtexzvhk7jt7gla8wlq5lztf79tjhg9fmd4f' console.log('address: ', address) getCapacities(address).then(capacities => console.log(`balance: ${capacities.div(10 ** 8).toString()} CKB`)) ``` ---------------------------------------- TITLE: Transferring CKB Capacity with Lumos Common Script (JavaScript) DESCRIPTION: This snippet demonstrates how to use the `common.transfer` function to send CKB capacity to another address, including handling locktime cells and paying transaction fees with `common.payFee`. It also shows how to prepare signing entries using `common.prepareSigningEntries` and seal the transaction. SOURCE: https://github.com/ckb-js/lumos/blob/develop/packages/common-scripts/README.md#_snippet_0 LANGUAGE: JavaScript CODE: ``` const { common } = require('@ckb-lumos/common-scripts'); const { sealTransaction } = require("@ckb-lumos/helpers") const { Indexer } = require("@ckb-lumos/ckb-indexer") // We can use Indexer module as cell provider const indexer = new Indexer("http://127.0.0.1:8114"); const tipHeader = { compactTarget: '0x20010000', dao: '0x49bfb20771031d556c8480d47f2a290059f0ac7e383b6509006f4a772ed50200', epoch: '0xa0006002b18', hash: '0x432451e23c26f45eaceeedcc261764d6485ea5c9a204ac55ad755bb8dec9a079', nonce: '0x8199548f8a5ac7a0f0caef1620f37b79', number: '0x1aef6', parentHash: '0x63594a64108f19f6aed53d0dca9ab4075aac4379cb80b2097b0deac8fc16fd3b', proposalsHash: '0x0000000000000000000000000000000000000000000000000000000000000000', timestamp: '0x172f6b9a4cf', transactions_root: '0x282dbadcd49f3e229d997875f37f4e4f19cb4f04fcf762e9639145aaa667b6f8', extra_hash: '0x0000000000000000000000000000000000000000000000000000000000000000', version: '0x0' } const fromInfos = [ "ckb1qyqwyxfa75whssgkq9ukkdd30d8c7txct0gq5f9mxs", { R: 0, M: 1, publicKeyHashes: ["0x36c329ed630d6ce750712a477543672adab57f4c"], }, ] let txSkeleton = TransactionSkeleton({ cellProvider: indexer }) // If using secp256k1_blake160_multisig lock script, put MultisigScript to `fromInfos` for generate signing messages. // By default, `common.transfer` will use cells with locktime firstly. `tipHeader` is required when you want to spent cells with locktime. txSkeleton = await common.transfer( txSkeleton, fromInfos, "ckb1qyqrdsefa43s6m882pcj53m4gdnj4k440axqdt9rtd", BigInt(3500 * 10 ** 8), tipHeader, ) // Or you want to use cells without locktime firstly. txSkeleton = await common.transfer( txSkeleton, fromInfos, "ckb1qyqrdsefa43s6m882pcj53m4gdnj4k440axqdt9rtd", BigInt(3500 * 10 ** 8), tipHeader, { useLocktimeCellsFirst: false } ) // When you want to pay fee for transaction, just call `payFee`. txSkeleton = await common.payFee( txSkeleton, fromInfos, BigInt(1*10**8), tipHeader, ) // `prepareSigningEntries` will generate message for signing. // Signing messages will fill in `txSkeleton.signingEntries`. txSkeleton = await common.prepareSigningEntries( txSkeleton ) // Then you can sign messages in order and get contents. // NOTE: lumos not provided tools for generate signatures now. // Call `sealTransaction` to get a transaction. const tx = sealTransaction(txSkeleton, contents) // Then you can send tx to a CKB node via RPC `send_transaction`. ``` ---------------------------------------- TITLE: Sending Simple Transaction - Lumos - TypeScript DESCRIPTION: This snippet demonstrates how to construct and send a simple CKB transaction using Lumos. It initializes the Lumos configuration, generates SECP256K1 accounts, creates a transaction skeleton, transfers CKB, pays transaction fees, signs the transaction, and finally sends it to the CKB network. It requires `@ckb-lumos/lumos` and `@ckb-lumos/helpers` dependencies. Inputs include private keys for sender and receiver, and the transfer amount. The output is the transaction hash. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-from-ckb-sdk-core.md#_snippet_0 LANGUAGE: TypeScript CODE: ``` import { Script, Address, 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, } } const bootstrap = async () => { const alice = generateSECP256K1Account("0xd00c06bfd800d27397002dca6fb0993d5ba6399b4238b2f29ee9deb97593d2bc") const bob = generateSECP256K1Account("0x63d86723e08f0f813a36ce6aa123bb2289d90680ae1e99d4de8cdb334553f24d") let txSkeleton = TransactionSkeleton({ cellProvider: indexer }) txSkeleton = await commons.secp256k1Blake160.transfer(txSkeleton, alice.address, bob.address, BigInt(1000 * 10 ** 8)) txSkeleton = await commons.secp256k1Blake160.payFee(txSkeleton, alice.address, BigInt(1 * 10 ** 8), { config: CONFIG, }) txSkeleton = commons.common.prepareSigningEntries(txSkeleton) const message = txSkeleton.get("signingEntries").get(0)?.message const Sig = hd.key.signRecoverable(message!, alice.privKey) const tx = sealTransaction(txSkeleton, [Sig]) const hash = await rpc.sendTransaction(tx, "passthrough") console.log("The transaction hash is", hash) } bootstrap() ``` ---------------------------------------- TITLE: SUDT Transaction Example with Lumos in TypeScript DESCRIPTION: 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`. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/migrations/migrate-from-ckb-sdk-core.md#_snippet_1 LANGUAGE: TypeScript CODE: ``` 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() ``` ---------------------------------------- TITLE: Initializing CKB Lumos Configuration (TypeScript) DESCRIPTION: This snippet demonstrates how to initialize the global CKB Lumos configuration using predefined network settings. Initializing the configuration is a prerequisite for many Lumos operations, such as address encoding, as it sets the context for network-specific parameters. SOURCE: https://github.com/ckb-js/lumos/blob/develop/packages/config-manager/README.md#_snippet_0 LANGUAGE: TypeScript CODE: ``` import { initializeConfig, predefined } from "@ckb-lumos/config-manager" // or import from the entry package import { initializeConfig, predefined } from "@ckb-lumos/lumos/config" import { encodeToAddress } from '@ckb-lumos/helper' initializeConfig(predefined.AGGRON); encodeToAddress({...}) // ckt1... initializeConfig(predefined.LINA); encodeToAddress({...}) // ckb1... ``` ---------------------------------------- TITLE: Packing and Unpacking UDTInfo Struct with Lumos Codec DESCRIPTION: This snippet demonstrates how to define and use a Molecule `struct` binding for `UDTInfo` using `@ckb-lumos/codec`. It shows the creation of the `UDTInfo` codec with `struct`, followed by examples of packing a JavaScript object into a `Uint8Array` and unpacking a `Uint8Array` back into a JavaScript object. It requires `struct`, `Uint8`, `Uint128` from `@ckb-lumos/codec` and `BI` for BigInt operations. SOURCE: https://github.com/ckb-js/lumos/blob/develop/packages/codec/README.md#_snippet_0 LANGUAGE: typescript CODE: ``` import { struct, Uint8, Uint128 } from "@ckb-lumos/codec"; // udt-info.mol // struct UDTInfo { // total_supply: Uint128, // decimals: Uint8, // } // array Uint8 [byte; 1]; // array Uint128 [byte; 16]; // 1. create molecule binding const UDTInfo /*: Codec */ = struct( { totalSupply: Uint128, decimals: Uint8, }, ["totalSupply", "decimals"] ); // 2. usage // 2.1 pack const buf /*: Uint8Array*/ = UDTInfo.pack({ totalSupply: BI.from(21000000 * 10 ** 8), decimals: 8, }); // 2.2 unpack const udtInfo = UDTInfo.unpack(buf); // { totalSupply: BI(21000000 * 10 ** 8), decimals: 8 } ``` ---------------------------------------- TITLE: Building a CKB Transfer Transaction with Lumos (TypeScript) DESCRIPTION: This snippet initializes a transaction skeleton and uses Lumos's `common.transfer` method to add a CKB transfer operation. It specifies the sender's address, the recipient's address (Bob's), and the amount of CKB to transfer (100 CKB, converted to shannons). This is the first step in constructing a payment transaction. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md#_snippet_12 LANGUAGE: TypeScript CODE: ``` import { helpers, commons } from '@ckb-lumos/lumos'; let txSkeleton = helpers.TransactionSkeleton({ cellProvider: indexer }); txSkeleton = await commons.common.transfer( txSkeleton, [''], 'ckt1qzda0cr08m85hc8jlnfp3zer7xulejywt49kt2rr0vthywaa50xwsqgy5rtexzvhk7jt7gla8wlq5lztf79tjhg9fmd4f', BigInt(100 * 10 ** 8), ); ``` ---------------------------------------- TITLE: Initializing Lumos Network Configuration (TypeScript) DESCRIPTION: This snippet initializes the Lumos configuration to use the `AGGRON4` testnet. This step is crucial for Lumos to correctly interact with the CKB blockchain, ensuring that subsequent operations use the correct network parameters. It depends on the `config` module from `@ckb-lumos/lumos`. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md#_snippet_6 LANGUAGE: TypeScript CODE: ``` import { config } from '@ckb-lumos/lumos'; // this tutorial will use the testnet. config.initializeConfig(config.predefined.AGGRON4); ``` ---------------------------------------- TITLE: Signing and Broadcasting a CKB Transaction with Lumos (TypeScript) DESCRIPTION: This snippet finalizes the transaction by preparing signing entries, signing the transaction message with a private key, and sealing the transaction. Finally, it uses the RPC client to send the signed transaction to the CKB network, logging the resulting transaction hash. This is the last step to submit the transaction for processing. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md#_snippet_14 LANGUAGE: TypeScript CODE: ``` import { BI, hd, config, helpers, RPC, Indexer, commons } from '@ckb-lumos/lumos'; txSkeleton = commons.common.prepareSigningEntries(txSkeleton); const message = txSkeleton.get("signingEntries").get(0)?.message; const Sig = hd.key.signRecoverable(message!, privateKey); const tx = helpers.sealTransaction(txSkeleton, [Sig]); const txHash = await rpc.sendTransaction(tx, "passthrough"); console.log(`txHash is: ${txHash}`) ``` ---------------------------------------- TITLE: Setting Up Lumos Configuration and Utilities DESCRIPTION: This TypeScript snippet initializes the Lumos configuration for the CKB testnet, sets up an Indexer and RPC client, and defines helper functions for creating CKB `Script` and `CellDep` objects. It also prepares the owner's private key and derives the corresponding lock script and address for subsequent operations. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-tutorial-issue-and-transfer-xudt.md#_snippet_2 LANGUAGE: ts CODE: ``` import type { Cell, Script, CellDep } from "@ckb-lumos/lumos" import { config, hd, Indexer, RPC } from "@ckb-lumos/lumos" import { bytes, BytesLike, Uint128 } from "@ckb-lumos/lumos/codec" import { common } from "@ckb-lumos/lumos/common-scripts" import { ScriptConfig } from "@ckb-lumos/lumos/config" import { addCellDep, cellHelper, encodeToAddress, sealTransaction, TransactionSkeleton } from "@ckb-lumos/lumos/helpers" import { computeScriptHash } from "@ckb-lumos/lumos/utils" // to work with the testnet config.initializeConfig(config.TESTNET) // indexer for cell provider const indexer = new Indexer("https://testnet.ckb.dev") // rpc to interact with the CKB node const rpc = new RPC("https://testnet.ckb.dev") // paste the generated key for the owner const ownerPrivateKey = "<0x paste the key here>" // script config that will be used later const { XUDT, SECP256K1_BLAKE160 } = config.TESTNET.SCRIPTS const ownerLockScript = createScript(SECP256K1_BLAKE160, hd.key.privateKeyToBlake160(ownerPrivateKey)) const ownerAddress = encodeToAddress(ownerLockScript) // a helper to create a Script from a ScriptConfig function createScript(config: ScriptConfig, args: BytesLike): Script { return { codeHash: config.CODE_HASH, hashType: config.HASH_TYPE, args: bytes.hexify(args) } } // a helper to crete a CellDep from a ScriptConfig function createCellDep(config: ScriptConfig): CellDep { return { depType: config.DEP_TYPE, outPoint: { txHash: config.TX_HASH, index: config.INDEX } } } ``` ---------------------------------------- TITLE: Building a Transaction with TransactionSkeleton in JavaScript DESCRIPTION: This snippet demonstrates the end-to-end process of constructing, updating, paying fees, signing, and broadcasting a CKB transaction using Lumos's `TransactionSkeleton`. It shows how to initialize `TransactionSkeleton` with a `CellProvider`, update its components (inputs, outputs, cellDeps, witnesses), calculate fees, sign the transaction, and finally send it via RPC. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/02-tx-skeleton.md#_snippet_0 LANGUAGE: js CODE: ``` const indexer = new Indexer("https://ckb-rpc-entry") const rpc = new RPC("https://ckb-rpc-entry") // txSkeleton is immutable, use 'let' to declare and update let txSkeleton = TransactionSkeleton({ cellProvider: (query) => // wrap the indexer as a CellProvider indexer.collector({ ...query, type: "empty" }) }) // update TransactionSkeleton txSkeleton = txSkeleton .update("inputs", (inputs) => inputs.push(inputs0, inputs1)) .update("outputs", (outputs) => outputs.push(outputs0, outputs1)) .update("cellDeps", (cellDeps) => cellDeps.push(lockScriptDep, typeScriptDep0)) .update("witnesses", (witnesses) => witnesses.push(aliceSignature)) // pay fee by the fee rate txSkeleton = await common.payFeeByFeeRate(txSkeleton, 1000, [fromAddr]) // sign the tranasction const signatures = txSkeleton .get("signingEntries") .map(({ message }) => sign(message)) .toArray() // convert the TransactionSkeleton to RPC transaction const signedTransaction = sealTransaction(txSkeleton, signatures) // broadcast the transaction const txHash = await rpc.sendTransaction(signedTransaction) ``` ---------------------------------------- TITLE: Installing Node.js and pnpm (Shell) DESCRIPTION: 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. SOURCE: https://github.com/ckb-js/lumos/blob/develop/README.md#_snippet_0 LANGUAGE: Shell CODE: ``` sudo apt-get update sudo apt install nodejs npm install -g pnpm ``` ---------------------------------------- TITLE: Transferring SUDT Tokens with Lumos DESCRIPTION: This asynchronous function facilitates the transfer of Simple User Defined Tokens (SUDT) from an issuer to a recipient address. It builds a transaction skeleton, adds SUDT transfer details, handles transaction fees, prepares signing entries, signs the transaction, and sends it to the CKB RPC. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md#_snippet_21 LANGUAGE: TypeScript CODE: ``` export const transferToken = async (issuer: Address, to: Address, amount: number, privateKey: string) => { let txSkeleton = helpers.TransactionSkeleton({ cellProvider: indexer }); const scriptLockHash = utils.computeScriptHash(helpers.parseAddress(issuer)) txSkeleton = await commons.sudt.transfer( txSkeleton, [issuer], scriptLockHash, to, BI.from(amount), ) txSkeleton = await commons.common.payFeeByFeeRate( txSkeleton, [issuer], 1000, ); txSkeleton = commons.common.prepareSigningEntries(txSkeleton); const message = txSkeleton.get("signingEntries").get(0)?.message; const Sig = hd.key.signRecoverable(message!, privateKey); const tx = helpers.sealTransaction(txSkeleton, [Sig]); return rpc.sendTransaction(tx, "passthrough"); } ``` ---------------------------------------- TITLE: Using Root Lumos Package for Configuration and Address Parsing in TypeScript DESCRIPTION: 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. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/01-run-lumos-in-the-browser.md#_snippet_3 LANGUAGE: ts CODE: ``` import { Script, Indexer, helpers, config } from "@ckb-lumos/lumos" config.initializeConfig(config.predefined.AGGRON4) const address = "ckt1qyqxgftlqzmtv05cwcyl4xlz6ryx6dgsyrasjrp27t" const lock: Script = helpers.parseAddress(address) ``` ---------------------------------------- TITLE: Implementing xUDT Cell Transfer with Lumos - TypeScript DESCRIPTION: This TypeScript function `transfer()` demonstrates the end-to-end process of transferring an xUDT cell using the Lumos library. It covers collecting the xUDT cell, setting up the transaction skeleton, adding cell dependencies, updating cell ownership, paying fees, preparing signing entries, signing the transaction, and broadcasting it to the CKB network. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-tutorial-issue-and-transfer-xudt.md#_snippet_6 LANGUAGE: TypeScript CODE: ``` async function transfer() { const xudtTypeScript = createScript(XUDT, computeScriptHash(ownerLockScript)) const cellProvider: TransactionSkeletonType["cellProvider"] = { collector: (query) => indexer.collector({ type: "empty", data: "0x", ...query }), } const alicePrivateKey = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" const aliceLock = createScript(SECP256K1_BLAKE160, hd.key.privateKeyToBlake160(alicePrivateKey)) // 1. Collect Minted xUDT Cell // Find the xUDT cell owned by you (based on owner lock script). const xudtCollector = indexer.collector({ type: xudtTypeScript, lock: ownerLockScript }) let transferCell: Cell | undefined for await (const cell of xudtCollector.collect()) { transferCell = cell // Collect only one (assuming you have only one minted xUDT cell). break } if (!transferCell) { throw new Error("Owner do not have an xUDT cell yet, please call mint first") } const transferAmount = Uint128.unpack(transferCell.data) console.log("Transfer to Alice", transferAmount.toNumber(), "xUDT") // 2. Create Transaction Skeleton let txSkeleton = TransactionSkeleton({ cellProvider }) // 3. Add xUDT Script Dependency txSkeleton = addCellDep(txSkeleton, createCellDep(XUDT)) // 4. Set Up Input Cell (Transfer Cell) // Include the minted xUDT cell as both input and output (for transfer). txSkeleton = await common.setupInputCell(txSkeleton, transferCell) // 5. Update Output Cell Lock to Alice's Lock // Change the ownership of the minted xUDT cell to Alice's lock. txSkeleton = txSkeleton.update("outputs", (outputs) => outputs.update(0, (cell) => ({ ...cell!, cellOutput: { ...cell!.cellOutput, lock: aliceLock } })) ) // the following process is the same with mint to broadcast the transaction txSkeleton = await common.payFeeByFeeRate(txSkeleton, [ownerAddress], 1000) txSkeleton = common.prepareSigningEntries(txSkeleton) const signatures = txSkeleton .get("signingEntries") .map(({ message }) => hd.key.signRecoverable(message, ownerPrivateKey)) .toArray() const signed = sealTransaction(txSkeleton, signatures) const txHash = await rpc.sendTransaction(signed) console.log(txHash) } ``` ---------------------------------------- TITLE: Getting CKB Balance with Lumos Indexer in TypeScript DESCRIPTION: 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. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/01-run-lumos-in-the-browser.md#_snippet_1 LANGUAGE: ts CODE: ``` 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() ``` ---------------------------------------- TITLE: Issuing and Transferring sUDT Tokens with Lumos (JavaScript) DESCRIPTION: This snippet demonstrates how to use the `sudt` script from Lumos to issue new sUDT tokens and transfer existing sUDT tokens between addresses. It highlights the parameters required for these operations, such as the token amount and addresses. SOURCE: https://github.com/ckb-js/lumos/blob/develop/packages/common-scripts/README.md#_snippet_2 LANGUAGE: JavaScript CODE: ``` const { sudt } = require("@ckb-lumos/common-scripts") let txSkeleton = TransactionSkeleton({ cellProvider: indexer }) // issue an sudt token, will use the second param address to generate sudt token(it's lock hash). txSkeleton = await sudt.issueToken( txSkeleton, "ckb1qyqrdsefa43s6m882pcj53m4gdnj4k440axqdt9rtd", 10000n, ); // and transfer sUDT const sudtToken = "0x1f2615a8dde4e28ca736ff763c2078aff990043f4cbf09eb4b3a58a140a0862d" txSkeleton = await sudt.transfer( txSkeleton, ["ckb1qyqrdsefa43s6m882pcj53m4gdnj4k440axqdt9rtd"], sudtToken, "ckb1qyqwyxfa75whssgkq9ukkdd30d8c7txct0gq5f9mxs", 1000n, "ckb1qyqrdsefa43s6m882pcj53m4gdnj4k440axqdt9rtd", ); ``` ---------------------------------------- TITLE: Minting xUDT Transaction Implementation (TypeScript) DESCRIPTION: This TypeScript function `mint()` demonstrates the step-by-step process of programmatically constructing and broadcasting an xUDT minting transaction using the Lumos library. It covers creating the xUDT type script, defining a cell provider, initializing the transaction skeleton, creating the minted cell, adding cell dependencies, injecting CKB capacity, paying transaction fees, preparing signing entries, signing the transaction with the owner's private key, and finally broadcasting the sealed transaction to the CKB network. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-tutorial-issue-and-transfer-xudt.md#_snippet_4 LANGUAGE: typescript CODE: ``` async function mint() { console.log("Please Claim some testnet CKB first from https://faucet.nervos.org") console.log("Your owner address:", ownerAddress) // 1. Create the xUDT Type Script // This script defines the structure of the xUDT token. const xudtTypeScript = createScript(XUDT, computeScriptHash(ownerLockScript)) // 2. Define Cell Provider (Optional) // This helps filter out unnecessary cells during transaction building. const cellProvider: TransactionSkeletonType["cellProvider"] = { collector: (query) => indexer.collector({ type: "empty", data: "0x", ...query }), } // 3. Create Transaction Skeleton // This is the base structure for our transaction. let txSkeleton = TransactionSkeleton({ cellProvider }) // 4. Create Minted Cell with Amount // This defines the cell that will hold the minted xUDT tokens. const mintCell = cellHelper.create({ lock: ownerLockScript, // The owner (you) controls this cell. type: xudtTypeScript, // This cell holds xUDT tokens. data: Uint128.pack(10000), // Set the initial amount of xUDT to mint (10000). }) // 5. Add xUDT Script Dependency txSkeleton = addCellDep(txSkeleton, createCellDep(XUDT)) // 6. Inject Capacity for Minted Cell txSkeleton = await common.injectCapacity(txSkeleton, [ownerAddress], mintCell.cellOutput.capacity) // 7. Add Minted Cell to Outputs // Specify the minted cell as part of the transaction outputs. txSkeleton = txSkeleton.update("outputs", (outputs) => outputs.push(mintCell)) // 8. Pay Transaction Fee // Allocate CKB for transaction fees. // see also https://github.com/nervosnetwork/ckb/blob/31e02872b3a55ca7558073cb781971d8bc8f29b2/util/app-config/src/legacy/tx_pool.rs#L8-L9 txSkeleton = await common.payFeeByFeeRate(txSkeleton, [ownerAddress], 1000) // 9. Prepare Signing Entries and Sign // Prepare transaction data for signing and sign it with your private key. txSkeleton = common.prepareSigningEntries(txSkeleton) const signatures = txSkeleton .get("signingEntries") .map(({ message }) => hd.key.signRecoverable(message, ownerPrivateKey)) .toArray() // 10. Broadcast Transaction // Send the signed transaction to the CKB node. const signedTransaction = sealTransaction(txSkeleton, signatures) const txHash = await rpc.sendTransaction(signedTransaction) console.log(`https://pudge.explorer.nervos.org/transaction/${txHash}`) } ``` ---------------------------------------- TITLE: Generating First HD Private Key (TypeScript) DESCRIPTION: This TypeScript function `generateFirstHDPrivateKey` uses `@ckb-lumos/hd` to generate a new mnemonic, convert it to a seed, and derive the first receiving extended private key. It returns the derived private key, which is essential for managing CKB assets. It depends on the `hd` module from `@ckb-lumos/lumos`. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md#_snippet_5 LANGUAGE: TypeScript CODE: ``` // wallet.ts import { hd } from '@ckb-lumos/lumos'; const { mnemonic, ExtendedPrivateKey,AddressType } = hd; export const generateFirstHDPrivateKey = () => { const myMnemonic = mnemonic.generateMnemonic(); const seed = mnemonic.mnemonicToSeedSync(myMnemonic); console.log("my mnemonic ", seed); const extendedPrivKey = ExtendedPrivateKey.fromSeed(seed); return extendedPrivKey.privateKeyInfo(AddressType.Receiving, 0).privateKey; } ``` ---------------------------------------- TITLE: Deriving CKB Address from Private Key (TypeScript) DESCRIPTION: This TypeScript function `getAddressByPrivateKey` converts a given private key into a CKB address. It uses the `SECP256K1_BLAKE160` script template from the `AGGRON4` configuration to construct the lock script and then encodes it into a human-readable CKB address. It requires the private key as input and outputs the CKB address string. It depends on the `hd`, `config`, and `helpers` modules from `@ckb-lumos/lumos`. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md#_snippet_7 LANGUAGE: TypeScript CODE: ``` import { hd, config, helpers } from '@ckb-lumos/lumos'; const getAddressByPrivateKey = (privateKey: string) => { const args = hd.key.privateKeyToBlake160(privateKey); const template = config.predefined.AGGRON4.SCRIPTS["SECP256K1_BLAKE160"]!; const lockScript = { codeHash: template.CODE_HASH, hashType: template.HASH_TYPE, args: args, }; return helpers.encodeToAddress(lockScript); } ``` ---------------------------------------- TITLE: Initializing CKB Lumos Indexer in JavaScript DESCRIPTION: This snippet demonstrates how to initialize a new instance of the CKB Lumos Indexer. It requires the `@ckb-lumos/ckb-indexer` package and takes two URI parameters: `indexUri` for the indexer service and `nodeUri` for the CKB RPC node. The `indexer` object can then be used for CKB data queries. SOURCE: https://github.com/ckb-js/lumos/blob/develop/packages/ckb-indexer/README.md#_snippet_0 LANGUAGE: JSX CODE: ``` 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); ``` ---------------------------------------- TITLE: Initializing CKB Indexer in JavaScript/JSX DESCRIPTION: 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. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/01-run-lumos-in-the-browser.md#_snippet_2 LANGUAGE: jsx CODE: ``` 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) ``` ---------------------------------------- TITLE: Complete SUDT Wallet Functions in Lumos (TypeScript) DESCRIPTION: This comprehensive code block provides a set of functions for a basic SUDT wallet. It includes issueToken for creating new SUDT tokens, transferToken for sending SUDT to another address, and getTokenAmount for checking an address's SUDT balance. All functions interact with the CKB blockchain via Lumos RPC and Indexer, handling transaction skeleton building, fee payment, signing, and sending. SOURCE: https://github.com/ckb-js/lumos/blob/develop/website/docs/00-intro.md#_snippet_25 LANGUAGE: TypeScript CODE: ``` import { config, Address, RPC, Indexer, helpers, commons, hd, BI, utils } from '@ckb-lumos/lumos'; import { number } from "@ckb-lumos/codec"; config.initializeConfig(config.predefined.AGGRON4); 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); export const issueToken = async (issuer: Address, amount: number, privateKey: string) => { let txSkeleton = helpers.TransactionSkeleton({ cellProvider: indexer }); txSkeleton = await commons.sudt.issueToken( txSkeleton, issuer, amount, ); txSkeleton = await commons.common.payFeeByFeeRate( txSkeleton, [issuer], 1000, ); txSkeleton = commons.common.prepareSigningEntries(txSkeleton); const message = txSkeleton.get("signingEntries").get(0)?.message; const Sig = hd.key.signRecoverable(message!, privateKey); const tx = helpers.sealTransaction(txSkeleton, [Sig]); return rpc.sendTransaction(tx, "passthrough"); } export const transferToken = async (issuer: Address, to: Address, amount: number, privateKey: string) => { let txSkeleton = helpers.TransactionSkeleton({ cellProvider: indexer }); const scriptLockHash = utils.computeScriptHash(helpers.parseAddress(issuer)) txSkeleton = await commons.sudt.transfer( txSkeleton, [issuer], scriptLockHash, to, BI.from(amount), ) txSkeleton = await commons.common.payFeeByFeeRate( txSkeleton, [issuer], 1000, ); txSkeleton = commons.common.prepareSigningEntries(txSkeleton); const message = txSkeleton.get("signingEntries").get(0)?.message; const Sig = hd.key.signRecoverable(message!, privateKey); const tx = helpers.sealTransaction(txSkeleton, [Sig]); return rpc.sendTransaction(tx, "passthrough"); } export const getTokenAmount = async (address: Address, sudtArgs: string) => { const collector = indexer.collector({ lock: helpers.parseAddress(address), type: { codeHash: config.predefined.AGGRON4.SCRIPTS['SUDT'].CODE_HASH, hashType: config.predefined.AGGRON4.SCRIPTS['SUDT'].HASH_TYPE, args: sudtArgs, } }); let amount = BI.from(0); for await (const cell of collector.collect()) { amount = amount.add(number.Uint128LE.unpack(cell.data)); } return amount; } ``` ---------------------------------------- TITLE: Calculating Cell Capacity and Generating Mainnet Address using Lumos Helpers (JavaScript) DESCRIPTION: This snippet demonstrates how to use `@ckb-lumos/helpers` to calculate the minimal capacity required for a CKB cell and to generate a mainnet address from a lock script. It shows the `minimalCellCapacity` function with a `CellOutput` and data, and the `generateAddress` function with `codeHash`, `hashType`, and `args` for the lock script. The expected output for `minimalCellCapacity` is 6100000000n shannons. SOURCE: https://github.com/ckb-js/lumos/blob/develop/packages/helpers/README.md#_snippet_0 LANGUAGE: javascript CODE: ``` const { minimalCellCapacity, generateAddress, parseAddress, } = require("@ckb-lumos/helpers"); // Get cell minimal capacity. const result = minimalCellCapacity({ cellOutput: { capacity: "0x174876e800", lock: { args: "0x36c329ed630d6ce750712a477543672adab57f4c", codeHash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hashType: "type", }, type: null, }, data: "0x", blockHash: null, blockNumber: null, outPoint: null, }); // result will be 6100000000n shannons. // Use `generateAddress` to get address from lock script. const address = generateAddress({ codeHash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hashType: "type", args: "0x36c329ed630d6ce750712a477543672adab57f4c", }); ```