1

How do we translate the below enum in smartPy.

enum ServiceType {
        REQUEST_COIN_TRANSFER,
        REQUEST_COIN_REGISTER,
        REPONSE_HANDLE_SERVICE,
        BLACKLIST_MESSAGE,
        CHANGE_TOKEN_LIMIT,
        UNKNOWN_TYPE
    }

1 Answer 1

2

SmartPy offers the variant system (see doc for new and legacy syntax). It's more powerful than enum as they associate a value with a type so you can create enum with them and even more. Basically an enum is a variant with a sp.unit value.

I suggest you to take time to think how you can use the full power of it (not using a sp.unit value for each field.

New syntax

# Naming enum type
my_enum_type: type = sp.variant(REQUEST_COIN_TRANSFER=sp.unit, REQUEST_COIN_REGISTER=sp.unit...)

# Creating a value
my_value = sp.variant.REQUEST_COIN_TRANSFER(sp.unit)

# If the value is used somewhere the type isn't already enforced:
sp.cast(my_value, my_enum_type)

Legacy syntax

# Naming enum type
my_enum_type = sp.TVariant(REQUEST_COIN_TRANSFER=sp.TUnit, REQUEST_COIN_REGISTER=sp.TUnit...)

# Creating a value
my_value = sp.variant("REQUEST_COIN_TRANSFER", sp.unit)

# If the value is used somewhere the type isn't already enforced:
my_value = sp.set_type_expr(my_value, my_enum_type)

More examples can be found here: https://smartpy.io/ide?template=test_variant.py

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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