As of December 3rd, 2021, the protocol update Hangzhou is active and brings a new feature, Views. There are several articles already talking about what Views are , and in this article, we’re going to look closely at how Views work and provide advice for using it.
When one smart contract “views” another via the VIEW instruction, the entire “viewed” smart contract will first be loaded from the Tezos storage, and then parsed into 4 parts:
- the argument
- the storage
- the code
- a map of Views where we can retrieve the view specified by the given view name
After parsing, the Tezos node performs type checking, followed by executing the specified view code of the “viewed” smart contract. Afterwards, the VIEW instruction returns an option type: Either a Some a if the execution of view code succeeds, or a None if anything goes wrong during the process. This entire process, unsurprisingly, requires costs. That is to say, each time the VIEW instruction is used, the required costs will be charged repeatedly.
Here are some tips for reducing the costs of using views:
- Instead of calling the same view multiple times as the following example,
We recommend to have a single VIEW instruction and then use the DUP instruction to duplicate and thus avoid the heavy costs. For instance, in general, the following pattern of using VIEW is more preferable.
- Only define views that are essential. The more views defined in a single smart contract, the higher the cost of parsing that contract.
- Use simple names for your views. A view name is actually typed as a string. This means the viewing costs correlate with the length of the view name.
Though it has not yet been integrated with Views, the cache mechanism, another feature introduced in Hangzhou, provides potential for reducing the runtime costs of using smart contracts. In the near future, it is possible that Views could be cached, shortening execution time and lowering the gas and XTZ costs. For anyone interested, here is the relevant issue.
If you want to know more about Marigold, please follow us on social media (Twitter, Reddit, Linkedin)!