Search code examples
ethereumblockchainsoliditysmartcontractsremix

solidity get contract address issue


    // SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 < 0.9.0;
contract Receiver{
    
    function getAddress() public view returns(address){
        return address(this);
    }
  
}

contract Caller{
    Receiver receiver;
    constructor(){
        receiver = new Receiver();
    }

    function getAddress() public view returns(address){
        return receiver.getAddress();
    }
  
}

My question is: when testing the above code on Remix, I couldn't get the same address, why? here is the ss:enter image description here many thanks!


Solution

  • Here is the catch: The new keyword deploys and creates a new contract instance. in Caller's contract's constructor you are actually deploying a new instance of Receiver. I add another function to get the deployed Receiver instance

    contract Caller{
        Receiver receiver;
        constructor(){
            // you created a new Receiver instance
            receiver = new Receiver();
        }
        // By calling this you are not interacting with the Receiver instance that you separately deployed on Remix.
        // this interacts with the Receiver instance which is deployed in the constructor
        function getAddress() public view returns(address){
            return receiver.getAddress();
        }
        // this returns the address of deployed Receiver instance 
        function deployedReceiverAddress() public view returns(address){
            return address(receiver);
        }
    }
    

    you do not have to deploy Receiver contract on remix. Caller will already deploy a new contract. in the above both functions in Caller returns same result:

    enter image description here