// Copyright 2019-2026 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use crate::blocks::Tipset; use crate::chain::{BASE_FEE_MAX_CHANGE_DENOM, BLOCK_GAS_TARGET}; use crate::interpreter::VMTrace; use crate::message::ChainMessage; use crate::prelude::*; use crate::rpc::eth::errors::EthErrors; use crate::rpc::{ApiPaths, Ctx, Permission, RpcMethod, error::ServerError, types::*}; use crate::shim::executor::ApplyRet; use crate::shim::{ address::Address, bigint::MAX_BIGINT_BITS, econ::{BLOCK_GAS_LIMIT, TokenAmount}, message::Message, }; use crate::state_manager::{SenderValidation, VMFlush}; use anyhow::Result; use enumflags2::BitFlags; use num::BigInt; use num_traits::{FromPrimitive, Zero}; use rand_distr::{Distribution, Normal}; use std::ops::Add; const MIN_GAS_PREMIUM: f64 = 100000.0; // constant taken from here const MAX_GAS_HISTORY: u64 = 128; /// Estimate the fee cap pub enum GasEstimateFeeCap {} impl RpcMethod<3> for GasEstimateFeeCap { const NAME: &'static str = "Filecoin.GasEstimateFeeCap"; const PARAM_NAMES: [&'static str; 3] = ["message", "maxQueueBlocks", "tipsetKey"]; const API_PATHS: BitFlags = ApiPaths::all(); const PERMISSION: Permission = Permission::Read; const DESCRIPTION: &'static str = "Returns the estimated fee cap for the given parameters."; type Params = (Message, i64, ApiTipsetKey); type Ok = TokenAmount; async fn handle( ctx: Ctx, (msg, max_queue_blks, tsk): Self::Params, _: &http::Extensions, ) -> Result { estimate_fee_cap(&ctx, msg.gas_premium(), max_queue_blks, &tsk) } } fn estimate_fee_cap( data: &Ctx, gas_premium: &TokenAmount, max_queue_blks: i64, ApiTipsetKey(ts_key): &ApiTipsetKey, ) -> Result { let ts = data .chain_store() .load_required_tipset_or_heaviest(ts_key)?; let parent_base_fee = &ts.block_headers().first().parent_base_fee; let increase_factor = (1.0 + (BASE_FEE_MAX_CHANGE_DENOM as f64).recip()).powf(max_queue_blks as f64); let fee_in_future = parent_base_fee * BigInt::from_f64(increase_factor * f64::from(1_i32 << 8)) .context("failed to convert fee_in_future f64 to bigint")?; let out = fee_in_future.div_floor(1 << 8).add(gas_premium); Ok(out) } /// Estimate the fee cap pub enum GasEstimateGasPremium {} impl RpcMethod<4> for GasEstimateGasPremium { const NAME: &'static str = "Filecoin.GasEstimateGasPremium"; const PARAM_NAMES: [&'static str; 4] = [ "numberOfBlocksToInclude", "senderAddress", "gasLimit", "tipsetKey", ]; const API_PATHS: BitFlags = ApiPaths::all(); const PERMISSION: Permission = Permission::Read; const DESCRIPTION: &'static str = "Returns the estimated gas premium for the given parameters."; type Params = (u64, Address, i64, ApiTipsetKey); type Ok = TokenAmount; async fn handle( ctx: Ctx, (nblocksincl, _sender, _gas_limit, tsk): Self::Params, _: &http::Extensions, ) -> Result { estimate_gas_premium(&ctx, nblocksincl, &tsk).await } } #[derive(Clone)] struct GasMeta { pub price: TokenAmount, pub limit: u64, } pub async fn estimate_gas_premium( ctx: &Ctx, nblocksincl: u64, ApiTipsetKey(ts_key): &ApiTipsetKey, ) -> Result { let nblocksincl = nblocksincl.clamp(1, MAX_GAS_HISTORY); let mut prices: Vec = Vec::new(); let mut blocks = 0; let mut ts = ctx.chain_store().load_required_tipset_or_heaviest(ts_key)?; for _ in 0..(nblocksincl * 2) { if ts.epoch() == 0 { break; } let parent_ts = ctx.chain_index().load_required_tipset(ts.parents())?; blocks += parent_ts.block_headers().len(); let msgs = ctx.chain_store().messages_for_tipset(&parent_ts)?; prices.append( &mut msgs .iter() .map(|msg| GasMeta { price: msg.message().gas_premium().clone(), limit: msg.message().gas_limit(), }) .collect(), ); ts = parent_ts; } let mut premium = compute_gas_premium(prices, blocks as u64); if premium < TokenAmount::from_atto(MIN_GAS_PREMIUM as u64) { premium = TokenAmount::from_atto(match nblocksincl { 1 => (MIN_GAS_PREMIUM * 2.0) as u64, 2 => (MIN_GAS_PREMIUM * 1.5) as u64, _ => MIN_GAS_PREMIUM as u64, }); } let precision = 32; // mean 1, stddev 0.005 => 95% within +-1% let noise: f64 = Normal::new(1.0, 0.005) .expect("mean 1.0 and stddev 0.005 are valid normal-distribution parameters") .sample(&mut crate::utils::rand::forest_rng()); premium *= BigInt::from_f64((noise * (1i64 << precision) as f64) + 1f64) .context("failed to convert gas premium f64 to bigint")?; premium = premium.div_floor(1i64 << precision); Ok(premium) } // logic taken from here fn compute_gas_premium(mut prices: Vec, blocks: u64) -> TokenAmount { prices.sort_by(|a, b| b.price.cmp(&a.price)); let mut at = BLOCK_GAS_TARGET * blocks / 2; at += BLOCK_GAS_TARGET * blocks / (2 * 20); let mut prev1 = TokenAmount::zero(); let mut prev2 = TokenAmount::zero(); for p in prices { prev2 = prev1; prev1 = p.price; if p.limit > at { // We've crossed the threshold break; } at -= p.limit; } if prev2.is_zero() { prev1 } else { (&prev1 + &prev2).div_floor(2) } } pub enum GasEstimateGasLimit {} impl RpcMethod<2> for GasEstimateGasLimit { const NAME: &'static str = "Filecoin.GasEstimateGasLimit"; const PARAM_NAMES: [&'static str; 2] = ["message", "tipsetKey"]; const API_PATHS: BitFlags = ApiPaths::all(); const PERMISSION: Permission = Permission::Read; const DESCRIPTION: &'static str = "Returns the estimated gas limit for the given parameters."; type Params = (Message, ApiTipsetKey); type Ok = i64; async fn handle( ctx: Ctx, (msg, ApiTipsetKey(tsk)): Self::Params, _: &http::Extensions, ) -> Result { let ts = ctx.chain_store().load_required_tipset_or_heaviest(&tsk)?; Ok(Self::estimate_gas_limit(&ctx, msg, &ts, SenderValidation::Enforce).await?) } } impl GasEstimateGasLimit { /// Runs `msg` at the block gas limit with the fees zeroed, to measure what it uses. pub async fn measure_gas_used( data: &Ctx, msg: Message, curr_ts: &Tipset, sender_validation: SenderValidation, ) -> anyhow::Result<(ApplyRet, Arc>, Tipset, Address)> { let msg = without_fees(msg, BLOCK_GAS_LIMIT); Self::probe_as_specified(data, msg, curr_ts, VMTrace::NotTraced, sender_validation).await } /// Runs `msg` exactly as given. The limit and fees are left alone: a gas search compares this /// against runs of the same message, so rewriting either here would measure something the /// caller never asked about. Also returns the resolved sender so a caller can avoid /// resolving it a second time. pub async fn probe_as_specified( data: &Ctx, msg: Message, curr_ts: &Tipset, vm_trace: VMTrace, sender_validation: SenderValidation, ) -> anyhow::Result<(ApplyRet, Arc>, Tipset, Address)> { let from_a = match sender_validation { SenderValidation::Skip => msg.from(), SenderValidation::Enforce => data .state_manager .resolve_to_deterministic_address(msg.from(), curr_ts) .await .map_err(|e| { crate::state_manager::Error::SenderValidationFailed(format!( "resolving sender {} ({e:#})", msg.from() )) })?, }; let pending = data.mpool.pending_for(&from_a).await; let prior_messages: Arc> = pending .map(|s| s.into_iter().map(Into::into).collect_vec()) .unwrap_or_default() .into(); let ts = data.mpool.current_tipset(); let (apply_ret, ..) = data .state_manager .call_with_gas( msg, from_a.protocol(), prior_messages.shallow_clone(), Some(ts.shallow_clone()), VMFlush::Skip, vm_trace, sender_validation, ) .await?; Ok((apply_ret, prior_messages, ts, from_a)) } pub async fn estimate_gas_limit( data: &Ctx, msg: Message, curr_ts: &Tipset, sender_validation: SenderValidation, ) -> Result { let (apply_ret, ..) = Self::measure_gas_used(data, msg, curr_ts, sender_validation) .await .context("gas estimation failed")?; let exit_code = apply_ret.exit_code(); if exit_code.is_success() { return Ok(apply_ret.gas_used() as i64); } if exit_code == crate::shim::fvm_shared_latest::error::ExitCode::SYS_OUT_OF_GAS { return Err(EthErrors::OutOfGas.into()); } if sender_validation == SenderValidation::Enforce && exit_code == crate::shim::fvm_shared_latest::error::ExitCode::SYS_SENDER_INVALID { let exit_code = crate::shim::error::ExitCode::from(exit_code); return Err(crate::state_manager::Error::SenderValidationFailed(format!( "message execution failed (exit=[{exit_code}], vm error=[{}])", apply_ret.failure_info().unwrap_or_default() )) .into()); } Err(EthErrors::execution_reverted_from_apply_ret(&apply_ret).into()) } } /// `msg` at `gas_limit` with zero fees, so a run judges gas alone and not the sender's funds. pub fn without_fees(msg: Message, gas_limit: u64) -> Message { msg.into_builder() .gas_limit(gas_limit) .gas_fee_cap(TokenAmount::from_atto(0)) .gas_premium(TokenAmount::from_atto(0)) .build() } /// Estimates the gas parameters for a given message pub enum GasEstimateMessageGas {} impl RpcMethod<3> for GasEstimateMessageGas { const NAME: &'static str = "Filecoin.GasEstimateMessageGas"; const PARAM_NAMES: [&'static str; 3] = ["message", "messageSendSpec", "tipsetKey"]; const API_PATHS: BitFlags = ApiPaths::all(); const PERMISSION: Permission = Permission::Read; const DESCRIPTION: &'static str = "Returns the estimated gas for the given parameters."; type Params = (Message, Option, ApiTipsetKey); type Ok = Message; async fn handle( ctx: Ctx, (msg, spec, tsk): Self::Params, _: &http::Extensions, ) -> Result { let message = estimate_message_gas(&ctx, msg, spec, tsk).await?; Ok(message) } } pub async fn estimate_message_gas( data: &Ctx, msg: Message, msg_spec: Option, tsk: ApiTipsetKey, ) -> anyhow::Result { let msg = if msg.gas_limit() == 0 { let ApiTipsetKey(key) = &tsk; let ts = data.chain_store().load_required_tipset_or_heaviest(key)?; let gl = GasEstimateGasLimit::estimate_gas_limit( data, msg.clone(), &ts, SenderValidation::Enforce, ) .await?; let gl = (gl as f64 * data.mpool.gas_limit_overestimation()) as u64; msg.into_builder() .gas_limit(gl.min(BLOCK_GAS_LIMIT)) .build() } else { msg }; let msg = if msg.gas_premium().is_zero() { let gp = estimate_gas_premium(data, 10, &tsk).await?; msg.into_builder().gas_premium(gp).build() } else { msg }; let msg = if msg.gas_fee_cap().is_zero() { let gfp = estimate_fee_cap(data, msg.gas_premium(), 20, &tsk)?; msg.into_builder().gas_fee_cap(gfp).build() } else { msg }; cap_gas_fee(&data.chain_config().default_max_fee, msg, msg_spec) } /// Caps the gas fee to ensure it doesn't exceed the maximum allowed fee. /// Returns an error if the msg `gas_limit` is zero or the resulting fee cap does not fit the message encoding. pub(crate) fn cap_gas_fee( default_max_fee: &TokenAmount, msg: Message, msg_spec: Option, ) -> Result { let gas_limit = msg.gas_limit(); anyhow::ensure!(gas_limit > 0, "gas limit must be positive for fee capping"); let (maximize_fee_cap, max_fee) = match &msg_spec { Some(spec) => ( spec.maximize_fee_cap, if spec.max_fee.is_zero() { default_max_fee } else { &spec.max_fee }, ), None => (false, default_max_fee), }; let total_fee = msg.gas_fee_cap() * gas_limit; let msg = if !max_fee.is_zero() && (maximize_fee_cap || total_fee > *max_fee) { msg.into_builder() .gas_fee_cap(max_fee.div_floor(gas_limit)) .build() } else { msg }; anyhow::ensure!( msg.gas_fee_cap().atto().bits() <= MAX_BIGINT_BITS, "gas fee cap exceeds {MAX_BIGINT_BITS} bits" ); // cap premium at FeeCap if msg.gas_premium() <= msg.gas_fee_cap() { return Ok(msg); } let gas_premium = msg.gas_fee_cap().clone(); Ok(msg.into_builder().gas_premium(gas_premium).build()) } #[cfg(test)] mod tests { use super::*; use crate::shim::econ::TokenAmount; use crate::utils; #[test] fn test_compute_gas_premium_single_entry() { // Test with single entry at full block gas target let prices = vec![GasMeta { price: TokenAmount::from_atto(5), limit: BLOCK_GAS_TARGET, }]; let result = compute_gas_premium(prices, 1); assert_eq!(result, TokenAmount::from_atto(5)); } #[test] fn test_compute_gas_premium_two_entries() { // Test with two entries, each at full block gas target // Function will sort by price descending: [10, 5] // With 1 block: at = BLOCK_GAS_TARGET/2 + BLOCK_GAS_TARGET/40 = 2.625B gas // First entry (10): limit = 5B > 2.625B, so we stop immediately and return first price let prices = vec![ GasMeta { price: TokenAmount::from_atto(5), limit: BLOCK_GAS_TARGET, }, GasMeta { price: TokenAmount::from_atto(10), limit: BLOCK_GAS_TARGET, }, ]; let result = compute_gas_premium(prices, 1); assert_eq!(result, TokenAmount::from_atto(10)); } #[test] fn test_compute_gas_premium_half_block_entries_single_block() { // Test with entries at half-block gas target, single block // Function will sort by price descending: [20, 10] let prices = vec![ GasMeta { price: TokenAmount::from_atto(10), limit: BLOCK_GAS_TARGET / 2, }, GasMeta { price: TokenAmount::from_atto(20), limit: BLOCK_GAS_TARGET / 2, }, ]; let result = compute_gas_premium(prices, 1); assert_eq!(result, TokenAmount::from_atto(15)); } #[test] fn test_compute_gas_premium_three_entries_two_blocks() { // Test with three entries at a half-block gas target, two blocks // Function will sort by price descending: [30, 20, 10] // With 2 blocks: at = BLOCK_GAS_TARGET + BLOCK_GAS_TARGET/20 = 5.25B gas // First entry (30): at = 5.25B - 2.5B = 2.75B remaining // Second entry (20): at = 2.75B - 2.5B = 0.25B remaining // Third entry (10): limit = 2.5B > 0.25B, so we stop and average second and third let prices = vec![ GasMeta { price: TokenAmount::from_atto(10), limit: BLOCK_GAS_TARGET / 2, }, GasMeta { price: TokenAmount::from_atto(20), limit: BLOCK_GAS_TARGET / 2, }, GasMeta { price: TokenAmount::from_atto(30), limit: BLOCK_GAS_TARGET / 2, }, ]; let result = compute_gas_premium(prices, 2); let expected = (TokenAmount::from_atto(20) + TokenAmount::from_atto(10)).div_floor(2); assert_eq!(result, expected); } #[test] fn test_compute_gas_premium_empty_list() { // Test with empty price list let prices = vec![]; let result = compute_gas_premium(prices, 1); assert_eq!(result, TokenAmount::zero()); } #[test] fn test_compute_gas_premium_large_gas_limits() { // Test with entries that have gas limits larger than the threshold // Function will sort by price descending: [100, 50] let prices = vec![ GasMeta { price: TokenAmount::from_atto(100), limit: BLOCK_GAS_TARGET * 2, // Exceeds threshold immediately }, GasMeta { price: TokenAmount::from_atto(50), limit: BLOCK_GAS_TARGET / 4, }, ]; let result = compute_gas_premium(prices, 1); assert_eq!(result, TokenAmount::from_atto(100)); } #[test] fn test_compute_gas_premium_unsorted_input() { // Test that function correctly handles unsorted input (sorting is done internally) // Input order: [10, 30, 20] -> After internal sorting: [30, 20, 10] let prices = vec![ GasMeta { price: TokenAmount::from_atto(10), limit: BLOCK_GAS_TARGET / 4, }, GasMeta { price: TokenAmount::from_atto(30), limit: BLOCK_GAS_TARGET / 4, }, GasMeta { price: TokenAmount::from_atto(20), limit: BLOCK_GAS_TARGET / 4, }, ]; let result = compute_gas_premium(prices, 1); let expected = (TokenAmount::from_atto(20) + TokenAmount::from_atto(10)).div_floor(2); assert_eq!(result, expected); } #[test] fn test_compute_gas_premium_multiple_blocks() { // Test with multiple blocks affecting the threshold calculation // Function will sort by price descending: [40, 30, 20, 10] let prices = vec![ GasMeta { price: TokenAmount::from_atto(40), limit: BLOCK_GAS_TARGET / 4, }, GasMeta { price: TokenAmount::from_atto(30), limit: BLOCK_GAS_TARGET / 4, }, GasMeta { price: TokenAmount::from_atto(20), limit: BLOCK_GAS_TARGET / 4, }, GasMeta { price: TokenAmount::from_atto(10), limit: BLOCK_GAS_TARGET / 4, }, ]; // With 3 blocks, threshold is higher, so we should get a different result let result_1_block = compute_gas_premium(prices.clone(), 1); let result_3_blocks = compute_gas_premium(prices, 3); // With more blocks, the threshold is higher, so we should pick a lower price assert!(result_3_blocks <= result_1_block); } // Helper function to create a test message with gas parameters fn create_test_message(gas_limit: u64, gas_fee_cap: u64, gas_premium: u64) -> Message { Message::builder() .from(Address::new_id(1000)) .to(Address::new_id(1001)) .gas_limit(gas_limit) .gas_fee_cap(TokenAmount::from_atto(gas_fee_cap)) .gas_premium(TokenAmount::from_atto(gas_premium)) .build() } #[test] fn test_cap_gas_fee_within_limit() { // Normal case: total fee is within default max fee let default_max_fee = TokenAmount::from_atto(1_000_000); let msg = create_test_message(1000, 500, 100); let msg = cap_gas_fee(&default_max_fee, msg, None).unwrap(); assert_eq!(msg.gas_fee_cap(), &TokenAmount::from_atto(500)); assert_eq!(msg.gas_premium(), &TokenAmount::from_atto(100)); } #[test] fn test_cap_gas_fee_exceeds_limit() { // Fee exceeds max: should cap gas_fee_cap let default_max_fee = TokenAmount::from_atto(500_000); let msg = create_test_message(1000, 1000, 200); let msg = cap_gas_fee(&default_max_fee, msg, None).unwrap(); assert_eq!(msg.gas_fee_cap(), &TokenAmount::from_atto(500)); assert_eq!(msg.gas_premium(), &TokenAmount::from_atto(200)); } #[test] fn test_cap_gas_fee_premium_exceeds_fee_cap() { // Premium exceeds fee cap after capping: premium should be capped too let default_max_fee = TokenAmount::from_atto(300_000); let msg = create_test_message(1000, 1000, 800); let msg = cap_gas_fee(&default_max_fee, msg, None).unwrap(); assert_eq!(msg.gas_fee_cap(), &TokenAmount::from_atto(300)); assert_eq!(msg.gas_premium(), &TokenAmount::from_atto(300)); } #[test] fn test_cap_gas_fee_maximize_flag() { // maximize_fee_cap flag: should set gas_fee_cap to max even if within limit let default_max_fee = TokenAmount::from_atto(1_000_000); let msg = create_test_message(1000, 500, 100); let spec = MessageSendSpec { max_fee: TokenAmount::zero(), msg_uuid: utils::rand::new_uuid_v4(), maximize_fee_cap: true, }; let msg = cap_gas_fee(&default_max_fee, msg, Some(spec)).unwrap(); assert_eq!(msg.gas_fee_cap(), &TokenAmount::from_atto(1000)); assert_eq!(msg.gas_premium(), &TokenAmount::from_atto(100)); } #[test] fn test_cap_gas_fee_zero_gas_limit() { // Edge case: zero gas_limit should return an error let default_max_fee = TokenAmount::from_atto(1_000_000); let msg = create_test_message(0, 1000, 200); let result = cap_gas_fee(&default_max_fee, msg, None); assert!(result.is_err()); } fn max_encodable() -> BigInt { (BigInt::from(1) << MAX_BIGINT_BITS) - 1 } #[rstest::rstest] #[case::uncapped_widest(TokenAmount::zero(), 0, Some(max_encodable()))] #[case::uncapped_too_wide(TokenAmount::zero(), 1, None)] #[case::capped(TokenAmount::from_atto(1_000_000), 1, Some(BigInt::from(1000)))] fn test_cap_gas_fee_fee_cap_width( #[case] default_max_fee: TokenAmount, #[case] excess: u8, #[case] expected_fee_cap: Option, ) { let msg = Message::builder() .gas_limit(1000) .gas_fee_cap(TokenAmount::from_atto(max_encodable() + excess)) .gas_premium(TokenAmount::from_atto(max_encodable())) .build(); let result = cap_gas_fee(&default_max_fee, msg, None).ok(); assert_eq!( result.as_ref().map(|msg| msg.gas_fee_cap().atto().clone()), expected_fee_cap ); if let Some(msg) = result { assert_eq!(msg.gas_premium(), msg.gas_fee_cap()); msg.cid(); } } }