9

Using Mix, if I create a contract in the scenario with address A as a parameter, clicking on getConstant in the html below returns A as I would expected it, and I see a JS flagged transaction.

If now I click on getPublic which is pretty much the same function bare the constant / public keyword I got a pending transaction in the scenario and an address that is not the one I expect.

So I might NOT understand something fundamental about what public means or implies but I fail at seeing what it is.

I have set this basic contract / html for this question :

contract constantOrPublic {
    address creator;
    address otheraddress;

    function constantOrPublic(address _otheraddress) 
    {
        creator = msg.sender;
        otheraddress = _otheraddress;
    }

    function getConstant() constant returns(address) {
        return otheraddress;
    }
    function getPublic() public returns(address) {
        return otheraddress;
    }

}

and this html page:

<!doctype>
<html>
<head>
<script type='text/javascript'>

function getConstant() {
    var param = document.getElementById('c').value;
    var res = contracts['constantOrPublic'].contract.getConstant();
    document.getElementById('c').innerText = res;
}

function getPublic() {
    var param = document.getElementById('p').value;
    var res = contracts['constantOrPublic'].contract.getPublic();
    document.getElementById('p').innerText = res;
}

</script>
</head>
<body >
<div>
getConstant:
    <div id='c'>none</div>
    <button onclick='getConstant()'>getConstant</button>
</div>
<div>
getPublic:
    <div id='p'>none</div>
    <button onclick='getPublic()'>getPublic</button>
</div>
</body>
</html>
8

I'm not sure which part of the system assumes this (web3.js?), but if you don't declare a a function as constant it's assumed it's going to change contract state and thus sets up a transaction.

The declaration should look like this (note, I didn't compile it):

function getPublic() public constant returns(address) {

I checked the solidity docs, I'm not sure public is a useful keyword for a function, because public is the default.

|improve this answer|||||
  • 2
    public is more useful for contract data. – Paweł Bylica Mar 31 '16 at 21:37
  • 4
    You are correct, constant only matters in that web3.js interprets myContract.getPublic() as myContract.getPublic.call() if it is constant, and myContract.getPublic.sendTransaction() otherwise. – Tjaden Hess Apr 1 '16 at 2:28
8

simply put, the "constant" indicates that no transaction is needed and no gas/eth will be used. It is the same as getting the value of a contract's property. Public indicates visibility to outside code.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.