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:
_10npm install web3
Connecting to Flow​
To use web3
in your project, start by imporing the module and initializing your Web3 provider the desired Flow RPC endpoint.
_10const { Web3 } = require('web3')_10const web3 = new Web3('https://mainnet.nodes.fff')
Currently, only Previewnet is available. More networks are coming soon, see here for more info.
Interacting With Smart Contracts​
web3.js
allows developers to interact with smart contracts via the web3.eth.Contract
API.
A Contract
object must be instantiated as follows:
_10const abi = [_10 ... // ABI of deployed contract_10]_10_10const contractAddress_10const contract =
Methods on the smart contract can now be called in the following ways.
Querying state​
We can query data from the contract by using the call
function on one of the contract's methods. This will not mutate the state and will not send a transaction.
_10const result = contract.methods.someGetterFunction().call()_10_10console.log(result)
Mutating state​
If you wish to mutate the contract's state, you may do so with the send
function on one of the contract's methods. This will possibly mutate the state and will send a transaction.
_10const argument = 1 _10const sender = "0x1234" // replace with the address this transaction will be sent from_10_10const result = await contract.methods.someSetterFunction(argument).call({_10 from: sender_10})_10_10console.log(result)
The transaction will be signed automatically by web3js
, as long as the sender's address is registered as an account in the provider.
For more information about using smart contracts in web3.js, see the official documentation.