Solidity

modifiers

1. Visibility modifiers

tell us how the function interacts with the BlockChain

  • private: only callable from other functions inside the contract
  • internal: like private but can also be called by contracts that inherit from this one
  • external: can only be accessed from external contracts or accounts
  • public: can be called anywhere, both internally and externally

2. State modifiers

tell us how the function interacts with the BlockChain

  • view: by running the function, no data will be saved/changed
  • pure: not only does the function not save any data to the blockchain, but it also doesn't read any data from the blockchain

view and pure don't cost any gas to call if they're called externally from outside the contract (but they do cost gas if called internally by another function)

3. Custom modifiers

solidity

contract MyContract {
    address owner;

    modifier onlyOwner() {
        require(msg.sender == owner);
        _;
    }
}

4. payable modifier

Special type of function that can receive Ether.

solidity

contract OnlineStore {
  function buySomething() external payable {
    // Check to make sure 0.001 ether was sent to the function call:
    require(msg.value == 0.001 ether);
    // If so, some logic to transfer the digital item to the caller of the function:
    transferThing(msg.sender);
  }
}

DApp's JS frontend

js

// Assuming `OnlineStore` points to your contract on Ethereum:
OnlineStore.buySomething({from: web3.eth.defaultAccount, value: web3.utils.toWei(0.001)})

Data Locations

When declaring reference type variables(Array, Struct, Mapping) in Solidity, you must specify data location.

  • storage
    refers to the space where state variables are stored. That is, all state variables are stored in Storage. In fact, all data stored in blockchain corresponds to storage.
  • memory
    Memory literally means a place where volatile data that exists only when a function call (external function call) is located. Data is copied from calldata passed as a function argument to new memory and used.
  • calldata
    Only available for external function call parameters. The main difference between Calldata and Memory is that Memory can be modified, but Calldata cannot be modified.

However, in the case of mapping, only Storage is allowed, like state variables. Bytes and string types are also treated as arrays. Therefore, the Data Location must be specified for these types too.

Best practice for data location

  1. If you want to store reference type variables directly in the blockchain and update their values, use storage.
  2. If you only need to read, or do not need to update state on the blockchain, but need to modify it, use memory.
  3. You can save gas by using the calldata keyword as a function parameter. Therefore, unless there is a special reason, use calldata.

Resources