From 3f98ae4b8239bb976ab434b438775bcd3db5207a Mon Sep 17 00:00:00 2001 From: glihm Date: Fri, 12 Jan 2024 13:03:27 -0600 Subject: [PATCH] feat: add helper function to parser to load an ABI --- crates/parser/src/abi/parser.rs | 48 +++++++++++++++++++++++++++++++-- crates/parser/src/error.rs | 4 +++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/crates/parser/src/abi/parser.rs b/crates/parser/src/abi/parser.rs index 85be0ba..2167b75 100644 --- a/crates/parser/src/abi/parser.rs +++ b/crates/parser/src/abi/parser.rs @@ -1,12 +1,56 @@ -use starknet::core::types::contract::{AbiEntry, AbiEvent, TypedAbiEvent}; +use starknet::core::types::contract::{AbiEntry, AbiEvent, SierraClass, TypedAbiEvent}; use std::collections::HashMap; use crate::tokens::{Array, CompositeInner, CompositeType, CoreBasic, Function, Token}; -use crate::CainomeResult; +use crate::{CainomeResult, Error}; pub struct AbiParser {} impl AbiParser { + /// Generates the [`Token`]s from the given ABI string. + /// + /// The `abi` can have two formats: + /// 1. Entire [`SierraClass`] json representation. + /// 2. The `abi` key from the [`SierraClass`], which is an array of [`AbiEntry`]. + /// + /// TODO: Move to cainome implementation when available. + /// + /// # Arguments + /// + /// * `abi` - A string representing the ABI. + /// * `type_aliases` - Types to be renamed to avoid name clashing of generated types. + pub fn tokens_from_abi_string( + abi: &str, + type_aliases: &HashMap, + ) -> CainomeResult>> { + let abi_entries = Self::parse_abi_string(abi)?; + let abi_tokens = AbiParser::collect_tokens(&abi_entries).expect("failed tokens parsing"); + let abi_tokens = AbiParser::organize_tokens(abi_tokens, type_aliases); + + Ok(abi_tokens) + } + + /// Parses an ABI string to output a `Vec`. + /// + /// The `abi` can have two formats: + /// 1. Entire [`SierraClass`] json representation. + /// 2. The `abi` key from the [`SierraClass`], which is an array of AbiEntry. + /// + /// TODO: Move to cainome implementation when available. + /// + /// # Arguments + /// + /// * `abi` - A string representing the ABI. + pub fn parse_abi_string(abi: &str) -> CainomeResult> { + let entries = if let Ok(sierra) = serde_json::from_str::(abi) { + sierra.abi + } else { + serde_json::from_str::>(abi).map_err(Error::SerdeJson)? + }; + + Ok(entries) + } + /// Organizes the tokens by cairo types. pub fn organize_tokens( tokens: HashMap, diff --git a/crates/parser/src/error.rs b/crates/parser/src/error.rs index fc54002..228d303 100644 --- a/crates/parser/src/error.rs +++ b/crates/parser/src/error.rs @@ -11,6 +11,10 @@ pub enum Error { ConversionFailed(String), #[error("Parser error: {0}")] ParsingFailed(String), + #[error(transparent)] + IO(#[from] std::io::Error), + #[error(transparent)] + SerdeJson(#[from] serde_json::Error), } pub type CainomeResult = Result;