I need a general-purpose method to call functions from a smart contract using ethers.js. I've always used web3 and I'm trying to transition over; however, I cannot find any good examples of calling functions in ethers.js.

Here is an example:

Let's say I want to transfer my bored ape to another wallet. In etherscan I can easily call the write-only function: https://etherscan.io/token/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#writeContract enter image description here

If I want to call the same function in ethers.js I know I need something like this, but I would kill for a good example.

var ethers = require("ethers");

const abi = <bayc abi here>;
var url = "your-quicknode-here"
var customWsProvider = new ethers.providers.WebSocketProvider(url);
let contractAddress = "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D";
let contract = new ethers.Contract(contractAddress, abi, customWsProvider);
let privateKey = 'your-privatekey-here';
let wallet = new ethers.Wallet(privateKey, customWsProvider);
console.log("wallet connected for purchasing...")

  • provider url and wallet private key should be stored in a ".env" file they would be then connected to "hardhat.config.js". Then you can separate connection to contract and contract call parts.
    – Abdulhakim
    Aug 31, 2022 at 14:38

1 Answer 1

 const tokenContract = new ethers.Contract(contractAddress, tokenAbi, connection);
const transaction = await tokenContract.balanceOf(put address here)
const data = Promise.resolve(transaction)
data.then(value => {
    const result = ethers.utils.formatUnits(value, 18);


To make a change

 const tokenContract = new ethers.Contract(contractAddress, tokenAbi, connection);
var signer = new ethers.Wallet(privateKey, connection);
const txSigner= tokenContract.connect(signer);
const transaction = await txSigner.transfer(to,address,amount)
const data = Promise.resolve(transaction)
data.then(value => {



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.