0

I've been practicing Ethernaut Elevator problem. In this code, it just passing msg.sender to Building interface. But, I think that it should be passing deployed contract address of Building to use interface. Is it not necessary to use deployed contract for using interface?

I found answer about msg.sender with interface in the below link, that says It's just interpreting msg.sender as a type Building, no constructor is involved, it's just a type casting. But I don't really get it why interpret msg.sender as a type Building.

What does passing msg.sender to an interface do?

// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

interface Building {
  function isLastFloor(uint) external returns (bool);
}


contract Elevator {
  bool public top;
  uint public floor;

  function goTo(uint _floor) public {
    Building building = Building(msg.sender);

    if (! building.isLastFloor(_floor)) {
      floor = _floor;
      top = building.isLastFloor(floor);
    }
  }
}

1 Answer 1

1

First more information on msg.sender

You can't pass msg.sender is always the address calls the function. If another contract calls this function then msg.sender is that contract, if a EOA (Externally Owned Account, aka an address owned by a person) calls this function then msg.sender is the user's address. If you want to retrieve the first transaction sender then you should use tx.origin this will always return first EOA that starts the transaction.

Now we can analyse this contract.

interface Building {
  function isLastFloor(uint) external returns (bool);
}

This is the interface as you said so this should be a deployed contract.

Building building = Building(msg.sender);

They, assume this contract is called by a Building contract. If an EOA calls this function, it will revert since building.isLastFloor(_floor) will fail. So, it will work as:

EOA (user) calls Building contract Building contract makes an External call to Elevator contract so, msg.sender in Elevator contract becomes the Building contract.

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.