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

minor code cleanup #968

Merged
merged 1 commit into from
Sep 1, 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
3 changes: 1 addition & 2 deletions src/core/contract_address/deprecated_contract_address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,6 @@ impl serde_json::ser::Formatter for PythonDefaultFormatter {

#[derive(serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]

pub struct CairoContractDefinition<'a> {
/// Contract ABI, which has no schema definition.
pub abi: serde_json::Value,
Expand Down Expand Up @@ -257,7 +256,7 @@ pub(crate) fn compute_hinted_class_hash(
None => {}
}
// We don't know what this type is supposed to be, but if its missing it is null.
if let Some(serde_json::Value::Null) = vals.get_mut("flow_tracking_data") {
if vals.get("flow_tracking_data") == Some(&serde_json::Value::Null) {
vals.remove("flow_tracking_data");
}

Expand Down
4 changes: 2 additions & 2 deletions src/definitions/block_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl StarknetOsConfig {
/// * `chain_id` - [`Felt252`] of the configured chain.
/// * `fee_token_address` - Address of the token used when paying fees.
/// * `gas_price` - Price of gas.
pub fn new(chain_id: Felt252, fee_token_address: Address, gas_price: u128) -> Self {
pub const fn new(chain_id: Felt252, fee_token_address: Address, gas_price: u128) -> Self {
StarknetOsConfig {
chain_id,
fee_token_address,
Expand Down Expand Up @@ -139,7 +139,7 @@ impl BlockContext {
/// Example: for block number 6351, this includes the blocks 5327, 5328, ..., 6340, 6341.
/// * `enforce_l1_handler_fee` - Whether to enforce the L1 handler fee.
#[allow(clippy::too_many_arguments)]
pub fn new(
pub const fn new(
starknet_os_config: StarknetOsConfig,
contract_storage_commitment_tree_height: u64,
global_state_commitment_tree_height: u64,
Expand Down
4 changes: 2 additions & 2 deletions src/execution/gas_usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ pub fn get_message_segment_lenght(
/// # Returns:
///
/// The on-chain data segment length
pub fn get_onchain_data_segment_length(
pub const fn get_onchain_data_segment_length(
n_modified_contracts: usize,
n_storage_changes: usize,
n_deployments: usize,
Expand Down Expand Up @@ -159,7 +159,7 @@ pub fn get_log_message_to_l1_emissions_cost(l2_to_l1_messages: &[L2toL1MessageIn
/// # Returns:
///
/// The cost of event emissions.
pub fn get_event_emission_cost(topics: usize, l1_handler_payload_size: usize) -> usize {
pub const fn get_event_emission_cost(topics: usize, l1_handler_payload_size: usize) -> usize {
GAS_PER_LOG
+ (topics + N_DEFAULT_TOPICS) * GAS_PER_LOG_TOPIC
+ l1_handler_payload_size * GAS_PER_LOG_DATA_WORD
Expand Down
4 changes: 2 additions & 2 deletions src/execution/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ pub struct TransactionExecutionInfo {
}

impl TransactionExecutionInfo {
pub fn new(
pub const fn new(
validate_info: Option<CallInfo>,
call_info: Option<CallInfo>,
revert_error: Option<String>,
Expand Down Expand Up @@ -553,7 +553,7 @@ impl TransactionExecutionInfo {
}
}

pub fn new_without_fee_info(
pub const fn new_without_fee_info(
validate_info: Option<CallInfo>,
call_info: Option<CallInfo>,
revert_error: Option<String>,
Expand Down
6 changes: 3 additions & 3 deletions src/hash_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ pub fn compute_hash_on_elements(vec: &[Felt252]) -> Result<Felt252, HashError> {
let felt_result = felt_vec
.into_iter()
.reduce(|x, y| pedersen_hash(&x, &y))
.ok_or(HashError::FailedToComputeHash(
"Failed to compute Pedersen hash.".to_string(),
))?;
.ok_or_else(|| {
HashError::FailedToComputeHash("Failed to compute Pedersen hash.".to_string())
})?;

let result = Felt252::from_bytes_be(&felt_result.to_bytes_be());
Ok(result)
Expand Down
2 changes: 1 addition & 1 deletion src/runner/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ impl<H> StarknetRunner<H>
where
H: HintProcessor + HintProcessorPostRun,
{
pub fn new(cairo_runner: CairoRunner, vm: VirtualMachine, hint_processor: H) -> Self {
pub const fn new(cairo_runner: CairoRunner, vm: VirtualMachine, hint_processor: H) -> Self {
StarknetRunner {
cairo_runner,
vm,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ pub struct ContractEntryPoint {
}

impl ContractEntryPoint {
pub fn new(selector: Felt252, offset: usize) -> ContractEntryPoint {
pub const fn new(selector: Felt252, offset: usize) -> ContractEntryPoint {
ContractEntryPoint { selector, offset }
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/state/in_memory_state_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::collections::HashMap;
///
/// This implementation is used for testing and debugging.
/// It uses HashMaps to store the data.
#[derive(Debug, MutGetters, Getters, PartialEq, Clone, Default)]
#[derive(Debug, MutGetters, Getters, PartialEq, Eq, Clone, Default)]
pub struct InMemoryStateReader {
#[getset(get_mut = "pub")]
pub address_to_class_hash: HashMap<Address, ClassHash>,
Expand All @@ -39,7 +39,7 @@ impl InMemoryStateReader {
/// - `class_hash_to_contract_class` - A HashMap from class hashes to their contract classes.
/// - `casm_contract_classes` - A [CasmClassCache].
/// - `class_hash_to_compiled_class_hash` - A HashMap from class hashes to their compiled class hashes.
pub fn new(
pub const fn new(
address_to_class_hash: HashMap<Address, ClassHash>,
address_to_nonce: HashMap<Address, Felt252>,
address_to_storage: HashMap<StorageEntry, Felt252>,
Expand Down
8 changes: 4 additions & 4 deletions src/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub struct BlockInfo {
}

impl BlockInfo {
pub fn empty(sequencer_address: Address) -> Self {
pub const fn empty(sequencer_address: Address) -> Self {
BlockInfo {
block_number: 0, // To do: In cairo-lang, this value is set to -1
block_timestamp: 0,
Expand All @@ -44,7 +44,7 @@ impl BlockInfo {
}
}

pub fn validate_legal_progress(
pub const fn validate_legal_progress(
&self,
next_block_info: &BlockInfo,
) -> Result<(), TransactionError> {
Expand Down Expand Up @@ -102,7 +102,7 @@ impl ExecutionResourcesManager {
}
}

#[derive(Default, Clone, PartialEq, Debug, Getters)]
#[derive(Default, Clone, PartialEq, Eq, Debug, Getters)]
#[getset(get = "pub")]
pub struct StateDiff {
pub(crate) address_to_class_hash: HashMap<Address, ClassHash>,
Expand All @@ -112,7 +112,7 @@ pub struct StateDiff {
}

impl StateDiff {
pub fn new(
pub const fn new(
address_to_class_hash: HashMap<Address, ClassHash>,
address_to_nonce: HashMap<Address, Felt252>,
class_hash_to_compiled_class: HashMap<ClassHash, CompiledClass>,
Expand Down
4 changes: 2 additions & 2 deletions src/state/state_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ impl StateCache {
#[allow(clippy::too_many_arguments)]

/// Create a new StateCache with given initial and written values for testing
pub fn new(
pub const fn new(
class_hash_initial_values: HashMap<Address, ClassHash>,
compiled_class_hash_initial_values: HashMap<ClassHash, CompiledClass>,
nonce_initial_values: HashMap<Address, Felt252>,
Expand Down Expand Up @@ -82,7 +82,7 @@ impl StateCache {

/// Creates a new instance of `StateCache` for testing purposes with the provided initial values and writes.
#[allow(clippy::too_many_arguments)]
pub fn new_for_testing(
pub const fn new_for_testing(
class_hash_initial_values: HashMap<Address, [u8; 32]>,
compiled_class_hash_initial_values: HashMap<ClassHash, CompiledClass>,
nonce_initial_values: HashMap<Address, Felt252>,
Expand Down
4 changes: 2 additions & 2 deletions src/syscalls/business_logic_syscall_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ impl<'a, S: StateReader> BusinessLogicSyscallHandler<'a, S> {
.map_err(|err| SyscallHandlerError::ExecutionError(err.to_string()))?;

let call_info = call_info.ok_or(SyscallHandlerError::ExecutionError(
revert_error.unwrap_or("Execution error".to_string()),
revert_error.unwrap_or_else(|| "Execution error".to_string()),
))?;

let retdata_maybe_reloc = call_info
Expand Down Expand Up @@ -376,7 +376,7 @@ impl<'a, S: StateReader> BusinessLogicSyscallHandler<'a, S> {
.map_err(|_| StateError::ExecutionEntryPoint())?;

let call_info = call_info.ok_or(StateError::CustomError(
revert_error.unwrap_or("Execution error".to_string()),
revert_error.unwrap_or_else(|| "Execution error".to_string()),
))?;

self.internal_calls.push(call_info.clone());
Expand Down
4 changes: 2 additions & 2 deletions src/syscalls/deprecated_business_logic_syscall_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ impl<'a, S: StateReader> DeprecatedBLSyscallHandler<'a, S> {
.map_err(|e| SyscallHandlerError::ExecutionError(e.to_string()))?;

let call_info = call_info.ok_or(SyscallHandlerError::ExecutionError(
revert_error.unwrap_or("Execution error".to_string()),
revert_error.unwrap_or_else(|| "Execution error".to_string()),
))?;

let retdata = call_info.retdata.clone();
Expand All @@ -461,7 +461,7 @@ impl<'a, S: StateReader> DeprecatedBLSyscallHandler<'a, S> {
Ok(retdata)
}

pub(crate) fn get_block_info(&self) -> &BlockInfo {
pub(crate) const fn get_block_info(&self) -> &BlockInfo {
&self.block_context.block_info
}

Expand Down
18 changes: 9 additions & 9 deletions src/syscalls/deprecated_syscall_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub(crate) struct DeprecatedGetBlockNumberResponse {
}

impl DeprecatedCallContractResponse {
pub(crate) fn new(retdata_size: usize, retdata: Relocatable) -> Self {
pub(crate) const fn new(retdata_size: usize, retdata: Relocatable) -> Self {
Self {
retdata_size,
retdata,
Expand All @@ -86,19 +86,19 @@ pub(crate) struct DeprecatedDeployResponse {
}

impl DeprecatedGetTxInfoResponse {
pub fn new(tx_info: Relocatable) -> Self {
pub const fn new(tx_info: Relocatable) -> Self {
DeprecatedGetTxInfoResponse { tx_info }
}
}

impl DeprecatedGetBlockTimestampResponse {
pub(crate) fn new(block_timestamp: u64) -> Self {
pub(crate) const fn new(block_timestamp: u64) -> Self {
DeprecatedGetBlockTimestampResponse { block_timestamp }
}
}

impl DeprecatedGetSequencerAddressResponse {
pub(crate) fn new(sequencer_address: Address) -> Self {
pub(crate) const fn new(sequencer_address: Address) -> Self {
Self { sequencer_address }
}
}
Expand All @@ -111,32 +111,32 @@ impl DeprecatedGetCallerAddressResponse {
}

impl DeprecatedGetTxSignatureResponse {
pub fn new(signature: Relocatable, signature_len: usize) -> Self {
pub const fn new(signature: Relocatable, signature_len: usize) -> Self {
DeprecatedGetTxSignatureResponse {
signature,
signature_len,
}
}
}
impl DeprecatedGetContractAddressResponse {
pub fn new(contract_address: Address) -> Self {
pub const fn new(contract_address: Address) -> Self {
DeprecatedGetContractAddressResponse { contract_address }
}
}

impl DeprecatedStorageReadResponse {
pub fn new(value: Felt252) -> Self {
pub const fn new(value: Felt252) -> Self {
DeprecatedStorageReadResponse { value }
}
}

impl DeprecatedGetBlockNumberResponse {
pub(crate) fn new(block_number: u64) -> Self {
pub(crate) const fn new(block_number: u64) -> Self {
Self { block_number }
}
}
impl DeprecatedDeployResponse {
pub(crate) fn new(
pub(crate) const fn new(
contract_address: Felt252,
constructor_retdata_size: Felt252,
constructor_retdata: Relocatable,
Expand Down
8 changes: 4 additions & 4 deletions src/syscalls/syscall_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ impl SyscallResponse {
// ----------------------

/// Represents the response of get_block_timestamp syscall.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GetBlockTimestampResponse {
/// The block timestamp.
pub timestamp: Felt252,
Expand Down Expand Up @@ -104,7 +104,7 @@ pub struct FailureReason {
}

/// Represents the response of call_contract syscall
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallContractResponse {
/// The retdata segment start.
pub retdata_start: Relocatable,
Expand All @@ -113,14 +113,14 @@ pub struct CallContractResponse {
}

/// Represents the response of get_block_hash syscall
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GetBlockHashResponse {
/// The returned hash.
pub block_hash: Felt252,
}

/// Represents the response of the `keccak` syscall
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KeccakResponse {
/// The returned hash.
pub hash_low: Felt252,
Expand Down
4 changes: 2 additions & 2 deletions src/transaction/deploy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ impl Deploy {
}

/// Returns the class hash of the deployed contract
pub fn class_hash(&self) -> ClassHash {
pub const fn class_hash(&self) -> ClassHash {
self.contract_hash
}

Expand Down Expand Up @@ -351,7 +351,7 @@ mod tests {
class_hash_bytes
);

let storage_key = calculate_sn_keccak("owner".as_bytes());
let storage_key = calculate_sn_keccak(b"owner");

assert_eq!(
state
Expand Down
4 changes: 1 addition & 3 deletions src/transaction/invoke_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1174,9 +1174,7 @@ mod tests {
fn test_reverted_transaction_wrong_entry_point() {
let internal_invoke_function = InvokeFunction {
contract_address: Address(0.into()),
entry_point_selector: Felt252::from_bytes_be(&calculate_sn_keccak(
"factorial_".as_bytes(),
)),
entry_point_selector: Felt252::from_bytes_be(&calculate_sn_keccak(b"factorial_")),
entry_point_type: EntryPointType::External,
calldata: vec![],
tx_type: TransactionType::InvokeFunction,
Expand Down
2 changes: 0 additions & 2 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,7 +585,6 @@ mod test {
}

#[test]

fn subtract_mappings_test() {
let mut a = HashMap::new();
let mut b = HashMap::new();
Expand Down Expand Up @@ -634,7 +633,6 @@ mod test {
}

#[test]

fn to_cache_state_storage_mapping_test() {
let mut storage: HashMap<(Address, ClassHash), Felt252> = HashMap::new();
let address1: Address = Address(1.into());
Expand Down