Web3.js
Web3.js is a Javascript library for building on EVM-compatible networks.
It allows developers to interact with smart contracts, send transactions, and retrieve data from the network.
Prerequisites
This guide assumes you have the latest version of Node.js installed.
To install web3
in your project, run the following command:
Initializing Web3 with Flow
To use web3
in your project, start by importing the module and initializing your Web3
instance with a Flow RPC endpoint.
Note: If you want to connect to the Flow testnet, replace the above URL with https://mainnet.evm.nodes.onflow.org
.
Querying The Blockchain
web3
provides a number of methods for querying the blockchain, such as getting the latest block number, querying account balances, and more.
You can try using some of these methods to verify that your web3
instance is working correctly.
For more information about other queries you can make web3
, please see the official documentation.
Interacting with Smart Contracts
The web3
library allows developers to interact with smart contracts via the web3.eth.Contract
API.
For this example we will use the following Storage
contract.
We recommend deploying your own contract, which can be done using Hardhat or Remix.
The ABI for this contract can be generated using the solc
compiler, or another tool such as Hardhat or Remix.
Now that we have both the ABI and address of the contract, we can create a new Contract
object for use in our application.
We can now interact with the contract on the network by using the contract
object.
Reading State
State can be read from the contract by using the call
function with one of the contract's methods. This will not change the state and will not send a transaction.
Changing State
We can mutate the state of the contract by sending a transaction to the network.
In order to send a transaction to the network, you will need an account with sufficient funds to pay for the transaction.
If you do not have an account yet, you can create one using the following command from your project's root directory:
Note that this is not a secure way to generate an account, and you should use a more secure method in a production environment.
You can fund your account using the Flow Faucet.
We can use the privateKeyToAccount
function to create an Web3Account
object from our account's private key.
Then, we can sign a transaction using the user's account and send it to the network.
Now that the transaction has been sent, the contract's state should have been updated. We can verify this by querying the contract's state again:
For more information about using smart contracts in web3.js, see the official documentation.