The purpose of this example is to demonstrate usage of basic blockchain methods.
Short overview of example:
- Prerequisites
- Build example
- Registering the Tolar plugin with a web3.js instance
- Getting blockchain information
- Getting block
- Getting transaction in block
- NodeJS (LTS/Iron)
- npm
- web3js 4.0 or higher
# Install
npm install
# Build
npm run build
# Run
npm run dev
First, we create a web3js object and set the provider to the local Tolar Hashnet network.
The next step is to register the Tolar Hashnet plugin in accordance with the web3JS plugin guide.
const web3 = new Web3("http://127.0.0.1:8200/jsonrpc");
web3.registerPlugin(new TolarPlugin());
To get information about blockchain we call getBlockchainInfo
method. Method returns hash of last block and total number of blocks.
const blockchainInfo = await web3.tolar.getBlockchainInfo();
With possible result:
console.log(JSON.stringify(blockchainInfo));
> {"lastConfirmedBlockHash":"0x0cf69aab323c999667b6046b24bceb03b26f836b1ebc471e0f849936416ee493","totalBlocksCount":430,"confirmedBlocksCount":430}
Blocks can be obtained by the hash or index of the block. Start block index is 1. In this example we obtain last block by using value from lastConfirmedBlockHash
field.
More convenient way will be by using getLatestBlock
method.
const block = await web3.tolar.getBlockByHash(blockchainInfo.lastConfirmedBlockHash);
The block object contains field transactionHashes
, which is an array containing transaction hashes.
We iterate it to obtain transactions using the getTransaction
method. The getLatestBalance
method is used to obtain the balances of the transaction sender and receiver.
for (const txHash of block.transactionHashes) {
const tx = await web3.tolar.getTransaction(txHash);
console.log(`Transaction ${tx.transactionHash} from last block has gas used: ${tx.gasUsed}`);
const senderBalance = await web3.tolar.getLatestBalance(tx.senderAddress);
const receiverBalance = await web3.tolar.getLatestBalance(tx.receiverAddress);
console.log(`Sender ${tx.senderAddress} balance: ${senderBalance.balance.toString()}`);
console.log(`Receiver ${tx.receiverAddress} balance: ${receiverBalance.balance.toString()}`);
}