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.
Storage | Entrypoint effects |
---|---|
|
|
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
- Michelson: Operations on views
- Archetype: View
- SmartPy: Views in testing
- LIGO: On-chain views