templates.fibonacci
1# Fibonacci, calling other contracts - Example for illustrative purposes only. 2 3import smartpy as sp 4 5 6@sp.module 7def main(): 8 class Fibonacci(sp.Contract): 9 def __init__(self): 10 self.data.counter = 0 11 self.data.steps = [] 12 13 @sp.entrypoint 14 def run(self, n): 15 self.data.steps.push(n) 16 if n > 1: 17 sp.transfer(n - 2, sp.mutez(0), sp.self_entrypoint("run")) 18 sp.transfer(n - 1, sp.mutez(0), sp.self_entrypoint("run")) 19 else: 20 self.data.counter += 1 21 22 @sp.entrypoint 23 def compute(self, n): 24 self.data.counter = 0 25 self.data.steps = [] 26 sp.transfer(n, sp.mutez(0), sp.self_entrypoint("run")) 27 28 29def fibo(n): 30 if n < 2: 31 return 1 32 return fibo(n - 1) + fibo(n - 2) 33 34 35@sp.add_test() 36def test(): 37 scenario = sp.test_scenario("Fibonacci", main) 38 scenario.h2("Fibonacci") 39 fibonacci = main.Fibonacci() 40 scenario += fibonacci 41 for i in range(0, 10): 42 fibonacci.compute(i) 43 scenario.verify(fibonacci.data.counter == fibo(i)) 44 scenario.show(fibonacci.data.steps.rev()) 45 scenario.verify_equal( 46 fibonacci.data.steps.rev(), 47 [ 48 9, 49 7, 50 5, 51 3, 52 1, 53 2, 54 0, 55 1, 56 4, 57 2, 58 0, 59 1, 60 3, 61 1, 62 2, 63 0, 64 1, 65 6, 66 4, 67 2, 68 0, 69 1, 70 3, 71 1, 72 2, 73 0, 74 1, 75 5, 76 3, 77 1, 78 2, 79 0, 80 1, 81 4, 82 2, 83 0, 84 1, 85 3, 86 1, 87 2, 88 0, 89 1, 90 8, 91 6, 92 4, 93 2, 94 0, 95 1, 96 3, 97 1, 98 2, 99 0, 100 1, 101 5, 102 3, 103 1, 104 2, 105 0, 106 1, 107 4, 108 2, 109 0, 110 1, 111 3, 112 1, 113 2, 114 0, 115 1, 116 7, 117 5, 118 3, 119 1, 120 2, 121 0, 122 1, 123 4, 124 2, 125 0, 126 1, 127 3, 128 1, 129 2, 130 0, 131 1, 132 6, 133 4, 134 2, 135 0, 136 1, 137 3, 138 1, 139 2, 140 0, 141 1, 142 5, 143 3, 144 1, 145 2, 146 0, 147 1, 148 4, 149 2, 150 0, 151 1, 152 3, 153 1, 154 2, 155 0, 156 1, 157 ], 158 )
def
fibo(n):