Custom Types in Entrypoints
When using custom types in Starknet contract entrypoints, you need to handle serialization and deserialization of data. This is because:
- Input parameters are sent to entrypoints as arrays of
felt252
- Return values must be converted back to arrays of
felt252
- Custom types need to be converted between these formats automatically
Using the Serde Trait
The Serde
trait provides the necessary serialization and deserialization capabilities for your custom types. For most simple types, you can derive this trait automatically:
#[starknet::interface]
trait ISerdeCustomType<TContractState> {
fn person_input(ref self: TContractState, person: Person);
fn person_output(self: @TContractState) -> Person;
}
// Deriving the `Serde` trait allows us to use
// the `Person` type as an entrypoint parameter and as a return value
#[derive(Drop, Serde)]
struct Person {
age: u8,
name: felt252,
}
#[starknet::contract]
mod SerdeCustomType {
use super::Person;
use super::ISerdeCustomType;
#[storage]
struct Storage {}
#[abi(embed_v0)]
impl SerdeCustomType of ISerdeCustomType<ContractState> {
fn person_input(ref self: ContractState, person: Person) {}
fn person_output(self: @ContractState) -> Person {
Person { age: 10, name: 'Joe' }
}
}
}