Ethers.js
ethers.js is a powerful JavaScript library for interacting with Ethereum and other EVM-compatible blockchain networks.
In this guide, we'll walk you through how to use ethers.js to interact with smart contracts on the Flow Blockchain.
Installation​
To begin using ethers.js in your project, you'll need to install the package. You can do this by running the following command:
_10bashCopy code_10npm install --save ethers
Setup​
After installing ethers.js, the next step is to import it into your project.
You can do this by adding the following line of code at the beginning of your JavaScript file:
_10const ethers = require('ethers');
Connecting to Flow​
To connect to the Flow Blockchain using ethers.js, you need to create a new JsonRpcProvider
instance with the appropriate RPC URL for Flow:
_10const ethers = require('ethers');_10_10const url = 'https://testnet.evm.nodes.onflow.org/';_10const provider = new ethers.providers.JsonRpcProvider(url);
Note: If you want to connect to the Flow testnet, replace the above URL with https://mainnet.evm.nodes.onflow.org
.
Reading Data from the Blockchain​
Once your provider is set up, you can start reading data from the Flow Blockchain. For instance, to retrieve the latest block number, you can use the getBlockNumber
method:
_10async function getLatestBlock() {_10 const latestBlock = await provider.getBlockNumber();_10 console.log(latestBlock);_10}
Writing Data to the Blockchain​
To send transactions or write data to the Flow Blockchain, you need to create a Signer
. This can be done by initializing a new Wallet
object with your private key and the previously created Provider
:
_10const privateKey = 'YOUR_PRIVATE_KEY';_10const signer = new ethers.Wallet(privateKey, provider);
Note: Replace 'YOUR_PRIVATE_KEY'
with the actual private key of the wallet you want to use.
Interacting with Smart Contracts​
ethers.js also enables interaction with smart contracts on the Flow Blockchain. To do this, create a Contract
object using the ABI (Application Binary Interface) and the address of the deployed contract:
_10const abi = [_10 // ABI of deployed contract_10];_10_10const contractAddress = 'CONTRACT_ADDRESS';_10_10// read-only contract instance_10const contract = new ethers.Contract(contractAddress, abi, provider);
For contracts that require writing, you'll need to provide a Signer
object instead of a Provider
:
_10// write-enabled contract instance_10const contract = new ethers.Contract(contractAddress, abi, signer);
Note: Replace 'CONTRACT_ADDRESS'
with the actual address of your deployed contract.
After setting up your Contract
object, you can call methods on the smart contract as needed:
_10async function setValue(value) {_10 const tx = await contract.set(value);_10 console.log(tx.hash);_10}_10_10async function getValue() {_10 const value = await contract.get();_10 console.log(value.toString());_10}