Codec

Encoding and decoding are done as per the fuel spec. To this end, fuels makes use of the ABIEncoder and the ABIDecoder.

Prerequisites for decoding/encoding

To encode a type, you must first convert it into a Token. This is commonly done by implementing the Tokenizable trait.

To decode, you also need to provide a ParamType describing the schema of the type in question. This is commonly done by implementing the Parameterize trait.

All types generated by the abigen! macro implement both the Tokenizable and Parameterize traits.

fuels also contains implementations for:

Deriving the traits

Both Tokenizable and Parameterize can be derived for structs and enums if all inner types implement the derived traits:

        use fuels::macros::{Parameterize, Tokenizable};

        #[derive(Parameterize, Tokenizable)]
        struct MyStruct {
            field_a: u8,
        }

        #[derive(Parameterize, Tokenizable)]
        enum SomeEnum {
            A(MyStruct),
            B(Vec<u64>),
        }

Note: Deriving Tokenizable on enums requires that all variants also implement Parameterize.

Tweaking the derivation

Changing the location of imports

The derived code expects that the fuels package is accessible through ::fuels. If this is not the case then the derivation macro needs to be given the locations of fuels::types and fuels::core.

            #[derive(Parameterize, Tokenizable)]
            #[FuelsCorePath = "fuels_core_elsewhere"]
            #[FuelsTypesPath = "fuels_types_elsewhere"]
            pub struct SomeStruct {
                field_a: u64,
            }

Generating no-std code

If you want no-std generated code:

            use fuels::macros::{Parameterize, Tokenizable};
            #[derive(Parameterize, Tokenizable)]
            #[NoStd]
            pub struct SomeStruct {
                field_a: u64,
            }