Solidity return function why the constant?
Asked Answered
R

2

9

I am just starting with solidity. I have a function like so:

function get() constant returns (uint) {
    return storedData;
  }

What is the use of the constant keyword here? I understand that after this keyboard we are defining the return type but why does it need constant in front of it? Are there alternatives to this such as var?

Rhaetian answered 24/8, 2017 at 17:20 Comment(0)
E
15

The "constant" keyword means that function will not alter the state of the contract, that means it won't alter any data, and so contract state and data remain... constant.

Such a function does not consume gas when executed by itself in your node (it may add to gas consumption if ran inside a function that alters contract state/data, because such a function call will need to be executed by miners and included in a block.

Editorial answered 25/8, 2017 at 2:43 Comment(3)
Excellent! Thanks for your answer.Rhaetian
What about function set(uint x) { storedData = x; } what would happen if I add the keyword constant to this? Why does the get need the word constant? Would it cost gas if omitted even though it doesn't modify data?Rhaetian
"constant on functions used to be an alias to view, but this was dropped in version 0.5.0." docs.soliditylang.org/en/v0.8.10/…Chaves
D
3

To give a little more context a constant declaration indicates that the function will not change the state of the contract (although currently this is not enforced by the compiler).

When generating the compiled binaries, declaring a function constant is reflected on the ABI. The ABI is then interpreted by web3 to figure out whether it should send a sendTransaction() or a call() message to the Ethereum node. Since calls are only executed locally, they're effectively free.

See this snippet from the web3.js library:

/**
 * Should be called to execute function
 *
 * @method execute
 */
SolidityFunction.prototype.execute = function () {
    var transaction = !this._constant;

    // send transaction
    if (transaction) {
        return this.sendTransaction.apply(this, Array.prototype.slice.call(arguments));
    }

    // call
    return this.call.apply(this, Array.prototype.slice.call(arguments));
};

Calling a constant function from another contract incurs the same cost as any other regular function.

Drummond answered 25/8, 2017 at 21:12 Comment(2)
If it incurs the same cost, why do I need it then? Why is it used in the ERC20 balanceOf() function? the function only returns return balances[_owner]; and changes no state. Where is the sense of it?Pottage
just to be more clear, is it not better a developer uses the view modifier for a function instead of constant as view function ensures that the state of the contract is not altered & it also enforces thatRain

© 2022 - 2024 — McMap. All rights reserved.