Skip to main content

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:


_10
bashCopy code
_10
npm 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:


_10
const 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:


_10
const ethers = require('ethers');
_10
_10
const url = 'https://testnet.evm.nodes.onflow.org/';
_10
const 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:


_10
async 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:


_10
const privateKey = 'YOUR_PRIVATE_KEY';
_10
const 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:


_10
const abi = [
_10
// ABI of deployed contract
_10
];
_10
_10
const contractAddress = 'CONTRACT_ADDRESS';
_10
_10
// read-only contract instance
_10
const 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
_10
const 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:


_10
async function setValue(value) {
_10
const tx = await contract.set(value);
_10
console.log(tx.hash);
_10
}
_10
_10
async function getValue() {
_10
const value = await contract.get();
_10
console.log(value.toString());
_10
}