DocumentationSubgraphsBasicsView Function Calls

View Function Calls

Sometimes the contracts don’t emit all the required information in the events and our subgraph needs to access the smart contract state to squire that missing bit of information. The code generated with [graph codegen](The%20Graph%20CLI%203e53884883174963a86a1a7aca17d9e2.md) also includes AssemblyScript contract bindings that can be used to access public state variables and call view/pure functions.

Couple of things to note here:

  1. You can only read data from the smart contracts, it is not possible to make transactions from the mappings/handlers.
  2. The function will access the state of the contract at the current block, i.e. the block in which the event or transaction has occurred if using event or call handlers, or the current block the block handler is indexing.
  3. Lets say two transactions that change the same state variable take place in the same block and those transactions emit an event, in our handler we call a contract function to get the value of that variable. In both cases when the handler is triggered, the returned value of the contract call will be the latest contract state, i.e. the value after the second transaction. Keep that in mind if you want to use the value to aggregate or calculate something.
  4. The graph codegen command will generate two methods for each read contract function, one with the original name of the function and one prefixed withtry_ , for example symbol() and try_symbol() for ERC20 contracts. The difference between the two is that if the function call reverts symbol() will throw an error and try_symbol() will return a result, which can be checked if the call has reverted.

Examples on how to perform contract calls and handle reverted calls can be found in the official TheGraph documentation.

Keep in mind that making contract calls will greatly impact the performance of the subgraph and the sync speed:

  1. Use them only when necessary and there’s absolutely no way to get the desired data another way.
  2. Try not to use many calls inside of a single handler.
  3. If it’s a static data, maybe you can use an initialisation handler to make the call once and save the data into an entity.

A great blog post about optimising your subgraph and reducing contract calls can be found here