Using Web3.js
Using Web3.js to interact with CLV
Introduction
This guide walks through the process of using web3.js to manually sign and send a transaction to a CLV standalone node. For this example, we will use Node.js and straightforward JavaScript code.
The guide assumes that you have a local CLV node running in --dev
mode. You can find instructions to set up a local CLV node here.
Prerequisites
1. Start CLV node
Start your standalone CLV node, which can successfully produce blocks in your local environment.
2. Install Node.js and NPM
To install Node.js (we'll go for v12.x, you can choose other versions, such as the latest version v15.x) and NPM package manager. You can do this by running the following commands in your terminal:
For Mac users:
For Debian users:
For Centos/Redhat users:
We can verify that everything installed correctly by querying the version for each package:
3. Create your Node.js project
You can create a repository on your local environment by running:
Query Balance
We can easily do this by leveraging the Ethereum compatibility features of CLV.
First let's create a file balance.js under the project we've created. Here we just query the balance of the genesis account, and the genesis account is endowed with 10,000,000 ETH by your local CLV node under the development mode. To get the balances of the account, we need to make an asynchronous function that uses the web3.eth.getBalance(address)
command. We can take advantage of the web3.utils.fromWei()
function to transform the balance into a more readable number in ETH.
The file looks like this:
Running the Script
You can run the above script using command :
The output of the execution is as following:
Send Transaction
For our example, we only need a single JavaScript file (arbitrarily named transaction.js) to create and send the transaction, which we will run using the node
command in the terminal. The script will transfer 100 CLV from the genesis account to another address. For simplicity, the file is divided into three sections: variable definition, create transaction, and send transaction.
We need to set a couple of values in the variable definitions, then construct and sign the transaction:
Create your Web3 constructor (
Web3
).Specify the received address, CLV amount, gas price and gas limit.
Sign the transaction and broadcast it the CLV chain
The code looks like:
Running the Script
You can run the above script using command :
Last updated