templates.upgradable_lambdas

 1import smartpy as sp
 2
 3##########################################################
 4# Upgradable Contract that uses lambdas
 5# https://tezos.gitlab.io/michelson-reference/#type-lambda
 6##########################################################
 7
 8
 9@sp.module
10def main():
11    class Upgradable(sp.Contract):
12        def __init__(self, value, logic):
13            self.data.value = value
14            self.data.logic = logic
15
16        @sp.entrypoint
17        def calc(self, data):
18            self.data.value = self.data.logic(data)
19
20        @sp.entrypoint
21        def updateLogic(self, logic):
22            self.data.logic = logic
23
24
25# Logic Version 1 (x, y)
26def logic1(data):
27    t = sp.record(x=sp.nat, y=sp.nat)
28    unpacked = sp.unpack(data, t).unwrap_some(error="Cannot UNPACK")
29
30    sp.result(unpacked.x + unpacked.y)
31
32
33# Logic Version 2 (x, y, z)
34def logic2(data):
35    t = sp.record(x=sp.nat, y=sp.nat, z=sp.nat)
36    unpacked = sp.unpack(data, t).unwrap_some(error="Cannot UNPACK")
37
38    sp.result(unpacked.x + unpacked.y + unpacked.z)
39
40
41@sp.add_test()
42def test():
43    scenario = sp.test_scenario("Upgradable", main)
44    scenario.h1("Upgradable")
45
46    c1 = main.Upgradable(value=0, logic=sp.build_lambda(logic1))
47    scenario += c1
48
49    # Use logic version 1
50    c1.calc(sp.pack(sp.record(x=1, y=2)))
51
52    # Update logic to version 2
53    c1.updateLogic(sp.build_lambda(logic2))
54
55    # Use logic version 2
56    c1.calc(sp.pack(sp.record(x=1, y=2, z=3)))
def logic1(data):
27def logic1(data):
28    t = sp.record(x=sp.nat, y=sp.nat)
29    unpacked = sp.unpack(data, t).unwrap_some(error="Cannot UNPACK")
30
31    sp.result(unpacked.x + unpacked.y)
def logic2(data):
35def logic2(data):
36    t = sp.record(x=sp.nat, y=sp.nat, z=sp.nat)
37    unpacked = sp.unpack(data, t).unwrap_some(error="Cannot UNPACK")
38
39    sp.result(unpacked.x + unpacked.y + unpacked.z)