EthersJs is a popular javascript library for interacting with the blockchain (Ethereum, BSc, and other Evm-compatible blockchains). Not too many people (beginners) are comfortable with using official documentation. hence why I came up with this. Let's get down to it ✈️
Installing Ethers.js
The first thing is to install the library we are talking about. At the time of writing, ethers were at v6 so this would strictly follow that.
npm install ethers
Connect Metamask
Connects ethereum with metamask
jconst provider = new ethers.BrowserProvider(window.ethereum);
Connect To RPC
For connecting Ethereum with RPCJsonRpcProvider
const provider = new ethers.JsonRpcProvider(url);
The url
now depends on what RPC we want to connect to, We have a good number of them. Like Alchemy, Infura, and Quicknode. Go to any of the providers we want to use to get the url and that should be assigned as the url when connecting to RPCJsonRpcProvider.
Signing Message
for signing messages using the Ethersjs library. An example is given below:
const wallet = new ethers.Wallet(privateKey, provider);
const message = "Hello, I am Israel!";
const signature = await wallet.signMessage(message);
console.log("Signature:", signature);
Contract
Create a contract instance by the signer. It won't work if the user doesn't have a wallet connected.
Example:
const { ethers } = require("ethers");
const { ERC20JSON } = require('./ERC20.json');
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
const contractAddress = "0x1..."
const contract = new ethers.Contract(contractAddress, ERC20JSON, signer);
console.log(contract)
Read-Only Contract
To do this we can create a contract instance with just provider.
It can call Read-only methods only, it works even if a user isn't connected.
const contract = new ethers.Contract(contractAddress, ERC20JSON, provider);
A Typical example:
const { ethers } = require("ethers");
const { ERC20JSON } = require('./ERC20.json');
const provider = new ethers.BrowserProvider(window.ethereum);
//const signer = await provider.getSigner();
const contractAddress = "0x1..."
const contract = new ethers.Contract(contractAddress, ERC20JSON, provider);
const tokenName = await contract.name();
console.log(`contract name is ${tokenName}`);
Write Only Contract
A "Write Only" contract typically refers to a smart contract on the Ethereum blockchain that only contains functions that modify the contract's state but does not have any functions to read or retrieve data from the contract. In other words, it allows users to write (i.e., update) the contract's state but doesn't provide any public functions to read or query data from the contract.
Example below:
const { ethers } = require("ethers");
const { ERC20JSON } = require('./ERC20.json');
const provider = new ethers.BrowserProvider(window.ethereum);
//const signer = await provider.getSigner();
const contractAddress = "0x1..."
const contract = new ethers.Contract(contractAddress, ERC20JSON, provider);
const functionName = await contract.functionName(argument1, argument2);
console.log(`contract name is ${functionName}`);
ChainID
Get connected ChainID and network
const network = await provider.getNetwork();
const chainId = network.chainId;
console.log(`Network: ${network}`);
console.log(`ChainID: ${chainId}`);
A list of networks and Chanid
Network | ChainID |
Ethereum (Mainnet) | 1 |
Goerli | 5 |
Sepolia test network | 11155111 |
Binance Smart Chain (BSC) | 56 |
BNB Smart Chain Testnet | 97 |
Polygon Mainnet | 137 |
Mumbai | 80001 |
Optimism | 10 |
Sending Transactions
When you want to send a transaction using ethers.js you can use this simple code:
try {
const recipient = "0xb1Ce7C558C8.................";
const amount = ethers.parseEther("0.005");
const tx = {
to: recipient,
value: amount,
gasPrice: ethers.parseUnits("100", "gwei"),
nonce: await wallet.getNonce()
};
const signedTx = await wallet.sendTransaction(tx);
const gasEstimateSigned = await provider.estimateGas(signedTx);
console.log("gas estimate signed", gasEstimateSigned);
console.log(signedTx);
console.log(signedTx.hash);
const address = await wallet.address;
console.log(address);
} catch (err) {
console.log(err);
}
Creating Wallet
An example is given below:
const Wallet = ethers.Wallet.createRandom(provider);
console.log("Wallet Mnemonic Phrase:", Wallet.mnemonic.phrase);
console.log("Address: ", Wallet.address)