templates.calculator

 1# Calculator - Example for illustrative purposes only.
 2
 3import smartpy as sp
 4
 5
 6@sp.module
 7def main():
 8    class Calculator(sp.Contract):
 9        def __init__(self):
10            self.data.result = 0
11
12        @sp.entrypoint
13        def multiply(self, x, y):
14            self.data.result = x * y
15
16        @sp.entrypoint
17        def add(self, x, y):
18            self.data.result = x + y
19
20        @sp.entrypoint
21        def square(self, x):
22            self.data.result = x * x
23
24        @sp.entrypoint
25        def squareRoot(self, x):
26            assert x >= 0
27            y = x
28            while y * y > x:
29                y = (x / y + y) / 2
30            assert y * y <= x and x < (y + 1) * (y + 1)
31            self.data.result = y
32
33        @sp.entrypoint
34        def factorial(self, x):
35            self.data.result = 1
36            for y in range(1, x + 1):
37                self.data.result *= y
38
39        @sp.entrypoint
40        def log2(self, x):
41            self.data.result = 0
42            y = x
43            while y > 1:
44                self.data.result += 1
45                y /= 2
46
47
48if "main" in __name__:
49
50    @sp.add_test()
51    def test():
52        scenario = sp.test_scenario("Calculator", main)
53        c1 = main.Calculator()
54        scenario.h1("Calculator")
55        scenario += c1
56        c1.multiply(x=2, y=5)
57        c1.add(x=2, y=5)
58        c1.add(x=2, y=5)
59        c1.square(12)
60        c1.squareRoot(0)
61        c1.squareRoot(1234)
62        c1.factorial(100)
63        c1.log2(c1.data.result)
64        scenario.verify(c1.data.result == 524)