0

In the following generalised code example, would myMethod still be free (no gas cost) to call from outside the contract? Even if it does a series of operations including abi.encodePacked()?

contract A{
    struct Data{
        uint8 num;
        bool include;
    }
    mapping (address => Data) dataMap;
/*
    more functions
*/

function myMethod() public view returns (string){
    string[2] memory array = ['a', 'b'];
    if(dataMap[msg.sender].include){
        return string(abi.encodePacked(array[dataMap[msg.sender].num], 'c'))
    }
    return array[dataMap[msg.sender].num];
}

}

1 Answers1

1

Yes, it is always free to call the view function outside the contract. However, they do cost gas when you call it inside a transaction.

trizin
  • 914
  • 5
  • 11
  • thank you for the answer. imagine a function that made 50 keccak256(abi.encodePacked('string calls')) internally but didn't alter account storage. Presumably those are calculations the EVM needs to process(?). Are those not costly calculations needed to be accounted for? – Andreas Dilaveris Oct 09 '21 at 16:41
  • Afaik, the calculations are being made on your local and the chain is only being used for reading data. – trizin Oct 09 '21 at 16:47