Search code examples
soliditychaiethers.jshardhat

How to test the revert for 'call' function with Hardhat?


I would like to have 100% code coverage but one function is giving trouble ...

(bool sent, bytes memory data) = _to.call{value: msg.value}("");
require(sent, "Failed to send Ether");

How to force the boolean 'sent' to false ?

Stack : hardhat, solidity, ethers.js, chai.js

I tried to modify the balance of the address which must pay :

await network.provider.send("hardhat_setBalance", [
 "...address...",
 "0x1000"
]);

But i don't go to the require, i've got this error :

sender doesn't have enough funds to send tx

Any idea please ?


Solution

  • (bool sent, bytes memory data) = _to.call{value: msg.value}("");
    

    How to force the boolean 'sent' to false ?

    The first value becomes false when the transfer fails.

    For example when the recipient is a contract that doesn't implement the receive() nor fallback() special functions.

    So you can have a mock contract that always rejects all native transfers, and assign it as the to address.

    pragma solidity 0.8.20;
    
    contract FailingRecipient {}