starknet-rs
starknet-rs copied to clipboard
[Feature]: decode a slice of `FieldElement` into a list of `Token`
This PR addresses issue #286
We implemented a decode
fucntion
fn decode(types: &[ParamType], data: &[FieldElement]) -> Result<Vec<Token>, DecoderError>
Where:
pub enum ParamType {
FieldElement,
Array,
Tuple(usize),
}
#[derive(PartialEq, Eq, Debug)]
pub enum Token {
FieldElement(FieldElement),
Array(Vec<FieldElement>),
Tuple(Vec<FieldElement>),
}
I like where you're going with this PR. My suggestion is to add a new trait for encoding and decoding Starknet types.
pub trait AbiEncode {
/// Encode type to a token.
// TODO: should it consume the type or should take a reference?
fn encode(self) -> Token;
}
pub trait AbiDecode {
type Error;
fn decode(tokens: impl AsRef<[Token]>) -> Result<Self, Self::Error>;
}
Then it's possible to implement the encoder and decoder for all rust builtin types like numbers (u64
, u32
), and structs (vectors, tuples, and arrays).
@xJonathanLEI can you please take a look here and tell us what do you think ?
I added a macro that auto generates a Decode
implementation for structs from a slice of Token
, check https://github.com/xJonathanLEI/starknet-rs/blob/59f42eaddab7651e94474cd70f8872b27eadebea/examples/decoder_example.rs
I like where you're going with this PR. My suggestion is to add a new trait for encoding and decoding Starknet types.
pub trait AbiEncode { /// Encode type to a token. // TODO: should it consume the type or should take a reference? fn encode(self) -> Token; } pub trait AbiDecode { type Error; fn decode(tokens: impl AsRef<[Token]>) -> Result<Self, Self::Error>; }
Then it's possible to implement the encoder and decoder for all rust builtin types like numbers (
u64
,u32
), and structs (vectors, tuples, and arrays).
I wen with TryFrom
for converting Token
to rust types because that's what is used for FieldElement
Now, after I introduced Decode
to convert a Vec<Token>
to a struct, naming the trait that convert Token
to a "scalar" type AbiDecode
will be confusing, maybe using TryFrom
is the best option after all, what do you guys think ?
@haroune-mohammedi @fracek it could be awesome to have your feedbacks on #475 related to this! As this one may be closed due to the overlap. :+1: