Skip to content
On this page

Debugging

sp.trace(x) → 

Prints x to standard error. Does not have any effect in the compiled contract.

For debugging it is often useful to print out intermediate values. In SmartPy this can be done with the sp.trace statement.

As an example, consider the fibonacci_view.py (fibonacci_view) template. In order to gain a better understanding of which recursive calls are made in which order, we can insert an sp.trace statement at the beginning of each call to the main view, resulting in the following code:

smartpy
import smartpy as sp

@sp.module
def main():
    class FibonacciView(sp.Contract):
        @sp.onchain_view()
        def fibonacci(self, n):
            sp.trace(n)
            sp.cast(n, int)
            if n < 2:
                return n
            else:
                n1 = sp.view("fibonacci", sp.self_address(), n - 1, int).unwrap_some()
                n2 = sp.view("fibonacci", sp.self_address(), n - 2, int).unwrap_some()
                return n1 + n2

@sp.add_test()
def test():
    s = sp.test_scenario("FibonacciView", main)
    c = main.FibonacciView()
    s += c
    s.verify(c.fibonacci(5) == 5)

Now when we run this, a line is printed on standard error for each call to the fibonacci view:

shell
$ python fibonacci_view.py
5
4
3
2
1
0
1
2
1
0
3
2
1
0
1