I'm using Hardhat to deploy my contract locally, and Ethers.js and Node.js run a Javascript file which makes sequential calls to the contract to simulate user activity. When the contract reverts (for example somebody calls the transfer() function with a zero balance) I want Ethers.js to ignore it instead of stopping execution of the Javascript. Is there a way to do this?
1 Answer
Yes, as sola24 said in the comments you can use a try and catch block, like this:
try {
//call contract
}catch(error){
//keep working on javascript code
}
More info about try/catch blocks here.
Also you could use openzepelin's test helpers, expectRevert
to be precise, just install it via npm:
npm install --save-dev @openzeppelin/test-helpers
remember to import @openzeppelin/test-helpers
on your test file and create a test as follows:
it('reverts when transferring tokens you dont have', async function () {
// Conditions that trigger a require statement can be precisely tested
await expectRevert(
this.erc20.transfer(some_address, 5000, { from: sender }),
'Not enough funds',
);
});
More info about it on their readme.