Michelson onchain views
Context
Currently, there is no direct way to get output from another contract. This MR adds a mechanism to declare a view that takes a value and the current storage of the contract as input and returns a value as output.
- TZIP:
- version 0: https://gitlab.com/tzip/tzip/-/merge_requests/108
- version 1: tzip!169 (merged)
- Tezos Agora: https://forum.tezosagora.org/t/views-tzip/2560/14
A new toplevel keyword view
is introduced for declaring views in Michelson scripts; each script can declare 0, 1, or several views.
Views are named using strings, in a given script views should have distinct names.
The syntax of a view declaration is:
-
view name 'arg_ty 'return_ty { (instr) ; ... }
: This view should be defined in the top-level. Like the main Michelson program, it maintains a stack and its initial value contains a pair in which the first element is an input value and the second element is the contract storage.
To call views from other contracts, a new instruction VIEW
is introduced.
-
VIEW name 'arg_ty 'return_ty
: It allows to use of predefined view in top-level and a result can be obtained immediately. If the given address or name is nonexistent,None
will be returned. Otherwise,Some a
will be returned.
VIEW name 'arg_ty 'return_ty :: 'arg_ty : address : 'S -> option 'return_ty : 'S
Here is an example of contracts:
In the first contract, it defines two view
s in top-level which named add_v
and mul_v
.
{ parameter nat;
storage nat;
code { CAR; NIL operation ; PAIR };
view "add_v" nat nat { UNPAIR; ADD };
view "mul_v" nat nat { UNPAIR; MUL };
}
In this contract, it calls the add_v
of the above contract and obtains a result immediately.
{ parameter (pair nat address) ;
storage nat ;
code { CAR ; UNPAIR; VIEW "add_v" nat nat ;
IF_SOME { } { FAIL }; NIL operation; PAIR };
}
reference: https://forum.tezosagora.org/t/adding-read-only-calls/1227
Manually testing the MR
The following is for manually running test cases of this change.
poetry run pytest tests_alpha/test_contract.py -k testView
Checklist
-
Document the interface of any function added or modified (see the coding guidelines) -
Provide automatic testing (see the testing guide). -
Add item in the Development Version
section ofCHANGES.md
(only for new features and bug fixes).