2

Function returns null address in any case.

pragma solidity ^0.4.9;

contract Test {

    address da;
    function getSender () constant returns (address){
        da=msg.sender;
        return da;
    }
}

Tried through myetherwallet and parity, network is not synchronized.

4
  • 1
    I've tested your code and the function getSender() correctly returns the address. Commented Jul 23, 2017 at 21:34
  • In your code you are storing msg.sender in the variable da, such function cannot be constant because your are modifying the contract state.
    – Ismael
    Commented Jul 24, 2017 at 3:02
  • Why not just return msg.sender; ? Commented Jul 24, 2017 at 4:04
  • Do I need an ether on the contract to perform this function?
    – Aliev
    Commented Jul 24, 2017 at 6:52

4 Answers 4

1

In a query function you are trying to update contract state variable. You can return msg.sender without using any variables

pragma solidity ^0.4.9;

contract Test {
    address da;
    function getSender () constant returns (address){
        return msg.sender; // just return msg.sender
    }
}
1

You either return msg.sender without updating "da" state variable so it's truly a constant function, or you don't make it constant but you'll have to get the return value out of an event if you want to access it.

Constant/view functions can't modify state variables in any way.

1

You can set the msg.sender to da in the constructor and than just return da with the modifier View.

pragma solidity ^0.4.9;

contract Test {

    address da;

    function Test() public {
        da = msg.sender;
    }

    function getSender () public view returns (address){
        return da;
    }
}
0

You can update a state variable, or you can make the function read-only (with constant, view or pure), but you can't do both. I've upvoted three answers that say it differently and offer different approaches depending on what you need it to do.

pragma solidity 0.4.9;

contract DA {

    address public da;

    function DA() public {
        da = msg.sender;
    }

    function setDa() public returns(bool success) {
        da = msg.sender;
        return true;
    }

    // getDa() is not really needed because da is made `public` near line 5, so function da() does the same.

    function getDa() public constant returns (address){
        return da;
    }

    function getMsgSender() public constant returns(address) {
        return msg.sender;
    }
}

Hope it helps.

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.