Skip to content
This repository has been archived by the owner on Aug 21, 2024. It is now read-only.

Commit

Permalink
test: remove the test util create_account_tx_test_state
Browse files Browse the repository at this point in the history
  • Loading branch information
ArniStarkware committed Mar 1, 2024
1 parent 28146e1 commit e2b0591
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 157 deletions.
83 changes: 8 additions & 75 deletions crates/blockifier/src/transaction/test_utils.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
use std::collections::HashMap;

use rstest::fixture;
use starknet_api::core::{ClassHash, ContractAddress, PatriciaKey};
use starknet_api::hash::{StarkFelt, StarkHash};
use starknet_api::state::StorageKey;
use starknet_api::core::{ClassHash, ContractAddress};
use starknet_api::hash::StarkFelt;
use starknet_api::transaction::{
Calldata, ContractAddressSalt, Fee, InvokeTransactionV0, InvokeTransactionV1,
InvokeTransactionV3, Resource, ResourceBounds, ResourceBoundsMapping, TransactionHash,
TransactionSignature, TransactionVersion,
};
use starknet_api::{calldata, class_hash, contract_address, patricia_key, stark_felt};
use starknet_api::{calldata, stark_felt};
use strum::IntoEnumIterator;

use crate::abi::abi_utils::{get_fee_token_var_address, get_storage_var_address};
use crate::context::{BlockContext, ChainInfo, FeeTokenAddresses};
use crate::execution::contract_class::{ClassInfo, ContractClass, ContractClassV0};
use crate::abi::abi_utils::get_fee_token_var_address;
use crate::context::{BlockContext, ChainInfo};
use crate::execution::contract_class::{ClassInfo, ContractClass};
use crate::state::cached_state::CachedState;
use crate::state::state_api::State;
use crate::test_utils::contracts::FeatureContract;
Expand All @@ -24,11 +21,8 @@ use crate::test_utils::dict_state_reader::DictStateReader;
use crate::test_utils::initial_test_state::test_state;
use crate::test_utils::invoke::{invoke_tx, InvokeTxArgs};
use crate::test_utils::{
create_calldata, test_erc20_faulty_account_balance_key, CairoVersion, NonceManager, BALANCE,
ERC20_CONTRACT_PATH, MAX_FEE, MAX_L1_GAS_AMOUNT, MAX_L1_GAS_PRICE, TEST_CLASS_HASH,
TEST_CONTRACT_ADDRESS, TEST_CONTRACT_CAIRO0_PATH, TEST_ERC20_CONTRACT_CLASS_HASH,
TEST_FAULTY_ACCOUNT_CONTRACT_ADDRESS, TEST_FAULTY_ACCOUNT_CONTRACT_CAIRO0_PATH,
TEST_FAULTY_ACCOUNT_CONTRACT_CLASS_HASH,
create_calldata, CairoVersion, NonceManager, BALANCE, MAX_FEE, MAX_L1_GAS_AMOUNT,
MAX_L1_GAS_PRICE,
};
use crate::transaction::account_transaction::AccountTransaction;
use crate::transaction::constants;
Expand Down Expand Up @@ -132,67 +126,6 @@ pub fn create_test_init_data(chain_info: &ChainInfo, cairo_version: CairoVersion
}
}

pub fn create_account_tx_test_state(
account_class: ContractClass,
account_class_hash: &str,
account_address: &str,
erc20_account_balance_key: StorageKey,
initial_account_balance: u128,
test_contract_class: ContractClass,
) -> CachedState<DictStateReader> {
let test_contract_class_hash = class_hash!(TEST_CLASS_HASH);
let test_account_class_hash = class_hash!(account_class_hash);
let test_erc20_class_hash = class_hash!(TEST_ERC20_CONTRACT_CLASS_HASH);
let class_hash_to_class = HashMap::from([
(test_account_class_hash, account_class),
(test_contract_class_hash, test_contract_class),
(test_erc20_class_hash, ContractClassV0::from_file(ERC20_CONTRACT_PATH).into()),
]);
let test_contract_address = contract_address!(TEST_CONTRACT_ADDRESS);
// A random address that is unlikely to equal the result of the calculation of a contract
// address.
let test_account_address = contract_address!(account_address);
let FeeTokenAddresses {
eth_fee_token_address: test_eth_token_address,
strk_fee_token_address: test_strk_token_address,
} = ChainInfo::create_for_testing().fee_token_addresses;
let address_to_class_hash = HashMap::from([
(test_contract_address, test_contract_class_hash),
(test_account_address, test_account_class_hash),
(test_strk_token_address, test_erc20_class_hash),
(test_eth_token_address, test_erc20_class_hash),
]);
let minter_var_address = get_storage_var_address("permitted_minter", &[]);

let initial_balance_felt = stark_felt!(initial_account_balance);
let storage_view = HashMap::from([
((test_strk_token_address, erc20_account_balance_key), initial_balance_felt),
((test_eth_token_address, erc20_account_balance_key), initial_balance_felt),
// Give the account mint permission.
((test_strk_token_address, minter_var_address), *test_account_address.0.key()),
((test_eth_token_address, minter_var_address), *test_account_address.0.key()),
]);
CachedState::from(DictStateReader {
address_to_class_hash,
class_hash_to_class,
storage_view,
..Default::default()
})
}

pub fn create_state_with_falliable_validation_account() -> CachedState<DictStateReader> {
let account_balance = BALANCE;
create_account_tx_test_state(
ContractClassV0::from_file(TEST_FAULTY_ACCOUNT_CONTRACT_CAIRO0_PATH).into(),
TEST_FAULTY_ACCOUNT_CONTRACT_CLASS_HASH,
TEST_FAULTY_ACCOUNT_CONTRACT_ADDRESS,
test_erc20_faulty_account_balance_key(),
account_balance * 2,
// TODO(Noa,01/12/2023): Use `once_cell::sync::Lazy` to create the contract class.
ContractClassV0::from_file(TEST_CONTRACT_CAIRO0_PATH).into(),
)
}

pub struct FaultyAccountTxCreatorArgs {
pub tx_type: TransactionType,
pub scenario: u64,
Expand Down
150 changes: 68 additions & 82 deletions crates/blockifier/src/transaction/transactions_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ use crate::context::{BlockContext, ChainInfo, FeeTokenAddresses, TransactionCont
use crate::execution::call_info::{
CallExecution, CallInfo, MessageToL1, OrderedEvent, OrderedL2ToL1Message, Retdata,
};
use crate::execution::contract_class::{ContractClass, ContractClassV0, ContractClassV1};
use crate::execution::entry_point::{CallEntryPoint, CallType};
use crate::execution::errors::EntryPointExecutionError;
use crate::execution::execution_utils::{felt_to_stark_felt, stark_felt_to_felt};
Expand All @@ -51,13 +50,11 @@ use crate::test_utils::initial_test_state::test_state;
use crate::test_utils::invoke::invoke_tx;
use crate::test_utils::prices::Prices;
use crate::test_utils::{
create_calldata, create_trivial_calldata, test_erc20_account_balance_key,
test_erc20_sequencer_balance_key, CairoVersion, NonceManager, SaltManager,
ACCOUNT_CONTRACT_CAIRO1_PATH, BALANCE, CHAIN_ID_NAME, CURRENT_BLOCK_NUMBER,
create_calldata, create_trivial_calldata, test_erc20_sequencer_balance_key, CairoVersion,
NonceManager, SaltManager, BALANCE, CHAIN_ID_NAME, CURRENT_BLOCK_NUMBER,
CURRENT_BLOCK_NUMBER_FOR_VALIDATE, CURRENT_BLOCK_TIMESTAMP,
CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE, MAX_FEE, MAX_L1_GAS_AMOUNT, MAX_L1_GAS_PRICE,
TEST_ACCOUNT_CONTRACT_ADDRESS, TEST_ACCOUNT_CONTRACT_CLASS_HASH, TEST_CONTRACT_ADDRESS,
TEST_CONTRACT_CAIRO0_PATH, TEST_CONTRACT_CAIRO1_PATH, TEST_SEQUENCER_ADDRESS,
TEST_SEQUENCER_ADDRESS,
};
use crate::transaction::account_transaction::AccountTransaction;
use crate::transaction::constants;
Expand All @@ -70,9 +67,9 @@ use crate::transaction::objects::{
};
use crate::transaction::test_utils::{
account_invoke_tx, calculate_class_info_for_testing, create_account_tx_for_validate_test,
create_account_tx_test_state, l1_resource_bounds, FaultyAccountTxCreatorArgs, CALL_CONTRACT,
GET_BLOCK_HASH, GET_BLOCK_NUMBER, GET_BLOCK_TIMESTAMP, GET_EXECUTION_INFO,
GET_SEQUENCER_ADDRESS, INVALID, VALID,
l1_resource_bounds, FaultyAccountTxCreatorArgs, CALL_CONTRACT, GET_BLOCK_HASH,
GET_BLOCK_NUMBER, GET_BLOCK_TIMESTAMP, GET_EXECUTION_INFO, GET_SEQUENCER_ADDRESS, INVALID,
VALID,
};
use crate::transaction::transaction_types::TransactionType;
use crate::transaction::transactions::{ExecutableTransaction, L1HandlerTransaction};
Expand Down Expand Up @@ -1870,106 +1867,95 @@ fn max_event_data() -> usize {
VERSIONED_CONSTANTS.tx_event_limits.max_data_length
}

#[test_case(
#[rstest]
#[case::positive_flow(
vec![stark_felt!(1_u16); max_event_keys()],
vec![stark_felt!(2_u16); max_event_data()],
max_n_emitted_events(),
None;
"Positive flow")]
#[test_case(
None)]
#[case::exceeds_max_number_of_events(
vec![stark_felt!(1_u16)],
vec![stark_felt!(2_u16)],
max_n_emitted_events() + 1,
Some(EmitEventError::ExceedsMaxNumberOfEmittedEvents {
n_emitted_events: max_n_emitted_events() + 1,
max_n_emitted_events: max_n_emitted_events(),
});
"exceeds max number of events")]
#[test_case(
}))]
#[case::exceeds_max_number_of_keys(
vec![stark_felt!(3_u16); max_event_keys() + 1],
vec![stark_felt!(4_u16)],
1,
Some(EmitEventError::ExceedsMaxKeysLength{
keys_length: max_event_keys() + 1,
max_keys_length: max_event_keys(),
});
"exceeds max number of keys")]
#[test_case(
}))]
#[case::exceeds_data_length(
vec![stark_felt!(5_u16)],
vec![stark_felt!(6_u16); max_event_data() + 1],
1,
Some(EmitEventError::ExceedsMaxDataLength{
data_length: max_event_data() + 1,
max_data_length: max_event_data(),
});
"exceeds data length")]
}))]
fn test_emit_event_exceeds_limit(
event_keys: Vec<StarkFelt>,
event_data: Vec<StarkFelt>,
n_emitted_events: usize,
expected_error: Option<EmitEventError>,
#[case] event_keys: Vec<StarkFelt>,
#[case] event_data: Vec<StarkFelt>,
#[case] n_emitted_events: usize,
#[case] expected_error: Option<EmitEventError>,
#[values(CairoVersion::Cairo0, CairoVersion::Cairo1)] cairo_version: CairoVersion,
) {
for cairo_version in [0, 1] {
let contract_class: ContractClass = match cairo_version {
0 => ContractClassV0::from_file(TEST_CONTRACT_CAIRO0_PATH).into(),
1 => ContractClassV1::from_file(TEST_CONTRACT_CAIRO1_PATH).into(),
_ => panic!("Invalid cairo version"),
};
let state = &mut create_account_tx_test_state(
ContractClassV1::from_file(ACCOUNT_CONTRACT_CAIRO1_PATH).into(),
TEST_ACCOUNT_CONTRACT_CLASS_HASH,
TEST_ACCOUNT_CONTRACT_ADDRESS,
test_erc20_account_balance_key(),
BALANCE,
contract_class,
);
let block_context = &BlockContext::create_for_account_testing();
let sender_address = ContractAddress(patricia_key!(TEST_ACCOUNT_CONTRACT_ADDRESS));
let entry_point_selector = selector_from_name("test_emit_events");
let calldata = [
vec![stark_felt!(
u16::try_from(n_emitted_events).expect("Failed to convert usize to u16.")
)]
.to_owned(),
vec![stark_felt!(
u16::try_from(event_keys.len()).expect("Failed to convert usize to u16.")
)],
event_keys.clone(),
let test_contract = FeatureContract::TestContract(cairo_version);
let account_contract = FeatureContract::AccountWithoutValidations(CairoVersion::Cairo1);
let block_context = &BlockContext::create_for_account_testing();
let state = &mut test_state(
&block_context.chain_info,
BALANCE,
&[(test_contract, 1), (account_contract, 1)],
);

let calldata = [
vec![stark_felt!(
u16::try_from(n_emitted_events).expect("Failed to convert usize to u16.")
)]
.to_owned(),
vec![stark_felt!(
u16::try_from(event_keys.len()).expect("Failed to convert usize to u16.")
)],
event_keys.clone(),
vec![stark_felt!(
u16::try_from(event_data.len()).expect("Failed to convert usize to u16.")
)],
event_data.clone(),
]
.concat();
let execute_calldata = Calldata(
[
vec![test_contract.get_instance_address(0).into()],
vec![selector_from_name("test_emit_events").0],
vec![stark_felt!(
u16::try_from(event_data.len()).expect("Failed to convert usize to u16.")
u16::try_from(calldata.len()).expect("Failed to convert usize to u16.")
)],
event_data.clone(),
calldata.clone(),
]
.concat();
let execute_calldata = Calldata(
[
vec![stark_felt!(TEST_CONTRACT_ADDRESS)],
vec![entry_point_selector.0],
vec![stark_felt!(
u16::try_from(calldata.len()).expect("Failed to convert usize to u16.")
)],
calldata.clone(),
]
.concat()
.into(),
);
.concat()
.into(),
);

let account_tx = account_invoke_tx(invoke_tx_args! {
max_fee: Fee(MAX_FEE),
sender_address,
calldata: execute_calldata,
version: TransactionVersion::ONE,
nonce: Nonce(stark_felt!(0_u8)),
});
let execution_info = account_tx.execute(state, block_context, true, true).unwrap();
match &expected_error {
Some(expected_error) => {
let error_string = execution_info.revert_error.unwrap();
assert!(error_string.contains(&format!("{}", expected_error)));
}
None => {
assert!(!execution_info.is_reverted());
}
let account_tx = account_invoke_tx(invoke_tx_args! {
max_fee: Fee(MAX_FEE),
sender_address: account_contract.get_instance_address(0),
calldata: execute_calldata,
version: TransactionVersion::ONE,
nonce: Nonce(stark_felt!(0_u8)),
});
let execution_info = account_tx.execute(state, block_context, true, true).unwrap();
match &expected_error {
Some(expected_error) => {
let error_string = execution_info.revert_error.unwrap();
assert!(error_string.contains(&format!("{}", expected_error)));
}
None => {
assert!(!execution_info.is_reverted());
}
}
}

0 comments on commit e2b0591

Please sign in to comment.