...by Daniel Szego
quote
"On a long enough timeline we will all become Satoshi Nakamoto.."
Daniel Szego

Wednesday, January 2, 2019

Solidity Tips and Tricks - security of the view modifier of a function


Solidity view function modifier means that the function do not modify the storage of the contract, due to the fact that it costs no gas to call this function. However, one might as well assume this feature as a security guarantee, meaning that the function can not modify the storage.  It is important to note however that in the 4. compiler versions there is actually no guarantee for that, the compiler gives a warning, but despite it compiles and deploys the contract without error. As an example, considering the following contracts:

pragma solidity ^0.4.24;

contract ViewImplementation {    
 uint public storageVariable = 0;
    
 function viewFunction() view external returns (uint) {
   storageVariable = 2;
   return 1;
 }
}

contract TestViewImplementation {
    
  address contractAddress =
           0xbbf289d846208c16edc8474705c748aff07732db;
    
 function testView() public {
   ViewImplementation imp =  ViewImplementation(contractAddress);
   imp.viewFunction();
 }  
}

Calling the viewFunction externally implied zero gas consumption and the storageVariable will not be modified. However, calling the function from another contractlike from testView will modifiy the storageVariable to 2.

The situation is fortunately better in the 5+ solidity versions, as there is not only warning but a compiler error as well in such a situations.