Huowuge
Huowuge

Reputation: 61

can I use address(this) to call a contract?

I want to set a function that the address of caller is address(this), which means the smart contract address itself, instead of msg.sender in solidity. Is that possible?

If it's possible, could you please show me the function code example?

If it's impossible, is it the feature of ethereum, or solidity constain? I mean if I can use other blockchain language to do it?

Upvotes: 0

Views: 894

Answers (1)

Petr Hejda
Petr Hejda

Reputation: 43581

When a contract performs an external call to its own (external or public) function, the value of msg.sender equals to address(this) in this called function.

For example:

pragma solidity ^0.8;

contract MyContract {
    function isMsgSenderAddressThis() public view returns (bool) {
        return msg.sender == address(this);
    }
    
    function yes() external view returns (bool) {
        // makes an external call to itself
        // same as MyContract(address(this)).isMsgSenderAddressThis()
        return this.isMsgSenderAddressThis();
    }

    function nope() external view returns (bool) {
        // this is an internal call, so it returns false
        return isMsgSenderAddressThis();
    }
}

Upvotes: 1

Related Questions