1

I find I run into some unexpected behavior when using sp.if. e.g.


        a = False
        sp.if 1 > 2:
            a = True

seems to result in a == True.

The example below is doing so in the Store Value contract template.

# Store Value - Example for illustrative purposes only.

import smartpy as sp

class StoreValue(sp.Contract):
    def __init__(self, value):
        self.init(storedValue = value)

    @sp.entry_point
    def replace(self, params):
        
        a = False
        sp.if 1 > 2:
            a = True
        
        sp.if a:
            self.data.storedValue = params.value

    @sp.entry_point
    def double(self, params):
        self.data.storedValue *= 2

    @sp.entry_point
    def divide(self, params):
        sp.verify(params.divisor > 5)
        self.data.storedValue /= params.divisor

if "templates" not in __name__:
    @sp.add_test(name = "StoreValue")
    def test():
        c1 = StoreValue(12)
        scenario = sp.test_scenario()
        scenario.h1("Store Value")
        scenario += c1
        scenario += c1.replace(value = 15)
        scenario.p("Some computation").show(c1.data.storedValue * 12)
        scenario += c1.replace(value = 25)
        scenario += c1.double()
        scenario += c1.divide(divisor = 2).run(valid = False)
        scenario.verify(c1.data.storedValue == 50)
        scenario += c1.divide(divisor = 6)
        scenario.verify(c1.data.storedValue == 8)
    ```
2

The short answer is that you need to use local variables.

a = sp.local('a', False)
sp.if ...:
    a.value = True
...

Otherwise, a is computed too soon by Python and not by SmartPy / Michelson.

| improve this answer | |
  • Hmm, I tried that in the above script, replacing "a = False" with "a = sp.local('a', False)", but it still didn't work. As in, the script passes when it should fail, because the 'replace' entrypoint should fail to update the value. – Darius Oct 12 at 17:57
  • Ah okay, I see that i also have to replace 'a' with 'a.value' . Now it works, thanks! – Darius Oct 12 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.