Level 7 of Ethernaut is Force, a lesson in self destruction.
Some contracts will simply not take your money
¯\_(ツ)_/¯
The goal of this level is to make the balance of the contract greater than zero.
Things that might help:https://ethernaut.openzeppelin.com/level/7
- Fallback methods
- Sometimes the best way to attack a contract is with another contract.
- See the Help page above, section “Beyond the console”
We are given this contract that contains a cat:
Since the contract has no payable fallback functions we can’t send ether to the contract in the traditional ways.
But the hints let us know to use another contract to attack, enter selfdestruct()
Self Destruct
Contracts can be deleted from the blockchain by calling
selfdestruct
.selfdestruct
sends all remaining Ether stored in the contract to a designated address.Vulnerability
A malicious contract can use
https://solidity-by-example.org/hacks/self-destruct/selfdestruct
to force sending Ether to any contract.
Solidity by example explains that the selfdestruct function can be used to delete a contract from the blockchain and forward all the remaining ether to an address.
This example from alchemy does a good job at explaining a destroy function that I’m going to steal for my attack on the level.
Open up Remix and create a new workspace for this level.
Create a new file named force.sol
and paste the contract source code.
Compile the contract with the green arrow or ctrl+s
, change your deployment environment to MetaMask.
Paste your instance address into the At Address box and click.
Create a new file destruct.sol
to house our attacking contract.
Heading back to that Alchemy post I’m going to steal that destroy function
Copying over the pragma and MIT license from the cat contract, wrap the function with the contract declaration contract Destruct { }
Lastly we need to add the constructor and make it payable, this way we can fund the contract upon deployment.
The complete destruct.sol contract should look like this:
Compile your destruct.sol and then let’s add some Wei to the deployment transaction so that when we selfdestruct it will forward the balance.
Scroll down to the deployed contracts, you will see the original Force at your instance address.. copy this address.
Below should be your Destruct contract with a balance.
After copying the Force address, paste it into the destroy function box and click transact.
Once the transaction is mined you should see the balance of the Force contract is no longer 0.
All that’s left is to submit your instance.
Congratulations, we selfdestructed our contract to break the balance and complete the level.
DAVE