1 - Fallback

fallback() function and receive() function

Ethernaut Level1: Fallbackarrow-up-right

// 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;
  }
}

Goal of this level

  • claim ownership of the contract

  • reduce its balance to 0

What you should know before

Solution

chevron-rightKey to solve this problem 🔑hashtag

using recieve function

1. Claming Ownership

1) contribution

2) receive() function

2. Reducing balance of the contract to 0

Since now we have ownership of the contract, we can withdraw all the balance of the contract.

Let's check if we successfully drained the contract.

Done! 😎

Last updated