Building 🏗 and Executing 🛫 a CKB Transaction - A Step-by-Step 📝 Guide
🔗 In this tutorial, we'll guide you through building and executing a transaction on
@NervosNetwork #CKB blockchain using TypeScript with the
@ckb-lumos/lumos library.
1️⃣ Setup and Configuration
🔧 Import the required modules from the
@ckb-lumos/lumos library.
🔧 Initialize the configuration for the testnet using `config.initializeConfig(config.predefined.AGGRON4)`.
2️⃣ Initialize RPC and Indexer
🌐 Define the URLs for the CKB RPC and Indexer.
🌐 Create an RPC instance with `new RPC(CKB_RPC_URL)` and an Indexer instance with `new Indexer(CKB_INDEXER_URL, CKB_RPC_URL)`.
3️⃣ Define Addresses and Private Key
🔑 Define the sender's and receiver's addresses and private key for the transaction.
4️⃣ Calculate Capacities
💰 Implement a function `getCapacities` that calculates the sender's account balance using the Indexer.
💰 Use `indexer.collector()` and `collector.collect()` to iterate through cells associated with the sender's address.
💰 Return the total capacities as a BigInt.
5️⃣ Building the Transaction
📄 Define a function `transfer` to create and send a transaction.
📄 Initialize `txSkeleton` with `helpers.TransactionSkeleton({ cellProvider: indexer })`.
📄 Utilize `commons.common.transfer()` to add the transfer details to the transaction.
📄 Add fee calculation using `commons.common.payFeeByFeeRate()`.
📄 Prepare signing entries using `commons.common.prepareSigningEntries()`.
📄 Generate a signature using the sender's private key and seal the transaction using `helpers.sealTransaction()`.
6️⃣ Sending the Transaction
✉️ Display the sender's address using `console.log()`.
✉️ Execute the `transfer()` function, passing in sender and receiver addresses, capacity, and private key.
✉️ Print the transaction hash when the promise resolves.
7️⃣ Check Balance
💸 Use the `getCapacities()` function to get the sender's remaining balance in CKB.
💸 Convert the capacities to CKB units and display it using `console.log()`.
To run 👾 the code, follow these steps:
1. Ensure you have Node.js installed (14 recommended).
2. Install
@ckb-lumos/lumos library using `npm install
@ckb-lumos/lumos`.
3. Copy the provided code into a TypeScript file (e.g., `transaction.ts`).
4. Compile TypeScript into JS code using `npx ts-node transaction.ts`.
5. Run JS code `node transaction.js`.