Created
July 26, 2023 08:37
-
-
Save cassc/75af91db3916c7d6cac7cfddd626fbcc to your computer and use it in GitHub Desktop.
various reverts in solidity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.8.0; | |
import "hardhat/console.sol"; | |
contract A { | |
function willRevert() public pure { | |
revert("This is an error message"); | |
} | |
function willAssert() public pure { | |
assert(false); | |
} | |
function willRequire() public pure { | |
require(false, "Requirement not met"); | |
} | |
function mightGiveDivByZero(uint256 i) public pure returns (uint256){ | |
return 8 / i; | |
} | |
function willRunOutOfGas() public pure{ | |
while(true) { } | |
} | |
} | |
contract B { | |
A public a; | |
event Log(string message); | |
event LogBytes(bytes data); | |
constructor(A _a) { | |
a = _a; | |
} | |
function callDivByZero(uint256 i) public returns (uint256 j){ | |
// try-catch can not handle div by zero error | |
try a.mightGiveDivByZero(i) { | |
return block.number; | |
} catch Error(string memory reason) { // revert and require | |
console.log("caught err"); | |
console.log(reason); | |
return 13; | |
} catch (bytes memory reason) { | |
console.log("caught data"); | |
emit LogBytes(reason); | |
return 1; | |
} | |
} | |
function callWillRevert() public returns (uint256) { | |
try a.willRevert() { | |
return 232; | |
} catch Error(string memory reason) { // revert and require | |
console.log("caught err"); | |
console.log(reason); | |
return 13; | |
} catch (bytes memory reason) { | |
console.log("caught data"); | |
emit LogBytes(reason); | |
return 1; | |
} | |
} | |
function callWillAssert() public returns (uint256) { | |
try a.willAssert() { | |
return 232; | |
} catch Error(string memory reason) { // revert and require | |
console.log("caught err"); | |
console.log(reason); | |
return 13; | |
} catch (bytes memory reason) { | |
console.log("caught data"); | |
emit LogBytes(reason); | |
return 1; | |
} | |
} | |
function callWillRequire() public returns (uint256) { | |
try a.willRequire() { | |
return 232; | |
} catch Error(string memory reason) { // revert and require | |
console.log("caught err"); | |
console.log(reason); | |
return 13; | |
} catch (bytes memory reason) { | |
console.log("caught data"); | |
emit LogBytes(reason); | |
return 1; | |
} | |
} | |
function callwillRunOutOfGas() public returns (uint256) { | |
try a.willRunOutOfGas() { | |
return 232; | |
} | |
catch Error(string memory reason) { // revert and require | |
console.log("caught err"); | |
console.log(reason); | |
return 13; | |
} catch (bytes memory reason) { | |
console.log("caught data"); | |
emit LogBytes(reason); | |
return 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment