⌘K

Icon SunFilledIcon MoonStars

Icon LinkEncoding

Be sure to read the prerequisites to encoding.

Encoding is done via the ABIEncoder Icon Link:

use fuels::{
    core::{codec::ABIEncoder, traits::Tokenizable},
    macros::Tokenizable,
    types::unresolved_bytes::UnresolvedBytes,
};
 
#[derive(Tokenizable)]
struct MyStruct {
    field: u64,
}
 
let instance = MyStruct { field: 101 };
let encoded: UnresolvedBytes = ABIEncoder::encode(&[instance.into_token()])?;
let load_memory_address: u64 = 0x100;
let _: Vec<u8> = encoded.resolve(load_memory_address);

Note that the return type of encode is UnresolvedBytes. The encoding cannot be finished until we know at which memory address this data is to be loaded. If you don't use heap types (::std::vec::Vec, ::fuels::types::Bytes, ::std::string::String), then you can safely .resolve(0) to get the encoded bytes.

There is also a shortcut-macro that can encode multiple types which implement Tokenizable Icon Link:

use fuels::{core::codec::calldata, macros::Tokenizable};
 
#[derive(Tokenizable)]
struct MyStruct {
    field: u64,
}
let _: Vec<u8> = calldata!(MyStruct { field: 101 }, MyStruct { field: 102 })?;
Icon InfoCircle

Note: The above example will call .resolve(0). Don't use it if you're encoding heap types.