Call vs transaction API in Ethereum

In Ethereum, there are 2 APIs to interact with a smart contract:

  • Calls (eth_call)
  • Transactions (eth_sendTransactions)

In Solidity (the language for writing Ethereum smart contracts), there are 2 kind of functions:

  • view functions, which don’t modify state variables
  • non-view functions, which DO modify state variables

Which Ethereum API to use for which function type in Solidity? This is often a source of confusion. Let’s clear this up!

In a nutshell:

  • If you want to write to the blockchain (i.e data writes or updates), you should use the Transaction API to execute a non-view function.
  • If you want to read data from the blockchain (read from smart contract storage or read result of a computation), you should use the Call API to execute a view function

call vs transaction API in Ethereum

For call => view function, you would have a code like this:

//web3
const result = await myContractInstance.methods.foo(1).call({from: '0xAb89...'});

//Solidity smart contract

function foo(uint a) view external returns(bool) {
  //do something
  return true;
}

For transaction => non-view functions, you would have a code like this:

//web3
const result = await myContractInstance.methods.bar(1).send({from: '0xAb89...'}); //send() instead of foo()

//Solidity smart contract   
function bar(uint a) external { //no "view" keyword
  //do something
  //No return statement
}

You will notice that there is no return statement in the non-view function. That’s because we can’t return anything from an Ethereum transaction.

Now, what most people don’t know is that you can also call use the Ethereum APIs in a non-natural way:

If you do this:

  • the state changes of the non-view functions will NOT be persisted in the blockchain after the function execution
  • the transaction will NOT be able to get the the return value of the view function

For the case transaction API => view function, there isn’t much value in doing this. However for the case Call API => non-view function, it could be interesting if you have a return statement in the function, or if you want to test that the function would not throw (and waste gas…) if you were to execute it in a transaction. This is a rare use case, but it’s good to know that you can do it.

Now, you should have understood that the 2 Ethereum APIs and the 2 function types of Solidity can be combined in any way, even though there is a “natural” combination and an “unnatural” one.

Leave a Reply

Your email address will not be published. Required fields are marked *