1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#![deny(warnings)]

use cairo_vm::felt::{Felt252, PRIME_STR};
use cairo_vm::{
    serde::deserialize_program::{
        deserialize_array_of_bigint_hex, Attribute, BuiltinName, HintParams, Identifier,
        ReferenceManager,
    },
    types::{
        errors::program_errors::ProgramError, program::Program, relocatable::MaybeRelocatable,
    },
};
use getset::{CopyGetters, Getters};
use serde::Deserialize;
use starknet_api::deprecated_contract_class::{ContractClassAbiEntry, EntryPoint};
use std::{collections::HashMap, fs::File, io::BufReader, path::PathBuf};

pub type AbiType = Vec<ContractClassAbiEntry>;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntryPointType {
    External,
    L1Handler,
    Constructor,
}

#[derive(Clone, CopyGetters, Debug, Default, Eq, Getters, Hash, PartialEq)]
pub struct ContractEntryPoint {
    #[getset(get = "pub")]
    pub selector: Felt252,
    #[getset(get_copy = "pub")]
    pub offset: usize,
}

impl ContractEntryPoint {
    pub fn new(selector: Felt252, offset: usize) -> ContractEntryPoint {
        ContractEntryPoint { selector, offset }
    }
}

// -------------------------------
//         Contract Class
// -------------------------------

#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
#[serde(try_from = "starknet_api::deprecated_contract_class::ContractClass")]
pub struct ParsedContractClass {
    pub program: Program,
    pub entry_points_by_type: HashMap<EntryPointType, Vec<ContractEntryPoint>>,
    pub abi: Option<AbiType>,
}

// -------------------------------
//         From traits
// -------------------------------

impl From<&ContractEntryPoint> for Vec<MaybeRelocatable> {
    fn from(entry_point: &ContractEntryPoint) -> Self {
        vec![
            MaybeRelocatable::from(entry_point.selector.clone()),
            MaybeRelocatable::from(entry_point.offset),
        ]
    }
}

impl From<starknet_api::deprecated_contract_class::EntryPointType> for EntryPointType {
    fn from(entry_type: starknet_api::deprecated_contract_class::EntryPointType) -> Self {
        type ApiEPT = starknet_api::deprecated_contract_class::EntryPointType;
        type StarknetEPT = EntryPointType;

        match entry_type {
            ApiEPT::Constructor => StarknetEPT::Constructor,
            ApiEPT::External => StarknetEPT::External,
            ApiEPT::L1Handler => StarknetEPT::L1Handler,
        }
    }
}

impl TryFrom<starknet_api::deprecated_contract_class::ContractClass> for ParsedContractClass {
    type Error = ProgramError;

    fn try_from(
        contract_class: starknet_api::deprecated_contract_class::ContractClass,
    ) -> Result<Self, Self::Error> {
        let program = to_cairo_runner_program(&contract_class.program)?;
        let entry_points_by_type = convert_entry_points(contract_class.entry_points_by_type);
        Ok(Self {
            program,
            entry_points_by_type,
            abi: contract_class.abi,
        })
    }
}

// -------------------
//  Helper Functions
// -------------------

impl TryFrom<&str> for ParsedContractClass {
    type Error = ProgramError;

    fn try_from(s: &str) -> Result<Self, ProgramError> {
        let raw_contract_class: starknet_api::deprecated_contract_class::ContractClass =
            serde_json::from_str(s)?;

        Self::try_from(raw_contract_class)
    }
}

impl TryFrom<PathBuf> for ParsedContractClass {
    type Error = ProgramError;

    fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
        Self::try_from(&path)
    }
}

impl TryFrom<&PathBuf> for ParsedContractClass {
    type Error = ProgramError;

    fn try_from(path: &PathBuf) -> Result<Self, Self::Error> {
        let file = File::open(path)?;
        let reader = BufReader::new(file);
        let raw_contract_class: starknet_api::deprecated_contract_class::ContractClass =
            serde_json::from_reader(reader)?;
        Self::try_from(raw_contract_class)
    }
}

fn convert_entry_points(
    entry_points: HashMap<starknet_api::deprecated_contract_class::EntryPointType, Vec<EntryPoint>>,
) -> HashMap<EntryPointType, Vec<ContractEntryPoint>> {
    let mut converted_entries: HashMap<EntryPointType, Vec<ContractEntryPoint>> = HashMap::new();
    for (entry_type, vec) in entry_points {
        let en_type = entry_type.into();

        let contracts_entry_points = vec
            .into_iter()
            .map(|e| {
                let selector = Felt252::from_bytes_be(e.selector.0.bytes());
                let offset = e.offset.0;
                ContractEntryPoint { selector, offset }
            })
            .collect::<Vec<ContractEntryPoint>>();

        converted_entries.insert(en_type, contracts_entry_points);
    }

    converted_entries
}

pub fn to_cairo_runner_program(
    program: &starknet_api::deprecated_contract_class::Program,
) -> Result<Program, ProgramError> {
    let program = program.clone();
    let identifiers = serde_json::from_value::<HashMap<String, Identifier>>(program.identifiers)?;

    if program.prime != *PRIME_STR {
        return Err(ProgramError::PrimeDiffers(program.prime.to_string()));
    };

    let error_message_attributes = serde_json::from_value::<Vec<Attribute>>(program.attributes)
        .unwrap_or(Vec::new())
        .into_iter()
        .filter(|attr| attr.name == "error_message")
        .collect();

    let program = Program::new(
        serde_json::from_value::<Vec<BuiltinName>>(program.builtins)?,
        deserialize_array_of_bigint_hex(program.data)?,
        None,
        serde_json::from_value::<HashMap<usize, Vec<HintParams>>>(program.hints)?,
        serde_json::from_value::<ReferenceManager>(program.reference_manager)?,
        identifiers,
        error_message_attributes,
        None,
    )?;

    Ok(program)
}

#[cfg(test)]
mod tests {
    use super::*;
    use cairo_vm::felt::felt_str;
    use starknet_api::deprecated_contract_class::{
        ContractClassAbiEntry, FunctionAbiEntry, FunctionAbiEntryType, FunctionAbiEntryWithType,
        TypedParameter,
    };
    use std::io::Read;

    #[test]
    fn try_from_string_abi() {
        let mut serialized = String::new();

        // This specific contract compiles with --no_debug_info
        File::open(PathBuf::from("../../starknet_programs/fibonacci.json"))
            .and_then(|mut f| f.read_to_string(&mut serialized))
            .expect("should be able to read file");

        let res = ParsedContractClass::try_from(serialized.as_str());

        let contract_class = res.unwrap();

        let expected_abi = Some(vec![ContractClassAbiEntry::Function(
            FunctionAbiEntryWithType {
                r#type: FunctionAbiEntryType::Function,
                entry: FunctionAbiEntry {
                    name: "fib".to_string(),
                    inputs: vec![
                        TypedParameter {
                            name: "first_element".to_string(),
                            r#type: "felt".to_string(),
                        },
                        TypedParameter {
                            name: "second_element".to_string(),
                            r#type: "felt".to_string(),
                        },
                        TypedParameter {
                            name: "n".to_string(),
                            r#type: "felt".to_string(),
                        },
                    ],
                    outputs: vec![TypedParameter {
                        name: "res".to_string(),
                        r#type: "felt".to_string(),
                    }],
                },
            },
        )]);
        assert_eq!(contract_class.abi, expected_abi);
    }

    #[test]
    fn try_from_string() {
        let mut serialized = String::new();

        // This specific contract compiles with --no_debug_info
        File::open(PathBuf::from("../../starknet_programs/AccountPreset.json"))
            .and_then(|mut f| f.read_to_string(&mut serialized))
            .expect("should be able to read file");

        let res = ParsedContractClass::try_from(serialized.as_str());

        let contract_class = res.unwrap();

        let program_builtins: Vec<BuiltinName> =
            contract_class.program.iter_builtins().cloned().collect();
        assert_eq!(
            program_builtins,
            vec![
                BuiltinName::pedersen,
                BuiltinName::range_check,
                BuiltinName::ecdsa,
                BuiltinName::bitwise
            ]
        );
        assert_eq!(
            contract_class
                .entry_points_by_type
                .get(&EntryPointType::L1Handler)
                .unwrap(),
            &vec![]
        );
        assert_eq!(
            contract_class
                .entry_points_by_type
                .get(&EntryPointType::Constructor)
                .unwrap(),
            &vec![ContractEntryPoint {
                selector: felt_str!(
                    "1159040026212278395030414237414753050475174923702621880048416706425641521556"
                ),
                offset: 366
            }]
        );
    }

    #[test]
    fn try_from_string_without_program_attributes() {
        let mut serialized = String::new();

        // This specific contract was extracted from: https://testnet.starkscan.co/class/0x068dd0dd8a54ebdaa10563fbe193e6be1e0f7c423c0c3ce1e91c0b682a86b5f9
        File::open(PathBuf::from(
            "../../starknet_programs/raw_contract_classes/program_without_attributes.json",
        ))
        .and_then(|mut f| f.read_to_string(&mut serialized))
        .expect("should be able to read file");

        let res = ParsedContractClass::try_from(serialized.as_str());

        res.unwrap();
    }

    #[test]
    fn try_from_string_without_program_attributes_2() {
        let mut serialized = String::new();

        // This specific contract was extracted from: https://testnet.starkscan.co/class/0x071b7f73b5e2b4f81f7cf01d4d1569ccba2921b3fa3170cf11cff3720dfe918e
        File::open(PathBuf::from(
            "../../starknet_programs/raw_contract_classes/program_without_attributes_2.json",
        ))
        .and_then(|mut f| f.read_to_string(&mut serialized))
        .expect("should be able to read file");

        let res = ParsedContractClass::try_from(serialized.as_str());

        res.unwrap();
    }

    #[test]
    fn deserialize_equals_try_from() {
        let mut serialized = String::new();

        // This specific contract compiles with --no_debug_info
        File::open(PathBuf::from("../../starknet_programs/AccountPreset.json"))
            .and_then(|mut f| f.read_to_string(&mut serialized))
            .expect("should be able to read file");

        let result_try_from = ParsedContractClass::try_from(serialized.as_str()).unwrap();
        let result_deserialize = serde_json::from_str(&serialized).unwrap();

        assert_eq!(result_try_from, result_deserialize);
    }
}