Skip to main content

Views

Views are a way for contracts to expose information to other contracts.

A view is similar to an entrypoint, with a few differences:

  • Views return a value.
  • Contracts can call views and use the returned values immediately. In other words, calling a view doesn't produce a new operation. The call to the view runs immediately and the return value can be used in the next instruction.
  • Calling a view doesn't have any effect other than returning that value. In particular, it doesn't modify the storage of its contract and doesn't generate any operations.

Example View

Here is an example that uses a view. The following contract is a ledger that handles a fungible token and keeps track of how many tokens are owned by each user.

Ledger contract
StorageEntrypoint effects
  • ledger: big-map
    • Key:
      • user: address
    • Value:
      • tokens: nat
  • view getBalance(user: address)
    • return ledger[user].tokens
  • transfer(nbTokens, destination)
    • Check that tokens[caller].tokens >= nbTokens
    • Create an entry tokens[destination] (value = 0 if it doesn't exist)
    • Add nbTokens to tokens[destination].nbTokens
    • Subtract nbTokens from tokens[caller].nbTokens

Another contract might provide an equalizeWith entrypoint such that if they have more tokens than another user, they can make their balances equal (plus or minus one if the total amount is odd). The following example code for this contract takes advantage of the getBalance(user) view of the first contract: to determine the balance of each user:

equalizeWith(destination)
destinationBalance = ledger.getBalance(destination)
totalBalance = ledger.getBalance(caller) + destinationBalance
targetBalance = totalBalance // 2
ledger.transfer(targetBalance - destinationBalance, destination)

Implementation details