0

I've read in the documentation that reading data from the blockchain does not cost gas. It costs gas only when saving data to the blockchain or when executing operations like +, -, * etc (see the opcodes).

BUT, I've created this simple contract:

pragma solidity ^0.5.0;
contract A{
    uint public x = 10;
    function get_x() public view returns(uint){
            return x;
    }
} 

When calling get_x() in remix it says: execution cost: 413 gas (Cost only applies when called by a contract). What does it mean? Do I have to pay gas for calling get_x(). If yes, why?

More that that, if I get the value of x whitout calling the get_x() getter function (it's a public variable so a getter with the same name x() is automatically created) I get another gas value: execution cost: 383 gas (Cost only applies when called by a contract)

2 Answers 2

2

execution cost: 413 gas (Cost only applies when called by a contract)

It means that the specified cost will apply only if the function is called from a non-constant function (in this contract or in another contract).

A non-constant function is function which is neither pure nor view (nor constant in earlier compiler versions).

1

Read-only function may be called off-chain, i.e. without publishing transaction into blockchain. In this case, nobody has to pay for gas the functions consumes, because gas is paid to miners for including transaction into block, but as long as there is not transaction to include, there is nothing to pay miners for.

Technically, this means that Ethereum node executes transaction locally, the same way as miner would execute it, obtains execution result, but does not include transaction into block. Though, when transaction is being executed locally, EVM still counts how much gas does it use, and this calculated value is what Remix shows to you. You may need this number to estimate how much gas the function will use when called on-chain, i.e. in published transaction, called directly or from another contract.

AS long as there is not a much sense to execute read-only functions directly, basically paying for what could be obtained for free, the only reasonable case when such function will actually consume gas is when it is called from another contract in on-chain transaction. That's why message says: Cost only applies when called by a contract, though this message is not fully correct, because it is indeed possible to call read-only function on-chain directly.

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.