If you're building a frontend for a blockchain protocol, you'll need to handle errors coming from the smart contracts. In Solidity, we will now learn about require statements.
Solidity require are statements that are added in the functions to stop them if a certain condition is not met. Think of the following scenario: Users can only call a function if a certain statement is true. In this case, the _amount must be higher than zero.
function myFunc(uint256 _amount){
require(\_amount > 0, "Amount must be greater than 0");
}
Now, in the frontend, let's write the corresponding function using wagmi hooks with react
First we need to import the useWriteContract hook from wagmi like so :
import { useWriteContract } from "wagmi";
Then, initiate it in our component as follows:
const { writeContract, failureReason} = useWriteContract();
You see we also destructure failureReason from useWriteContract hook. We will use this failureReason to see why the function reverted.
Now let's call the Solidity function
const callMyFunc = async () => {
try {
writeContract({
abi,
address,
functionName: "myFunc",
args: [0],
});
} catch (error) {
console.log(error);
}
};
This is just basic function call. The thing is, since we're passing zero as an argument, the function call will fail/revert. If we logged the failureReason, we'd get something like this:
"ContractFunctionExecutionError: The contract function "myFunc" reverted with the following reason:
Amount must be greater than 0.
Contract Call:
address: 0xD...dc5b6
function: myFunc()
sender: 0x1A...667D"
Of course, in a real world scenario, we'd not just log the error message but maybe display it with a pop-up. Totally up to you.
Top comments (2)
Please, consider editing your article for readability. Thanks.
sure mate