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.
Installation​
This guide assumes you have the latest version of Node.js installed.
To install web3
, run the following command:
Initialization​
To use web3
in your project, start by importing the module and initializing your Web3 provider the desired Flow RPC endpoint.
Currently, only Flow Previewnet is available. More networks are coming soon - see here for more info.
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, deployed on the Flow Previewnet to the address 0x4c7784ae96e7cfcf0224a95059573e96f03a4e70
. Note that anybody can interact with this contract, as it is deployed on a public network, so state may not always be as expected.
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.
Using this newly created object, we can now interact with the contract on the network.
Reading State​
Querying data from the contract is done 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:
For Flow Previewnet, you can fund your account using the Flow Faucet.
First, we will need to be able to sign a transaction using an account. To do this, we can use the privateKeyToAccount
function to create an Web3Account
object from the 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 has been updated. We an verify this by querying the contract's state again.
For more information about using smart contracts in web3.js, see the official documentation.