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

Commit

Permalink
feat(fee): add GasVector to TransactionExecutionInfo (#1399)
Browse files Browse the repository at this point in the history
* feat(fee): add DA GasVector to TransactionExecutionInfo

Signed-off-by: Dori Medini <[email protected]>

* chore(fee): rename blob_gas to l1_data_gas

Signed-off-by: Dori Medini <[email protected]>

* chore(fee): delete unused PyGasVector

Signed-off-by: Dori Medini <[email protected]>
  • Loading branch information
dorimedini-starkware authored Feb 8, 2024
1 parent 27ac871 commit 2475cef
Show file tree
Hide file tree
Showing 15 changed files with 88 additions and 67 deletions.
16 changes: 12 additions & 4 deletions crates/blockifier/src/fee/actual_cost.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,22 @@ use crate::abi::constants as abi_constants;
use crate::context::TransactionContext;
use crate::execution::call_info::CallInfo;
use crate::execution::entry_point::ExecutionResources;
use crate::fee::gas_usage::calculate_tx_gas_usage_vector;
use crate::fee::gas_usage::{calculate_tx_gas_usage_vector, get_da_gas_cost};
use crate::state::cached_state::{CachedState, StateChanges};
use crate::state::state_api::{StateReader, StateResult};
use crate::transaction::objects::{
HasRelatedFeeType, ResourcesMapping, TransactionExecutionResult,
GasVector, HasRelatedFeeType, ResourcesMapping, TransactionExecutionResult,
};
use crate::transaction::transaction_types::TransactionType;
use crate::transaction::transaction_utils::calculate_tx_resources;
use crate::transaction::transactions::ClassInfo;

// TODO(Gilad): Use everywhere instead of passing the `actual_{fee,resources}` tuple, which often
// get passed around together.
#[derive(Default)]
pub struct ActualCost {
pub actual_fee: Fee,
pub da_gas: GasVector,
pub actual_resources: ResourcesMapping,
}

Expand Down Expand Up @@ -134,18 +136,24 @@ impl<'a> ActualCostBuilder<'a> {

// Private methods.

fn use_kzg_da(&self) -> bool {
self.tx_context.block_context.block_info.use_kzg_da
}

// Construct the actual cost object using all fields that were set in the builder.
fn calculate_actual_fee_and_resources(
self,
execution_resources: &ExecutionResources,
) -> TransactionExecutionResult<ActualCost> {
let use_kzg_da = self.use_kzg_da();
let state_changes_count = self.state_changes.count_for_fee_charge(
self.sender_address,
self.tx_context
.block_context
.chain_info
.fee_token_address(&self.tx_context.tx_info.fee_type()),
);
let da_gas = get_da_gas_cost(state_changes_count, use_kzg_da);
let non_optional_call_infos =
self.validate_call_info.into_iter().chain(self.execute_call_info);
// Gas usage for SHARP costs and Starknet L1-L2 messages. Includes gas usage for data
Expand All @@ -154,7 +162,7 @@ impl<'a> ActualCostBuilder<'a> {
non_optional_call_infos,
state_changes_count,
self.l1_payload_size,
self.tx_context.block_context.block_info.use_kzg_da,
use_kzg_da,
)?;

let mut actual_resources = calculate_tx_resources(
Expand All @@ -179,6 +187,6 @@ impl<'a> ActualCostBuilder<'a> {
Fee(0)
};

Ok(ActualCost { actual_fee, actual_resources })
Ok(ActualCost { actual_fee, da_gas, actual_resources })
}
}
4 changes: 2 additions & 2 deletions crates/blockifier/src/fee/fee_checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ impl FeeCheckReport {
&tx_context.block_context.block_info,
GasVector {
l1_gas: info.l1_resource_bounds()?.max_amount.into(),
blob_gas: 0,
l1_data_gas: 0,
},
&FeeType::Strk,
),
Expand All @@ -93,7 +93,7 @@ impl FeeCheckReport {
tx_context: &TransactionContext,
actual_cost: &ActualCost,
) -> TransactionExecutionResult<()> {
let ActualCost { actual_fee, actual_resources } = actual_cost;
let ActualCost { actual_fee, actual_resources, .. } = actual_cost;
let TransactionContext { tx_info, block_context } = tx_context;

// First, compare the actual resources used against the upper bound(s) defined by the
Expand Down
3 changes: 2 additions & 1 deletion crates/blockifier/src/fee/fee_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ fn test_calculate_l1_gas_by_vm_usage() {
// Verify calculation - in our case, n_steps is the heaviest resource.
let l1_gas_by_vm_usage = vm_resource_usage.0.get(constants::N_STEPS_RESOURCE).unwrap();
assert_eq!(
GasVector { l1_gas: *l1_gas_by_vm_usage as u128, blob_gas: 0 },
GasVector { l1_gas: *l1_gas_by_vm_usage as u128, l1_data_gas: 0 },
calculate_l1_gas_by_vm_usage(&versioned_constants, &vm_resource_usage).unwrap()
);

Expand Down Expand Up @@ -89,6 +89,7 @@ fn test_discounted_gas_overdraft(
(constants::L1_GAS_USAGE.to_string(), l1_gas_used),
(constants::BLOB_GAS_USAGE.to_string(), l1_data_gas_used),
])),
..Default::default()
};
let charge_fee = true;
let report = PostExecutionReport::new(
Expand Down
4 changes: 2 additions & 2 deletions crates/blockifier/src/fee/fee_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub fn calculate_l1_gas_by_vm_usage(
.fold(f64::NAN, f64::max);

// TODO(Dori, 1/5/2024): Check this conversion.
Ok(GasVector { l1_gas: vm_l1_gas_usage.ceil() as u128, blob_gas: 0 })
Ok(GasVector { l1_gas: vm_l1_gas_usage.ceil() as u128, l1_data_gas: 0 })
}

/// Computes and returns the total L1 gas consumption.
Expand All @@ -75,7 +75,7 @@ pub fn calculate_tx_gas_vector(
Ok(GasVector {
l1_gas: u128_from_usize(l1_gas_usage)
.expect("Conversion from usize to u128 should not fail."),
blob_gas: u128_from_usize(l1_blob_gas_usage)
l1_data_gas: u128_from_usize(l1_blob_gas_usage)
.expect("Conversion from usize to u128 should not fail."),
} + vm_usage_gas_vector)
}
Expand Down
16 changes: 8 additions & 8 deletions crates/blockifier/src/fee/gas_usage.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::collections::HashMap;

use super::fee_utils::calculate_tx_gas_vector;
use crate::abi::constants;
use crate::context::{BlockContext, TransactionContext};
use crate::execution::call_info::{CallInfo, MessageL1CostInfo};
use crate::fee::eth_gas_constants;
use crate::fee::fee_utils::calculate_tx_gas_vector;
use crate::state::cached_state::StateChangesCount;
use crate::transaction::account_transaction::AccountTransaction;
use crate::transaction::objects::{
Expand Down Expand Up @@ -56,7 +56,7 @@ pub fn calculate_messages_gas_vector<'a>(
+ n_l1_to_l2_messages * eth_gas_constants::GAS_PER_COUNTER_DECREASE,
)
.expect("Could not convert starknet gas usage from usize to u128."),
blob_gas: 0,
l1_data_gas: 0,
} + get_consumed_message_to_l2_emissions_cost(l1_handler_payload_size)
+ get_log_message_to_l1_emissions_cost(&l2_to_l1_payload_lengths);

Expand All @@ -65,7 +65,7 @@ pub fn calculate_messages_gas_vector<'a>(
message_segment_length * eth_gas_constants::SHARP_GAS_PER_MEMORY_WORD,
)
.expect("Could not convert sharp gas usage from usize to u128."),
blob_gas: 0,
l1_data_gas: 0,
};

Ok(starknet_gas_usage + sharp_gas_usage)
Expand Down Expand Up @@ -129,7 +129,7 @@ pub fn get_da_gas_cost(state_changes_count: StateChangesCount, use_kzg_da: bool)
(u128_from_usize(gas).expect("Failed to convert L1 gas usage from usize to u128."), 0)
};

GasVector { l1_gas, blob_gas }
GasVector { l1_gas, l1_data_gas: blob_gas }
}

/// Returns the number of felts added to the output messages segment as a result of adding
Expand Down Expand Up @@ -164,7 +164,7 @@ pub fn get_consumed_message_to_l2_emissions_cost(
) -> GasVector {
match l1_handler_payload_size {
// The corresponding transaction is not an L1 handler.,
None => GasVector { l1_gas: 0, blob_gas: 0 },
None => GasVector { l1_gas: 0, l1_data_gas: 0 },
Some(l1_handler_payload_size) => {
get_event_emission_cost(
constants::CONSUMED_MSG_TO_L2_N_TOPICS,
Expand Down Expand Up @@ -197,7 +197,7 @@ fn get_event_emission_cost(n_topics: usize, data_length: usize) -> GasVector {
+ data_length * eth_gas_constants::GAS_PER_LOG_DATA_WORD,
)
.expect("Cannot convert event emission gas from usize to u128."),
blob_gas: 0,
l1_data_gas: 0,
}
}

Expand Down Expand Up @@ -234,7 +234,7 @@ pub fn estimate_minimal_gas_vector(
n_modified_contracts: 1,
},
};
let GasVector { l1_gas: gas_cost, blob_gas: blob_gas_cost } =
let GasVector { l1_gas: gas_cost, l1_data_gas: blob_gas_cost } =
get_da_gas_cost(state_changes_by_account_transaction, block_info.use_kzg_da);

let resources = ResourcesMapping(HashMap::from([
Expand Down Expand Up @@ -265,7 +265,7 @@ pub fn compute_discounted_gas_from_gas_vector(
tx_context: &TransactionContext,
) -> u128 {
let gas_prices = &tx_context.block_context.block_info.gas_prices;
let GasVector { l1_gas: gas_usage, blob_gas: blob_gas_usage } = gas_usage_vector;
let GasVector { l1_gas: gas_usage, l1_data_gas: blob_gas_usage } = gas_usage_vector;
let fee_type = tx_context.tx_info.fee_type();
let gas_price = gas_prices.get_gas_price_by_fee_type(&fee_type);
let data_gas_price = gas_prices.get_data_gas_price_by_fee_type(&fee_type);
Expand Down
12 changes: 6 additions & 6 deletions crates/blockifier/src/fee/gas_usage_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ fn test_get_da_gas_cost_basic(#[case] state_changes_count: StateChangesCount) {

let computed_gas_vector = get_da_gas_cost(state_changes_count, true);
assert_eq!(
GasVector { l1_gas: 0, blob_gas: u128_from_usize(manual_blob_gas_usage).unwrap() },
GasVector { l1_gas: 0, l1_data_gas: u128_from_usize(manual_blob_gas_usage).unwrap() },
computed_gas_vector
);
}
Expand All @@ -80,7 +80,7 @@ fn test_calculate_tx_gas_usage_basic(#[values(false, true)] use_kzg_da: bool) {
use_kzg_da,
)
.unwrap();
assert_eq!(empty_tx_gas_usage_vector, GasVector { l1_gas: 0, blob_gas: 0 });
assert_eq!(empty_tx_gas_usage_vector, GasVector { l1_gas: 0, l1_data_gas: 0 });

// DeployAccount.

Expand Down Expand Up @@ -128,7 +128,7 @@ fn test_calculate_tx_gas_usage_basic(#[values(false, true)] use_kzg_da: bool) {
message_segment_length * eth_gas_constants::SHARP_GAS_PER_MEMORY_WORD;
let manual_gas_computation = GasVector {
l1_gas: u128_from_usize(manual_starknet_gas_usage + manual_sharp_gas_usage).unwrap(),
blob_gas: 0,
l1_data_gas: 0,
};

assert_eq!(l1_handler_gas_usage_vector, manual_gas_computation);
Expand Down Expand Up @@ -190,10 +190,10 @@ fn test_calculate_tx_gas_usage_basic(#[values(false, true)] use_kzg_da: bool) {
+ usize_from_u128(get_da_gas_cost(l2_to_l1_state_changes_count, use_kzg_da).l1_gas)
.unwrap();
let manual_sharp_blob_gas_usage =
get_da_gas_cost(l2_to_l1_state_changes_count, use_kzg_da).blob_gas;
get_da_gas_cost(l2_to_l1_state_changes_count, use_kzg_da).l1_data_gas;
let manual_gas_computation = GasVector {
l1_gas: u128_from_usize(manual_starknet_gas_usage + manual_sharp_gas_usage).unwrap(),
blob_gas: manual_sharp_blob_gas_usage,
l1_data_gas: manual_sharp_blob_gas_usage,
};

assert_eq!(l2_to_l1_messages_gas_usage_vector, manual_gas_computation);
Expand Down Expand Up @@ -253,7 +253,7 @@ fn test_calculate_tx_gas_usage_basic(#[values(false, true)] use_kzg_da: bool) {
// the combined calculation got it once.
+ u128_from_usize(fee_balance_discount).unwrap(),
// Expected blob gas usage is from data availability only.
blob_gas: get_da_gas_cost(combined_state_changes_count, use_kzg_da).blob_gas,
l1_data_gas: get_da_gas_cost(combined_state_changes_count, use_kzg_da).l1_data_gas,
};

assert_eq!(expected_gas_vector, gas_usage_vector);
Expand Down
3 changes: 1 addition & 2 deletions crates/blockifier/src/test_utils/deploy_account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ use starknet_api::transaction::{
TransactionVersion,
};

use super::default_testing_resource_bounds;
use crate::test_utils::NonceManager;
use crate::test_utils::{default_testing_resource_bounds, NonceManager};
use crate::transaction::transactions::DeployAccountTransaction;

#[derive(Clone)]
Expand Down
12 changes: 6 additions & 6 deletions crates/blockifier/src/test_utils/struct_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,6 @@ use starknet_api::core::{ChainId, ContractAddress, PatriciaKey};
use starknet_api::hash::StarkHash;
use starknet_api::{contract_address, patricia_key};

use super::{
CHAIN_ID_NAME, CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_TIMESTAMP, DEFAULT_ETH_L1_DATA_GAS_PRICE,
DEFAULT_ETH_L1_GAS_PRICE, DEFAULT_STRK_L1_DATA_GAS_PRICE, DEFAULT_STRK_L1_GAS_PRICE,
TEST_ERC20_CONTRACT_ADDRESS, TEST_ERC20_CONTRACT_ADDRESS2, TEST_SEQUENCER_ADDRESS,
};
use crate::block::{BlockInfo, GasPrices};
use crate::context::{BlockContext, ChainInfo, FeeTokenAddresses, TransactionContext};
use crate::execution::call_info::{CallExecution, CallInfo, Retdata};
Expand All @@ -18,7 +13,12 @@ use crate::execution::entry_point::{
CallEntryPoint, EntryPointExecutionContext, EntryPointExecutionResult, ExecutionResources,
};
use crate::state::state_api::State;
use crate::test_utils::get_raw_contract_class;
use crate::test_utils::{
get_raw_contract_class, CHAIN_ID_NAME, CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_TIMESTAMP,
DEFAULT_ETH_L1_DATA_GAS_PRICE, DEFAULT_ETH_L1_GAS_PRICE, DEFAULT_STRK_L1_DATA_GAS_PRICE,
DEFAULT_STRK_L1_GAS_PRICE, TEST_ERC20_CONTRACT_ADDRESS, TEST_ERC20_CONTRACT_ADDRESS2,
TEST_SEQUENCER_ADDRESS,
};
use crate::transaction::objects::{DeprecatedTransactionInfo, TransactionInfo};
use crate::versioned_constants::VersionedConstants;

Expand Down
12 changes: 9 additions & 3 deletions crates/blockifier/src/transaction/account_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ impl AccountTransaction {
post_execution_error.to_string(),
ActualCost {
actual_fee: post_execution_report.recommended_fee(),
actual_resources: revert_cost.actual_resources,
..revert_cost
},
))
}
Expand All @@ -512,7 +512,7 @@ impl AccountTransaction {
execution_context.error_trace(),
ActualCost {
actual_fee: post_execution_report.recommended_fee(),
actual_resources: revert_cost.actual_resources,
..revert_cost
},
))
}
Expand Down Expand Up @@ -582,7 +582,12 @@ impl<S: StateReader> ExecutableTransaction<S> for AccountTransaction {
validate_call_info,
execute_call_info,
revert_error,
final_cost: ActualCost { actual_fee: final_fee, actual_resources: final_resources },
final_cost:
ActualCost {
actual_fee: final_fee,
da_gas: final_da_gas,
actual_resources: final_resources,
},
} = self.run_or_revert(
state,
&mut remaining_gas,
Expand All @@ -598,6 +603,7 @@ impl<S: StateReader> ExecutableTransaction<S> for AccountTransaction {
execute_call_info,
fee_transfer_call_info,
actual_fee: final_fee,
da_gas: final_da_gas,
actual_resources: final_resources,
revert_error,
};
Expand Down
4 changes: 2 additions & 2 deletions crates/blockifier/src/transaction/execution_flavors_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ fn gas_and_fee(base_gas: u64, validate_mode: bool, fee_type: &FeeType) -> (u64,
gas,
get_fee_by_gas_vector(
&BlockContext::create_for_account_testing().block_info,
GasVector { l1_gas: gas.into(), blob_gas: 0 },
GasVector { l1_gas: gas.into(), l1_data_gas: 0 },
fee_type,
),
)
Expand Down Expand Up @@ -489,7 +489,7 @@ fn test_simulate_validate_charge_fee_mid_execution(
let block_limit_gas = invoke_tx_max_n_steps_as_u64 + 1652;
let block_limit_fee = get_fee_by_gas_vector(
&block_context.block_info,
GasVector { l1_gas: block_limit_gas.into(), blob_gas: 0 },
GasVector { l1_gas: block_limit_gas.into(), l1_data_gas: 0 },
&fee_type,
);
let tx_execution_info = account_invoke_tx(invoke_tx_args! {
Expand Down
10 changes: 6 additions & 4 deletions crates/blockifier/src/transaction/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,10 @@ pub struct DeprecatedTransactionInfo {
pub max_fee: Fee,
}

#[derive(derive_more::Add, derive_more::Sum, Clone, Debug, Default, Eq, PartialEq)]
#[derive(derive_more::Add, derive_more::Sum, Clone, Debug, Default, Eq, PartialEq, Serialize)]
pub struct GasVector {
pub l1_gas: u128,
pub blob_gas: u128,
pub l1_data_gas: u128,
}

impl GasVector {
Expand All @@ -141,10 +141,10 @@ impl GasVector {
);
u128::MAX
});
let l1_data_gas_cost = self.blob_gas.checked_mul(blob_gas_price).unwrap_or_else(|| {
let l1_data_gas_cost = self.l1_data_gas.checked_mul(blob_gas_price).unwrap_or_else(|| {
log::warn!(
"L1 blob gas cost overflowed: multiplication of {} by {} resulted in overflow.",
self.blob_gas,
self.l1_data_gas,
blob_gas_price
);
u128::MAX
Expand Down Expand Up @@ -182,6 +182,8 @@ pub struct TransactionExecutionInfo {
pub fee_transfer_call_info: Option<CallInfo>,
/// The actual fee that was charged (in Wei).
pub actual_fee: Fee,
/// Actual gas consumption the transaction is charged for data availability.
pub da_gas: GasVector,
/// Actual execution resources the transaction is charged for,
/// including L1 gas and additional OS resources estimation.
pub actual_resources: ResourcesMapping,
Expand Down
3 changes: 2 additions & 1 deletion crates/blockifier/src/transaction/transaction_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ impl<S: StateReader> ExecutableTransaction<S> for L1HandlerTransaction {
self.run_execute(state, &mut execution_resources, &mut context, &mut remaining_gas)?;
let l1_handler_payload_size = self.payload_size();

let ActualCost { actual_fee, actual_resources } =
let ActualCost { actual_fee, da_gas, actual_resources } =
ActualCost::builder_for_l1_handler(tx_context, l1_handler_payload_size)
.with_execute_call_info(&execute_call_info)
.try_add_state_changes(state)?
Expand All @@ -131,6 +131,7 @@ impl<S: StateReader> ExecutableTransaction<S> for L1HandlerTransaction {
execute_call_info,
fee_transfer_call_info: None,
actual_fee: Fee::default(),
da_gas,
actual_resources,
revert_error: None,
})
Expand Down
Loading

0 comments on commit 2475cef

Please sign in to comment.