If one smart contract reads data from another smart contract, does it costs gas?
Asked Answered
N

1

5

When one contract's function read data from second contract's function (that is, there is no state change on the second contract). Does it consumes gas?

Nonresident answered 21/1, 2020 at 8:42 Comment(0)
R
8

1) Queries

If you just want to get information without changing state then yes you can query a contract for free. Querying means you can call any function that is marked as view or pure and there is no gas cost. In these cases whatever node you ask can answer the query immediately without having to ask any other node.

2) Transactions

If you want to modify state then there is a gas cost, and you have to send a transaction and pay the gas.

3) Queries inside Transactions

I thought your original question was about whether there was a cost to querying inside a transaction. This does consume additional gas. I tried this experiment in Remix with Solidity 0.6.1 (most code omitted for clarity):

   // Gas used = 24,656
   function SetSomethingInAnotherContract_WithoutCall() public
   {
       anotherContract.SetSomething(4);
   }

   // Gas used = 28,124
   function SetSomethingInAnotherContract_WithCall() public
   {
       uint temp = anotherContract.GetSomething(); // in a query this would be free
       anotherContract.SetSomething(4);
   }

I think it makes sense that it should incur a cost because a query can be answered from a single node, but the transaction calls have to be validated by all nodes.

Receptacle answered 21/1, 2020 at 16:43 Comment(5)
I just want to get some data from another contract without changing anything on that contract. Does it would be free or cost some gas?Nonresident
I misunderstood your question, I've clarified the answer.Receptacle
And can I query any number of times? Because my contract will make frequent read calls to another contract.Nonresident
If you're in case 1 above (sending queries) then there are at least these limitations: a) There are limits on contract size that limit the max amount of solidity code per contract. b) The node you execute the query against may have limits on frequency of calls. If you run your own node you have control over this limitation.Receptacle
@KS In your second example if GetSomething was internal function would it cost same?Desirous

© 2022 - 2024 — McMap. All rights reserved.