Skip to content
This repository was archived by the owner on Jul 22, 2024. It is now read-only.

fix: generate program_json directly from program string #764

Merged
merged 4 commits into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ target/

# END AUTOGENERATED

cairo1/**/
cairo2/**/
cairo1
cairo2
starknet-venv/
**/*.json
cairo_programs/cairo_1_contracts/*.sierra
Expand Down
8 changes: 5 additions & 3 deletions crates/starknet-contract-class/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use serde::Deserialize;
use starknet_api::deprecated_contract_class::{ContractClassAbiEntry, EntryPoint};
use std::{collections::HashMap, fs::File, io::BufReader, path::PathBuf};

// TODO: move this crate's functionality into SiR and remove the crate

pub type AbiType = Vec<ContractClassAbiEntry>;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -131,15 +133,15 @@ 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 {
for (entry_type, entry_points) in entry_points {
let en_type = entry_type.into();

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

Expand Down
182 changes: 146 additions & 36 deletions src/services/api/contract_classes/deprecated_contract_class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ use starknet_api::deprecated_contract_class::EntryPoint;
pub use starknet_contract_class::to_cairo_runner_program;
use starknet_contract_class::AbiType;
use starknet_contract_class::{ContractEntryPoint, EntryPointType};
use std::{collections::HashMap, fs::File, io::BufReader, path::PathBuf};
use std::collections::HashMap;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};

// -------------------------------
// Contract Class
Expand All @@ -33,12 +35,10 @@ impl ContractClass {
abi: Option<AbiType>,
) -> Result<Self, ContractClassError> {
for entry_points in entry_points_by_type.values() {
let mut index = 1;
while let Some(entry_point) = entry_points.get(index) {
if entry_point.selector() > entry_points[index - 1].selector() {
for i in 1..entry_points.len() {
if entry_points[i - 1].selector() > entry_points[i].selector() {
return Err(ContractClassError::EntrypointError(entry_points.clone()));
}
index += 1;
}
}

Expand All @@ -49,21 +49,29 @@ impl ContractClass {
abi,
})
}

pub fn new_from_path<F>(path: F) -> Result<Self, ProgramError>
where
F: AsRef<Path>,
{
Self::try_from(std::fs::read_to_string(path)?.as_str())
}
}

// -------------------------------
// From traits
// -------------------------------
impl TryFrom<starknet_api::deprecated_contract_class::ContractClass> for ContractClass {

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

fn try_from(
contract_class: starknet_api::deprecated_contract_class::ContractClass,
) -> Result<Self, Self::Error> {
fn try_from(s: &str) -> Result<Self, ProgramError> {
let contract_class: starknet_api::deprecated_contract_class::ContractClass =
serde_json::from_str(s)?;
let program = to_cairo_runner_program(&contract_class.program)?;
let entry_points_by_type =
convert_entry_points(contract_class.clone().entry_points_by_type);
let program_json = serde_json::to_value(&contract_class)?;
let program_json = serde_json::from_str(s)?;
Ok(ContractClass {
program_json,
program,
Expand All @@ -73,58 +81,52 @@ impl TryFrom<starknet_api::deprecated_contract_class::ContractClass> for Contrac
}
}

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

impl TryFrom<&str> for ContractClass {
impl TryFrom<&Path> for ContractClass {
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)?;
ContractClass::try_from(raw_contract_class)
fn try_from(path: &Path) -> Result<Self, Self::Error> {
Self::new_from_path(path)
}
}

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

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

impl TryFrom<&PathBuf> for ContractClass {
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)?;
ContractClass::try_from(raw_contract_class)
Self::new_from_path(path)
}
}

impl<T: std::io::Read> TryFrom<BufReader<T>> for ContractClass {
type Error = ProgramError;

fn try_from(reader: BufReader<T>) -> Result<Self, Self::Error> {
let raw_contract_class: starknet_api::deprecated_contract_class::ContractClass =
serde_json::from_reader(reader)?;
ContractClass::try_from(raw_contract_class)
fn try_from(mut reader: BufReader<T>) -> Result<Self, Self::Error> {
let mut s = String::new();
reader.read_to_string(&mut s)?;
Self::try_from(s.as_str())
}
}

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

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 {
for (entry_type, entry_points) in entry_points {
let en_type = entry_type.into();

let contracts_entry_points = vec
let contracts_entry_points = entry_points
.into_iter()
.map(|e| {
let selector = Felt252::from_bytes_be(e.selector.0.bytes());
Expand All @@ -141,20 +143,20 @@ fn convert_entry_points(

#[cfg(test)]
mod tests {
use crate::core::contract_address::compute_deprecated_class_hash;

use super::*;
use cairo_vm::{
felt::{felt_str, PRIME_STR},
serde::deserialize_program::BuiltinName,
};
use std::io::Read;
use starknet_contract_class::ParsedContractClass;
use std::{fs, str::FromStr};

#[test]
fn deserialize_contract_class() {
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))
let serialized = fs::read_to_string("starknet_programs/AccountPreset.json")
.expect("should be able to read file");

let res = ContractClass::try_from(serialized.as_str());
Expand Down Expand Up @@ -201,4 +203,112 @@ mod tests {
)]
);
}

#[test]
fn test_contract_class_new_equals_raw_instantiation() {
let contract_str = fs::read_to_string("starknet_programs/raw_contract_classes/0x4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad.json").unwrap();

let parsed_contract_class = ParsedContractClass::try_from(contract_str.as_str()).unwrap();
let contract_class = ContractClass {
program_json: serde_json::Value::from_str(&contract_str).unwrap(),
program: parsed_contract_class.program.clone(),
entry_points_by_type: parsed_contract_class.entry_points_by_type.clone(),
abi: parsed_contract_class.abi.clone(),
};

let contract_class_new = ContractClass::new(
serde_json::Value::from_str(&contract_str).unwrap(),
parsed_contract_class.program,
parsed_contract_class.entry_points_by_type,
parsed_contract_class.abi,
)
.unwrap();

assert_eq!(contract_class, contract_class_new);
}

#[test]
fn test_compute_class_hash_0x4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad_try_from(
) {
let contract_str = fs::read_to_string("starknet_programs/raw_contract_classes/0x4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad.json").unwrap();

let contract_class = ContractClass::try_from(contract_str.as_str()).unwrap();

assert_eq!(
compute_deprecated_class_hash(&contract_class).unwrap(),
felt_str!(
"4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad",
16
)
);
}

#[test]
fn test_new_equals_try_from() {
let contract_str = fs::read_to_string("starknet_programs/raw_contract_classes/0x4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad.json").unwrap();

let parsed_contract_class = ParsedContractClass::try_from(contract_str.as_str()).unwrap();

let contract_class_new = ContractClass::new(
serde_json::Value::from_str(&contract_str).unwrap(),
parsed_contract_class.program,
parsed_contract_class.entry_points_by_type,
parsed_contract_class.abi,
)
.unwrap();

let contract_class = ContractClass::try_from(contract_str.as_str()).unwrap();

assert_eq!(contract_class.abi, contract_class_new.abi);
assert_eq!(contract_class.program, contract_class_new.program);
assert_eq!(contract_class.program_json, contract_class_new.program_json);
assert_eq!(
contract_class.entry_points_by_type,
contract_class_new.entry_points_by_type
);
}

#[test]
fn test_compute_class_hash_0x4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad_new(
) {
let contract_str = fs::read_to_string("starknet_programs/raw_contract_classes/0x4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad.json").unwrap();

let parsed_contract_class = ParsedContractClass::try_from(contract_str.as_str()).unwrap();
let contract_class = ContractClass::new(
serde_json::Value::from_str(&contract_str).unwrap(),
parsed_contract_class.program,
parsed_contract_class.entry_points_by_type,
parsed_contract_class.abi,
)
.unwrap();

assert_eq!(
compute_deprecated_class_hash(&contract_class).unwrap(),
felt_str!(
"4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad",
16
)
);
}

#[test]
fn test_compute_class_hash_0x4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad() {
let contract_str = fs::read_to_string("starknet_programs/raw_contract_classes/0x4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad.json").unwrap();

let parsed_contract_class = ParsedContractClass::try_from(contract_str.as_str()).unwrap();
let contract_class = ContractClass {
program_json: serde_json::Value::from_str(&contract_str).unwrap(),
program: parsed_contract_class.program,
entry_points_by_type: parsed_contract_class.entry_points_by_type,
abi: parsed_contract_class.abi,
};

assert_eq!(
compute_deprecated_class_hash(&contract_class).unwrap(),
felt_str!(
"4479c3b883b34f1eafa5065418225d78a11ee7957c371e1b285e4b77afc6dad",
16
)
);
}
}

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions tests/complex_contracts/amm_contracts/amm_proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,8 +427,8 @@ fn amm_proxy_get_account_token_balance() {
retdata: [200.into()].to_vec(),
storage_read_values: [200.into()].to_vec(),
execution_resources: ExecutionResources {
n_steps: 94,
n_memory_holes: 10,
n_steps: 92,
n_memory_holes: 11,
builtin_instance_counter: HashMap::from([
("pedersen_builtin".to_string(), 2),
("range_check_builtin".to_string(), 3),
Expand All @@ -448,8 +448,8 @@ fn amm_proxy_get_account_token_balance() {
calldata: calldata.clone(),
retdata: [200.into()].to_vec(),
execution_resources: ExecutionResources {
n_steps: 153,
n_memory_holes: 10,
n_steps: 151,
n_memory_holes: 11,
builtin_instance_counter: HashMap::from([
("pedersen_builtin".to_string(), 2),
("range_check_builtin".to_string(), 3),
Expand Down Expand Up @@ -561,8 +561,8 @@ fn amm_proxy_swap() {
storage_read_values: [100.into(), 1000.into(), 1000.into(), 100.into(), 200.into()]
.to_vec(),
execution_resources: ExecutionResources {
n_steps: 824,
n_memory_holes: 93,
n_steps: 826,
n_memory_holes: 92,
builtin_instance_counter: HashMap::from([
("pedersen_builtin".to_string(), 14),
("range_check_builtin".to_string(), 41),
Expand All @@ -582,8 +582,8 @@ fn amm_proxy_swap() {
calldata: calldata.clone(),
retdata: expected_result,
execution_resources: ExecutionResources {
n_steps: 883,
n_memory_holes: 93,
n_steps: 885,
n_memory_holes: 92,
builtin_instance_counter: HashMap::from([
("pedersen_builtin".to_string(), 14),
("range_check_builtin".to_string(), 41),
Expand Down