Offchain-views โ
Introduction โ
Offchain views are functions stored outside of the blockchain in the metadata JSON file associated to a contract. Off-chain views let people get more structured info from the the contract without having to send a transaction nor use a wallet. They can simplify decentralized applications job by abstracting the contract's storage.
They can be compiled from SmartPy into Michelson like the contract's code and they can be called without wallet nor transaction to the chain.
Their code is similar to what can be found in an entrypoint except that they are read-only (they cannot write the storage and they don't create operations) but they can return a value. Also, as they are executed outside of the chain, they are not limited by gas.
See Defining an off-chain view for more info.
The full specification is available in TZIP-16.
Build a metadata object with offchain views. โ
In the code snippet below, we have a contract example that builds a metadata object. It compiles the functions get_x
and get_storage
functions into Michelson to be used as off-chain views.
import smartpy as sp
class MyContract(sp.Contract):
def __init__(self, **kargs):
self.init(**kargs)
# A python dictionary that contains metadata entries
metadata = {
"name": "Contract Name",
"description": "A description about the contract",
"version": 1,
"views" : [self.get_x, self.get_storage],
}
# Helper method that builds the metadata and produces the JSON representation as an artifact.
self.init_metadata("example1", metadata)
@sp.offchain_view(pure = True)
def get_x(self, params):
"""blah blah ' some documentation """
sp.result(sp.record(a = self.data.x, b = 12 + params))
@sp.offchain_view(doc = "The storage")
def get_storage(self):
sp.result(self.data.x)
@sp.add_test("test")
def test():
s = sp.test_scenario()
s += MyContract(x = 1)
{
"name": "Contract Name",
"description": "A description about the contract",
"version": "1",
"views": [
{
"name": "get_x",
"pure": true,
"description": "blah blah ' some documentation ",
"implementations": [
{
"michelsonStorageView": {
"parameter": { "prim": "int" },
"returnType": {
"prim": "pair",
"args": [{ "prim": "int" }, { "prim": "int" }]
},
"code": [
{ "prim": "UNPAIR" },
{
"prim": "PUSH",
"args": [{ "prim": "int" }, { "int": "12" }]
},
{ "prim": "ADD" },
{ "prim": "SWAP" },
{ "prim": "PAIR" }
]
}
}
]
},
{
"name": "get_storage",
"pure": false,
"description": "The storage",
"implementations": [
{
"michelsonStorageView": {
"returnType": { "prim": "int" },
"code": []
}
}
]
}
]
}