Model classes

Using mx-sdk-as, you can define your own data models using classes. However, there are some constraints you need to acknowledge before doing so.

Use the @struct annotation

You have to use the @struct annotation in order to create a VM compatible class; then the SDK will take care of generating the necessary code.

@struct
class MyModel {
    // Fields
}

It is strongly recommended to never create a class without an annotation. Doing so would lead to heap allocations.

Include at Least One Field

You cannot create a class without any fields.

Constructors are forbidden

At the moment, due to some limitations within the AssemblyScript language, it is impossible to create a constructor without performing heap allocations. The SDK is aware of this and will throw a compilation error, indicating that you should remove the constructor.

A workaround is to use static methods to create an instance of your class:

@struct
class MyModel {
    name!: ManagedBuffer

    static new(name: ManagedBuffer): MyModel {
        const myModel = new MyModel()
        myModel.name = name

        return myModel
    }
}

Specify Field Types: mx-sdk-as or @struct/@enum annotated

The generated code includes VM (de)serialization logic, which depends on the class' fields also possessing this capability. Therefore, you should only use field types provided by mx-sdk-as, such as ManagedBuffer, BigUint, ElrondU32, etc., or those annotated with @struct or @enum.

Last updated