Solidity – Does Executing View or Pure Functions Cost Gas?

contract-deploymentcontract-designcontract-development

Let's suppose i have the following code in ethereum's solidity function:

function getArray() external pure returns(uint[]) {
  // Instantiate a new array in memory with a length of 3
  uint[] memory values = new uint[](3);
  // Add some values to it
  values.push(1);
  values.push(2);
  values.push(3);
  // Return the array
  return values;
}

As it's pure, it doesn't even read data from storage, doesn't change anything in storage. So imagine I deployed this contract. then there're people who want to invoke this function from web3.js or remix for example. Will this function cost them gas? I've read that view functions and pure functions are the way that don't change the storage. so they're free (no gas). If users use above function, why is it free? i still make the calculation and save temprorary data to memory.

Best Answer

It depends,

If they call a pure function itself, like the one in your example, getArray(), then no, it won't cost anything.

However, if they call a function which isn't pure or view, and that function internally calls the getArray() function, then they will have to pay for the whole transaction.

Related Topic