Custom types in entrypoints
Using custom types in entrypoints requires our type to implement the Serde
trait. This is because when calling an entrypoint, the input is sent as an array of felt252
to the entrypoint, and we need to be able to deserialize it into our custom type. Similarly, when returning a custom type from an entrypoint, we need to be able to serialize it into an array of felt252
.
Thankfully, we can just derive the Serde
trait for our custom type.
The purpose is to only show the capability of using custom types as inputs and outputs in contract calls. We are not employing getters and setters for managing the contract's state in this example for simplicity.
contract
#[starknet::interface]
pub 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 return value
#[derive(Drop, Serde)]
pub struct Person {
pub age: u8,
pub name: felt252
}
#[starknet::contract]
pub mod SerdeCustomType {
use super::Person;
#[storage]
struct Storage {}
#[abi(embed_v0)]
impl SerdeCustomType of super::ISerdeCustomType<ContractState> {
fn person_input(ref self: ContractState, person: Person) {}
fn person_output(self: @ContractState) -> Person {
Person { age: 10, name: 'Joe' }
}
}
}