Given that this is a sample balanceOf function code:

function balanceOf(address tokenOwner) public view returns (uint balance) {
    return balances[tokenOwner];

and this function is view function, does it's execution cost gas? If I understand correctly, balances array has to be read with SLOAD, and this is not gas free. balances is mapping(address => uint256) variable.

So how come that sites like etherscan.io provide interface to query balance of erc-20 tokens for free? E.g. this old EOS token contract, where I can run balanceOf on any address and get response instantly free of charge.

Thanks for explaining!

1 Answer 1


In Ethereum there are two ways of interacting with a smart contract: transactions and calls.

Calls are possible only for function which are marked as pure or view. If you issue a call to such function the result is fetched directly from the node which you are connected to - the actual blockchain is not involved. Your node should have the most recent data (if it's synchronized) so there's no need to consult the actual blockchain. These kind of operations are always read-only operations. Calls do not cost any gas.

The other way to interact with a smart contract is by a transaction. They are used for changing the state but also for reading the state. Basically a transaction is used for anything which is not a read-only operation and which needs to go to the blockchain.

The tricky part is that a transaction can also read data. In that case the reading costs gas. You can issue a transaction to only read some data and pay for it even if you could just read it for free with a call. But typically a transaction performs state updates, calculations and read operations and it has to pay for each operation. So it's a matter of context - whether reading is performed in a transaction or in a call.

  • 1
    Ok but what if I call balanceOf() from within a smart contract? Like in contract A I want to know the balance of tokenX for address Y. Does this cost gas?
    – flo
    Dec 30, 2021 at 22:17

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.