This repo contains the solidity smart contract used to hack Ethernaut Lvl 27 - Good Samaritan. Find the step by step walkthrough below.
-
Let's create a function inside GoodSamaritanAttack.sol called
attack()
. This functioncallsrequestDonation()
in the GoodSamaritan contract. -
Notice
thatrequestDonation()
is trying to transfer only 10 tokens inside the try block, and only if it gives an error it executes the code insidecatch
. The code insidecatch
transfers all the balance available in the wallet if the encoded error isabi.encodeWithSignature("NotEnoughBalance()")
. Now, as we know about custom errors, our motive is to revert an error defined aserror NotEnoughBalance();
. -
When the
requestDonation()
is called byattack()
, it will transfer 10 tokens, and the Coin contract will execute functionnotify(uint256 amount)
defined ininterface INotifyable
. This will only be executed ifmsg.sender
is a contract address. So, let's create a function inside GoodSamaritanAttack.sol whose function signature looks exactly like functionnotify(uint256 amount) external;
. -
Remember, our goal was to
revert NotEnoughBalance();
. So, let's define anerror NotEnoughBalance();
and callrevert NotEnoughBalance();
inside functionnotify(uint amount)
in GoodSamaritanAttack.sol. -
Now, the
try
block will revert with an error and trigger the code insidecatch
. Will this transfer the entire wallet balance and drain the contract? Nope! When thecatch
code will execute, the Coin contract will again call functionnotify(uint256 amount)
and hence willrevert
again. So, we can simply write anif
condition to check if the transfer amount is 10 and onlyrevert NotEnoughBalance()
in that case. -
Deploy GoodSamaritanAttack.sol and call the function
attack()
.
WOAH!! The contract has now been successfully hacked!!!
Find the complete walkthrough at https://blog.blockmagnates.com/ethernaut-lvl-27-good-samaritan-walkthrough-custom-errors-in-solidity-17c7e20fb58a