Search code examples
ethereumsolidityweb3js

what is the difference between this and address(this) in solidity


From the solidity document, I get to know that this is address of contract. Then why following contract throws errors, pragma solidity ^0.6.2;

contract Sample {
    function getContractAddress() public view returns (address) {
        return this;
    }
}

But typecasting this as address(this). Then what is the data type of this If I want keccak256, Should I use keccak256(abi.encodePacked(this, num)) // uint256 num OR keccak256(abi.encodePacked(address(this)), num) So that I can get the result of web3.utills.sha3(contractAddress, num) //contractAddress - address(this)


Solution

  • Prior to version 0.5.0, Solidity allowed address members to be accessed by a contract instance, for example this.balance. This is now forbidden and an explicit conversion to address must be done: address(this).balance.

    Source: https://docs.soliditylang.org/en/v0.5.0/units-and-global-variables.html

    So unless you're using deprecated version of Solidity (0.4.x and older), you need to use the conversion to address(this)

    keccak256(abi.encodePacked(address(this)), num)