Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solidity return function why the constant?

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?

like image 984
Kex Avatar asked Dec 18 '22 04:12

Kex


2 Answers

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.

like image 179
Fatima Maldonado Avatar answered Dec 27 '22 07:12

Fatima Maldonado


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.

like image 26
Yao Sun Avatar answered Dec 27 '22 06:12

Yao Sun