templates.test_variant

 1# Options and Variants - Example for illustrative purposes only.
 2
 3import smartpy as sp
 4
 5
 6@sp.module
 7def main():
 8    class TestOptionsAndVariants(sp.Contract):
 9        def __init__(self):
10            self.data.x = sp.variant.A(-1)
11            self.data.y = sp.Some(-42)
12            self.data.z = sp.Left(-10)
13            self.data.r = 0
14            self.data.s = sp.record(x=0, y=1)
15
16        @sp.entrypoint
17        def options(self):
18            if self.data.y.is_some():
19                self.data.r = 44 + self.data.y.unwrap_some(error="Not a some!")
20                self.data.y = None
21            else:
22                self.data.r = 3
23                self.data.y = sp.Some(12)
24
25        @sp.entrypoint
26        def ep1(self):
27            with sp.match(self.data.x):
28                with sp.case.A as arg:
29                    self.data.x = sp.variant.B(-2)
30                    self.data.r = arg
31            self.data.x = sp.variant.C(3)
32
33        @sp.entrypoint
34        def ep3(self):
35            with sp.match(self.data.z):
36                with sp.case.Left as arg:
37                    self.data.r = arg
38
39        @sp.entrypoint
40        def ep4(self):
41            with sp.match(self.data.x):
42                with sp.case.A as a1:
43                    with sp.match(self.data.z):
44                        with sp.case.Right as a2:
45                            self.data.r = a1 + a2
46
47        @sp.entrypoint
48        def ep5(self):
49            if self.data.x.is_variant.Toto():
50                self.data.r = 42
51
52        @sp.entrypoint
53        def ep6(self):
54            self.data.s = self.data.x.unwrap.Toto(error="no toto")
55
56        @sp.entrypoint
57        def ep7(self, params):
58            self.data.x = params
59
60        @sp.entrypoint
61        def ep8(self, params):
62            with sp.match(params.x):
63                with sp.case.A as dummy:
64                    self.data.x = params.x
65                with sp.case.B as arg:
66                    self.data.y = sp.Some(12 + arg + params.y)
67
68        @sp.entrypoint
69        def ep9(self, params):
70            sp.cast(params.other, int)
71            with sp.match(params.z):
72                with sp.case.A as dummy:
73                    self.data.x = params.z
74
75
76@sp.add_test()
77def test():
78    scenario = sp.test_scenario("variant", main)
79    scenario.h1("Variants")
80    c = main.TestOptionsAndVariants()
81    scenario += c
82    c.options()
83    c.ep1()
84    c.ep3()
85    c.ep4()
86    c.ep5()
87    c.ep6(_valid=False)