Ethernaut Challenge-1 Fallback
So the task is that we have a smart contract available with us.
The code goes like this
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Fallback {
mapping(address => uint) public contributions;
address public owner;
constructor() {
owner = msg.sender;
contributions[msg.sender] = 1000 * (1 ether);
}
modifier onlyOwner {
require(
msg.sender == owner,
"caller is not the owner"
);
_;
}
function contribute() public payable {
require(msg.value < 0.001 ether);
contributions[msg.sender] += msg.value;
if(contributions[msg.sender] > contributions[owner]) {
owner = msg.sender;
}
}
function getContribution() public view returns (uint) {
return contributions[msg.sender];
}
function withdraw() public onlyOwner {
payable(owner).transfer(address(this).balance);
}
receive() external payable {
require(msg.value > 0 && contributions[msg.sender] > 0);
owner = msg.sender;
}
}
Now somehow we need to claim ownership of this smart contract. For that we first generate an instance of the smart contract using the button that is already provided by ethernaut.
Now to claim ownership and transfer all the funds to a specific address we first copy the contract code inside remix ide and compile it. As we already have the instance address we can just create an object to interact with inside the IDE.
Firstly we call the contribute function of the instance with a ether value less than 0.001 ethers. For that we can use online calculators to convert the ethers value to wei or gwei respectively.
After that once the address becomes a contributor we can send some ethers directly to the contract address via metamask so that because of the flaws in the receive function we get the ownership of the smart contract.
Now we can just call the withdraw function to drain all the funds.