Views
Views are a way for contracts to expose information to other contracts and to off-chain consumers.
Contracts can store the source code of their views either on-chain or off-chain:
- The code of on-chain views is stored in the smart contract code itself, like entrypoints.
- The code of off-chain views is stored externally, usually in decentralized data storage such as IPFS. The contract metadata has information about its off-chain views that consumers such as indexers and other dApps use to know what off-chain views are available and to run them.
On-chain and off-chain views have the same capabilities and limitations.
For more information about views, see Views on docs.tezos.com.
Defining on-chain views
To define an on-chain view, use the @view
decorator.
Defining off-chain views
To compile an off-chain view, create a function, compile it as an expression, and put the expression in the contract's metadata.
To compile an expression as a off-chain view, use the LIGO compile expression
command and pass the --function-body
flag.
To use an expression from a file, pass it in the --init-file
argument.
For example, this file has a contract named C
with a function named v
:
To compile the function v
as an off-chain view, pass C.v
to the compile expression
command, as in this example:
The response is the function compiled to Michelson. It is up to you to store this code and link to it from the contract metadata.
Note that the function is not annotated as an entrypoint or on-chain view; it is just a function declared in the context of the contract.
Calling views
Contracts can call on-chain and off-chain views with the Tezos.call_view
function and use the result immediately.
const call_view : string => 'arg => address => option <'ret>
The function accepts these parameters:
- The name of the view
- The parameter to pass to the view
- The address of the contract
For example, this contract has a view that multiplies the integer in storage with the integer that the caller passes and returns the result:
This contract stores the address of the first contract and calls its view:
This test deploys both contracts, calls the contract that calls the view, and verifies the result: