templates.fibonacci_view

 1import smartpy as sp
 2
 3
 4@sp.module
 5def main():
 6    class FibonacciView(sp.Contract):
 7        """Contract with a recursing view to compute the sum of fibonacci numbers."""
 8
 9        @sp.onchain_view()
10        def fibonacci(self, n):
11            """Return the sum of fibonacci numbers until n.
12
13            Args:
14                n (sp.int): number of fibonacci numbers to sum.
15            Return:
16                (sp.int): the sum of fibonacci numbers
17            """
18            sp.cast(n, int)
19            if n < 2:
20                return n
21            else:
22                n1 = sp.view("fibonacci", sp.self_address(), n - 1, int).unwrap_some()
23                n2 = sp.view("fibonacci", sp.self_address(), n - 2, int).unwrap_some()
24                return n1 + n2
25
26
27if "main" in __name__:
28
29    @sp.add_test()
30    def basic_scenario():
31        sc = sp.test_scenario("FibonacciView basic scenario", main)
32        sc.h1("Basic scenario.")
33        sc.h2("Origination.")
34        c1 = main.FibonacciView()
35        sc += c1
36        sc.verify(c1.fibonacci(8) == 21)