use crate::parameter::Parameter;
use crate::parameter_table::FeeComponent;
use enum_map::{EnumMap, enum_map};
use near_account_id::AccountType;
use near_primitives_core::account::{AccessKey, GasKeyInfo};
use near_primitives_core::errors::IntegerOverflowError;
use near_primitives_core::trie_key::access_key_key_len;
use near_primitives_core::types::{Balance, Compute, Gas, NonceIndex};
use near_schema_checker_lib::ProtocolSchema;
use num_rational::Rational32;

/// Costs associated with an object that can only be sent over the network (and executed
/// by the receiver).
/// NOTE: `send_sir` or `send_not_sir` fees are usually burned when the item is being created.
/// And `execution` fee is burned when the item is being executed.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct Fee {
    /// Fee for sending an object from the sender to itself, guaranteeing that it does not leave
    /// the shard.
    pub send_sir: FeeComponent,
    /// Fee for sending an object potentially across the shards.
    pub send_not_sir: FeeComponent,
    /// Fee for executing the object.
    pub execution: FeeComponent,
}

impl Fee {
    pub fn new(send_sir: u64, send_not_sir: u64, execution: u64) -> Self {
        Self {
            send_sir: FeeComponent::Gas(Gas::from_gas(send_sir)),
            send_not_sir: FeeComponent::Gas(Gas::from_gas(send_not_sir)),
            execution: FeeComponent::Gas(Gas::from_gas(execution)),
        }
    }

    #[inline]
    pub fn send_fee(&self, sir: bool) -> ParameterCost {
        if sir { self.send_sir.cost() } else { self.send_not_sir.cost() }
    }

    pub fn exec_fee(&self) -> ParameterCost {
        self.execution.cost()
    }

    /// The minimum gas fee to send and execute.
    pub fn min_send_and_exec_fee(&self) -> Gas {
        std::cmp::min(self.send_sir.gas(), self.send_not_sir.gas())
            .checked_add(self.execution.gas())
            .unwrap()
    }

    fn test_value(value: u64, factor: u64) -> Self {
        Self::test_value_detailed(value, value, value, factor)
    }

    fn test_value_detailed(
        send_sir_cost: u64,
        send_not_sir_cost: u64,
        execution_cost: u64,
        factor: u64,
    ) -> Self {
        Self {
            send_sir: FeeComponent::GasAndCompute {
                gas: Gas::from_gas(send_sir_cost),
                compute: send_sir_cost * factor,
            },
            send_not_sir: FeeComponent::GasAndCompute {
                gas: Gas::from_gas(send_not_sir_cost),
                compute: send_not_sir_cost * factor,
            },
            execution: FeeComponent::GasAndCompute {
                gas: Gas::from_gas(execution_cost),
                compute: execution_cost * factor,
            },
        }
    }
}
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub struct ParameterCost {
    pub gas: Gas,
    pub compute: Compute,
}

impl ParameterCost {
    pub const ZERO: ParameterCost = ParameterCost { gas: Gas::ZERO, compute: 0 };

    pub fn new(gas: Gas, compute: Compute) -> Self {
        Self { gas, compute }
    }

    pub fn checked_add(self, rhs: Self) -> Option<Self> {
        let gas = self.gas.checked_add(rhs.gas)?;
        let compute = self.compute.checked_add(rhs.compute)?;
        Some(Self { gas, compute })
    }

    pub fn checked_add_result(self, rhs: Self) -> Result<Self, IntegerOverflowError> {
        self.checked_add(rhs).ok_or(IntegerOverflowError)
    }

    pub fn checked_sub(self, rhs: Self) -> Option<Self> {
        let gas = self.gas.checked_sub(rhs.gas)?;
        let compute = self.compute.checked_sub(rhs.compute)?;
        Some(Self { gas, compute })
    }

    pub fn checked_mul(self, rhs: u64) -> Option<Self> {
        let gas = self.gas.checked_mul(rhs)?;
        let compute = self.compute.checked_mul(rhs)?;
        Some(Self { gas, compute })
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct ExtCostsConfig {
    pub costs: EnumMap<ExtCosts, ParameterCost>,
}

// We multiply the actual computed costs by the fixed factor to ensure we
// have certain reserve for further gas price variation.
const SAFETY_MULTIPLIER: u64 = 3;

impl ExtCostsConfig {
    pub fn gas_cost(&self, param: ExtCosts) -> Gas {
        self.costs[param].gas
    }

    pub fn compute_cost(&self, param: ExtCosts) -> Compute {
        self.costs[param].compute
    }

    /// Convenience constructor to use in tests where the exact gas cost does
    /// not need to correspond to a specific protocol version.
    pub fn test_with_undercharging_factor(factor: u64) -> ExtCostsConfig {
        let costs = enum_map! {
            ExtCosts::base => SAFETY_MULTIPLIER * 88256037,
            ExtCosts::contract_loading_base => SAFETY_MULTIPLIER * 11815321,
            ExtCosts::contract_loading_bytes => SAFETY_MULTIPLIER * 72250,
            ExtCosts::read_memory_base => SAFETY_MULTIPLIER * 869954400,
            ExtCosts::read_memory_byte => SAFETY_MULTIPLIER * 1267111,
            ExtCosts::write_memory_base => SAFETY_MULTIPLIER * 934598287,
            ExtCosts::write_memory_byte => SAFETY_MULTIPLIER * 907924,
            ExtCosts::read_register_base => SAFETY_MULTIPLIER * 839055062,
            ExtCosts::read_register_byte => SAFETY_MULTIPLIER * 32854,
            ExtCosts::write_register_base => SAFETY_MULTIPLIER * 955174162,
            ExtCosts::write_register_byte => SAFETY_MULTIPLIER * 1267188,
            ExtCosts::utf8_decoding_base => SAFETY_MULTIPLIER * 1037259687,
            ExtCosts::utf8_decoding_byte => SAFETY_MULTIPLIER * 97193493,
            ExtCosts::utf16_decoding_base => SAFETY_MULTIPLIER * 1181104350,
            ExtCosts::utf16_decoding_byte => SAFETY_MULTIPLIER * 54525831,
            ExtCosts::sha256_base => SAFETY_MULTIPLIER * 1513656750,
            ExtCosts::sha256_byte => SAFETY_MULTIPLIER * 8039117,
            ExtCosts::keccak256_base => SAFETY_MULTIPLIER * 1959830425,
            ExtCosts::keccak256_byte => SAFETY_MULTIPLIER * 7157035,
            ExtCosts::keccak512_base => SAFETY_MULTIPLIER * 1937129412,
            ExtCosts::keccak512_byte => SAFETY_MULTIPLIER * 12216567,
            ExtCosts::ripemd160_base => SAFETY_MULTIPLIER * 284558362,
            ExtCosts::ed25519_verify_base => SAFETY_MULTIPLIER * 1513656750,
            ExtCosts::ed25519_verify_byte => SAFETY_MULTIPLIER * 7157035,
            ExtCosts::ripemd160_block => SAFETY_MULTIPLIER * 226702528,
            ExtCosts::ecrecover_base => SAFETY_MULTIPLIER * 1121789875000,
            ExtCosts::p256_verify_base => SAFETY_MULTIPLIER * 433_333_333_333,
            ExtCosts::p256_verify_byte => SAFETY_MULTIPLIER * 4_333_333,
            ExtCosts::log_base => SAFETY_MULTIPLIER * 1181104350,
            ExtCosts::log_byte => SAFETY_MULTIPLIER * 4399597,
            ExtCosts::storage_write_base => SAFETY_MULTIPLIER * 21398912000,
            ExtCosts::storage_write_key_byte => SAFETY_MULTIPLIER * 23494289,
            ExtCosts::storage_write_value_byte => SAFETY_MULTIPLIER * 10339513,
            ExtCosts::storage_write_evicted_byte => SAFETY_MULTIPLIER * 10705769,
            ExtCosts::storage_read_base => SAFETY_MULTIPLIER * 18785615250,
            ExtCosts::storage_read_key_byte => SAFETY_MULTIPLIER * 10317511,
            ExtCosts::storage_read_value_byte => SAFETY_MULTIPLIER * 1870335,
            ExtCosts::storage_large_read_overhead_base => 0,
            ExtCosts::storage_large_read_overhead_byte => 0,
            ExtCosts::storage_remove_base => SAFETY_MULTIPLIER * 17824343500,
            ExtCosts::storage_remove_key_byte => SAFETY_MULTIPLIER * 12740128,
            ExtCosts::storage_remove_ret_value_byte => SAFETY_MULTIPLIER * 3843852,
            ExtCosts::storage_has_key_base => SAFETY_MULTIPLIER * 18013298875,
            ExtCosts::storage_has_key_byte => SAFETY_MULTIPLIER * 10263615,
            // Here it should be `SAFETY_MULTIPLIER * 0` for consistency, but then
            // clippy complains with "this operation will always return zero" warning
            ExtCosts::storage_iter_create_prefix_base => 0,
            ExtCosts::storage_iter_create_prefix_byte => 0,
            ExtCosts::storage_iter_create_range_base => 0,
            ExtCosts::storage_iter_create_from_byte => 0,
            ExtCosts::storage_iter_create_to_byte => 0,
            ExtCosts::storage_iter_next_base => 0,
            ExtCosts::storage_iter_next_key_byte => 0,
            ExtCosts::storage_iter_next_value_byte => 0,
            ExtCosts::touching_trie_node => SAFETY_MULTIPLIER * 5367318642,
            ExtCosts::read_cached_trie_node => SAFETY_MULTIPLIER * 760_000_000,
            ExtCosts::promise_and_base => SAFETY_MULTIPLIER * 488337800,
            ExtCosts::promise_and_per_promise => SAFETY_MULTIPLIER * 1817392,
            ExtCosts::promise_return => SAFETY_MULTIPLIER * 186717462,
            ExtCosts::validator_stake_base => SAFETY_MULTIPLIER * 303944908800,
            ExtCosts::validator_total_stake_base => SAFETY_MULTIPLIER * 303944908800,
            ExtCosts::alt_bn128_g1_multiexp_base => 713_000_000_000,
            ExtCosts::alt_bn128_g1_multiexp_element => 320_000_000_000,
            ExtCosts::alt_bn128_pairing_check_base => 9_686_000_000_000,
            ExtCosts::alt_bn128_pairing_check_element => 5_102_000_000_000,
            ExtCosts::alt_bn128_g1_sum_base => 3_000_000_000,
            ExtCosts::alt_bn128_g1_sum_element => 5_000_000_000,
            ExtCosts::bls12381_p1_sum_base => SAFETY_MULTIPLIER * 5_500_000_000,
            ExtCosts::bls12381_p1_sum_element => SAFETY_MULTIPLIER * 2_000_000_000,
            ExtCosts::bls12381_p2_sum_base => SAFETY_MULTIPLIER * 6_200_000_000,
            ExtCosts::bls12381_p2_sum_element => SAFETY_MULTIPLIER * 5_000_000_000,
            ExtCosts::bls12381_g1_multiexp_base => SAFETY_MULTIPLIER * 5_500_000_000,
            ExtCosts::bls12381_g1_multiexp_element => SAFETY_MULTIPLIER * 310_000_000_000,
            ExtCosts::bls12381_g2_multiexp_base => SAFETY_MULTIPLIER * 6_200_000_000,
            ExtCosts::bls12381_g2_multiexp_element => SAFETY_MULTIPLIER * 665_000_000_000,
            ExtCosts::bls12381_map_fp_to_g1_base => SAFETY_MULTIPLIER * 500_000_000,
            ExtCosts::bls12381_map_fp_to_g1_element => SAFETY_MULTIPLIER * 84_000_000_000,
            ExtCosts::bls12381_map_fp2_to_g2_base => SAFETY_MULTIPLIER * 500_000_000,
            ExtCosts::bls12381_map_fp2_to_g2_element => SAFETY_MULTIPLIER * 300_000_000_000,
            ExtCosts::bls12381_pairing_base => SAFETY_MULTIPLIER * 710_000_000_000,
            ExtCosts::bls12381_pairing_element => SAFETY_MULTIPLIER * 710_000_000_000,
            ExtCosts::bls12381_p1_decompress_base => SAFETY_MULTIPLIER * 500_000_000,
            ExtCosts::bls12381_p1_decompress_element => SAFETY_MULTIPLIER * 27_000_000_000,
            ExtCosts::bls12381_p2_decompress_base => SAFETY_MULTIPLIER * 500_000_000,
            ExtCosts::bls12381_p2_decompress_element => SAFETY_MULTIPLIER * 55_000_000_000,
            // TODO(yield/resume): replicate fees here after estimation
            ExtCosts::yield_create_base => 300_000_000_000_000,
            ExtCosts::yield_create_byte => 300_000_000_000_000,
            ExtCosts::yield_create_with_id_base => 300_000_000_000_000,
            ExtCosts::yield_resume_base => 300_000_000_000_000,
            ExtCosts::yield_resume_byte => 300_000_000_000_000,
        }
        .map(|_, value| ParameterCost { gas: Gas::from_gas(value), compute: value * factor });
        ExtCostsConfig { costs }
    }

    /// `test_with_undercharging_factor` with a factor of 1.
    pub fn test() -> ExtCostsConfig {
        Self::test_with_undercharging_factor(1)
    }
}

/// Strongly-typed representation of the fees for counting.
///
/// Do not change the enum discriminants here, they are used for borsh
/// (de-)serialization.
#[derive(
    Copy,
    Clone,
    Hash,
    PartialEq,
    Eq,
    Debug,
    PartialOrd,
    Ord,
    strum::Display,
    strum::EnumIter,
    enum_map::Enum,
    ProtocolSchema,
)]
#[allow(non_camel_case_types)]
pub enum ExtCosts {
    base = 0,
    contract_loading_base = 1,
    contract_loading_bytes = 2,
    read_memory_base = 3,
    read_memory_byte = 4,
    write_memory_base = 5,
    write_memory_byte = 6,
    read_register_base = 7,
    read_register_byte = 8,
    write_register_base = 9,
    write_register_byte = 10,
    utf8_decoding_base = 11,
    utf8_decoding_byte = 12,
    utf16_decoding_base = 13,
    utf16_decoding_byte = 14,
    sha256_base = 15,
    sha256_byte = 16,
    keccak256_base = 17,
    keccak256_byte = 18,
    keccak512_base = 19,
    keccak512_byte = 20,
    ripemd160_base = 21,
    ripemd160_block = 22,
    ecrecover_base = 23,
    log_base = 24,
    log_byte = 25,
    storage_write_base = 26,
    storage_write_key_byte = 27,
    storage_write_value_byte = 28,
    storage_write_evicted_byte = 29,
    storage_read_base = 30,
    storage_read_key_byte = 31,
    storage_read_value_byte = 32,
    storage_remove_base = 33,
    storage_remove_key_byte = 34,
    storage_remove_ret_value_byte = 35,
    storage_has_key_base = 36,
    storage_has_key_byte = 37,
    storage_iter_create_prefix_base = 38,
    storage_iter_create_prefix_byte = 39,
    storage_iter_create_range_base = 40,
    storage_iter_create_from_byte = 41,
    storage_iter_create_to_byte = 42,
    storage_iter_next_base = 43,
    storage_iter_next_key_byte = 44,
    storage_iter_next_value_byte = 45,
    touching_trie_node = 46,
    read_cached_trie_node = 47,
    promise_and_base = 48,
    promise_and_per_promise = 49,
    promise_return = 50,
    validator_stake_base = 51,
    validator_total_stake_base = 52,
    alt_bn128_g1_multiexp_base = 53,
    alt_bn128_g1_multiexp_element = 54,
    alt_bn128_pairing_check_base = 55,
    alt_bn128_pairing_check_element = 56,
    alt_bn128_g1_sum_base = 57,
    alt_bn128_g1_sum_element = 58,
    ed25519_verify_base = 59,
    ed25519_verify_byte = 60,
    yield_create_base = 61,
    yield_create_byte = 62,
    yield_resume_base = 63,
    yield_resume_byte = 64,
    bls12381_p1_sum_base = 65,
    bls12381_p1_sum_element = 66,
    bls12381_p2_sum_base = 67,
    bls12381_p2_sum_element = 68,
    bls12381_g1_multiexp_base = 69,
    bls12381_g1_multiexp_element = 70,
    bls12381_g2_multiexp_base = 71,
    bls12381_g2_multiexp_element = 72,
    bls12381_map_fp_to_g1_base = 73,
    bls12381_map_fp_to_g1_element = 74,
    bls12381_map_fp2_to_g2_base = 75,
    bls12381_map_fp2_to_g2_element = 76,
    bls12381_pairing_base = 77,
    bls12381_pairing_element = 78,
    bls12381_p1_decompress_base = 79,
    bls12381_p1_decompress_element = 80,
    bls12381_p2_decompress_base = 81,
    bls12381_p2_decompress_element = 82,
    storage_large_read_overhead_base = 83,
    storage_large_read_overhead_byte = 84,
    p256_verify_base = 85,
    p256_verify_byte = 86,
    yield_create_with_id_base = 87,
}

// Type of an action, used in fees logic.
#[derive(
    Copy,
    Clone,
    Hash,
    PartialEq,
    Eq,
    Debug,
    PartialOrd,
    Ord,
    strum::Display,
    strum::EnumIter,
    enum_map::Enum,
    ProtocolSchema,
)]
#[allow(non_camel_case_types)]
pub enum ActionCosts {
    create_account = 0,
    delete_account = 1,
    deploy_contract_base = 2,
    deploy_contract_byte = 3,
    function_call_base = 4,
    function_call_byte = 5,
    transfer = 6,
    stake = 7,
    add_full_access_key = 8,
    add_function_call_key_base = 9,
    add_function_call_key_byte = 10,
    delete_key = 11,
    new_action_receipt = 12,
    new_data_receipt_base = 13,
    new_data_receipt_byte = 14,
    delegate = 15,
    deploy_global_contract_base = 16,
    deploy_global_contract_byte = 17,
    use_global_contract_base = 18,
    use_global_contract_byte = 19,
    deterministic_state_init_base = 20,
    deterministic_state_init_byte = 21,
    deterministic_state_init_entry = 22,
    gas_key_transfer_base = 23,
    gas_key_byte = 24,
    gas_key_nonce_write_base = 25,
}

impl ExtCosts {
    pub fn gas(self, config: &ExtCostsConfig) -> Gas {
        config.gas_cost(self)
    }

    pub fn compute(self, config: &ExtCostsConfig) -> Compute {
        config.compute_cost(self)
    }

    pub fn param(&self) -> Parameter {
        match self {
            ExtCosts::base => Parameter::WasmBase,
            ExtCosts::contract_loading_base => Parameter::WasmContractLoadingBase,
            ExtCosts::contract_loading_bytes => Parameter::WasmContractLoadingBytes,
            ExtCosts::read_memory_base => Parameter::WasmReadMemoryBase,
            ExtCosts::read_memory_byte => Parameter::WasmReadMemoryByte,
            ExtCosts::write_memory_base => Parameter::WasmWriteMemoryBase,
            ExtCosts::write_memory_byte => Parameter::WasmWriteMemoryByte,
            ExtCosts::read_register_base => Parameter::WasmReadRegisterBase,
            ExtCosts::read_register_byte => Parameter::WasmReadRegisterByte,
            ExtCosts::write_register_base => Parameter::WasmWriteRegisterBase,
            ExtCosts::write_register_byte => Parameter::WasmWriteRegisterByte,
            ExtCosts::utf8_decoding_base => Parameter::WasmUtf8DecodingBase,
            ExtCosts::utf8_decoding_byte => Parameter::WasmUtf8DecodingByte,
            ExtCosts::utf16_decoding_base => Parameter::WasmUtf16DecodingBase,
            ExtCosts::utf16_decoding_byte => Parameter::WasmUtf16DecodingByte,
            ExtCosts::sha256_base => Parameter::WasmSha256Base,
            ExtCosts::sha256_byte => Parameter::WasmSha256Byte,
            ExtCosts::keccak256_base => Parameter::WasmKeccak256Base,
            ExtCosts::keccak256_byte => Parameter::WasmKeccak256Byte,
            ExtCosts::keccak512_base => Parameter::WasmKeccak512Base,
            ExtCosts::keccak512_byte => Parameter::WasmKeccak512Byte,
            ExtCosts::ripemd160_base => Parameter::WasmRipemd160Base,
            ExtCosts::ripemd160_block => Parameter::WasmRipemd160Block,
            ExtCosts::ecrecover_base => Parameter::WasmEcrecoverBase,
            ExtCosts::ed25519_verify_base => Parameter::WasmEd25519VerifyBase,
            ExtCosts::ed25519_verify_byte => Parameter::WasmEd25519VerifyByte,
            ExtCosts::p256_verify_base => Parameter::WasmP256VerifyBase,
            ExtCosts::p256_verify_byte => Parameter::WasmP256VerifyByte,
            ExtCosts::log_base => Parameter::WasmLogBase,
            ExtCosts::log_byte => Parameter::WasmLogByte,
            ExtCosts::storage_write_base => Parameter::WasmStorageWriteBase,
            ExtCosts::storage_write_key_byte => Parameter::WasmStorageWriteKeyByte,
            ExtCosts::storage_write_value_byte => Parameter::WasmStorageWriteValueByte,
            ExtCosts::storage_write_evicted_byte => Parameter::WasmStorageWriteEvictedByte,
            ExtCosts::storage_read_base => Parameter::WasmStorageReadBase,
            ExtCosts::storage_read_key_byte => Parameter::WasmStorageReadKeyByte,
            ExtCosts::storage_read_value_byte => Parameter::WasmStorageReadValueByte,
            ExtCosts::storage_large_read_overhead_base => {
                Parameter::WasmStorageLargeReadOverheadBase
            }
            ExtCosts::storage_large_read_overhead_byte => {
                Parameter::WasmStorageLargeReadOverheadByte
            }
            ExtCosts::storage_remove_base => Parameter::WasmStorageRemoveBase,
            ExtCosts::storage_remove_key_byte => Parameter::WasmStorageRemoveKeyByte,
            ExtCosts::storage_remove_ret_value_byte => Parameter::WasmStorageRemoveRetValueByte,
            ExtCosts::storage_has_key_base => Parameter::WasmStorageHasKeyBase,
            ExtCosts::storage_has_key_byte => Parameter::WasmStorageHasKeyByte,
            ExtCosts::storage_iter_create_prefix_base => Parameter::WasmStorageIterCreatePrefixBase,
            ExtCosts::storage_iter_create_prefix_byte => Parameter::WasmStorageIterCreatePrefixByte,
            ExtCosts::storage_iter_create_range_base => Parameter::WasmStorageIterCreateRangeBase,
            ExtCosts::storage_iter_create_from_byte => Parameter::WasmStorageIterCreateFromByte,
            ExtCosts::storage_iter_create_to_byte => Parameter::WasmStorageIterCreateToByte,
            ExtCosts::storage_iter_next_base => Parameter::WasmStorageIterNextBase,
            ExtCosts::storage_iter_next_key_byte => Parameter::WasmStorageIterNextKeyByte,
            ExtCosts::storage_iter_next_value_byte => Parameter::WasmStorageIterNextValueByte,
            ExtCosts::touching_trie_node => Parameter::WasmTouchingTrieNode,
            ExtCosts::read_cached_trie_node => Parameter::WasmReadCachedTrieNode,
            ExtCosts::promise_and_base => Parameter::WasmPromiseAndBase,
            ExtCosts::promise_and_per_promise => Parameter::WasmPromiseAndPerPromise,
            ExtCosts::promise_return => Parameter::WasmPromiseReturn,
            ExtCosts::validator_stake_base => Parameter::WasmValidatorStakeBase,
            ExtCosts::validator_total_stake_base => Parameter::WasmValidatorTotalStakeBase,
            ExtCosts::alt_bn128_g1_multiexp_base => Parameter::WasmAltBn128G1MultiexpBase,
            ExtCosts::alt_bn128_g1_multiexp_element => Parameter::WasmAltBn128G1MultiexpElement,
            ExtCosts::alt_bn128_pairing_check_base => Parameter::WasmAltBn128PairingCheckBase,
            ExtCosts::alt_bn128_pairing_check_element => Parameter::WasmAltBn128PairingCheckElement,
            ExtCosts::alt_bn128_g1_sum_base => Parameter::WasmAltBn128G1SumBase,
            ExtCosts::alt_bn128_g1_sum_element => Parameter::WasmAltBn128G1SumElement,
            ExtCosts::yield_create_base => Parameter::WasmYieldCreateBase,
            ExtCosts::yield_create_byte => Parameter::WasmYieldCreateByte,
            ExtCosts::yield_create_with_id_base => Parameter::WasmYieldCreateWithIdBase,
            ExtCosts::yield_resume_base => Parameter::WasmYieldResumeBase,
            ExtCosts::yield_resume_byte => Parameter::WasmYieldResumeByte,
            ExtCosts::bls12381_p1_sum_base => Parameter::WasmBls12381P1SumBase,
            ExtCosts::bls12381_p1_sum_element => Parameter::WasmBls12381P1SumElement,
            ExtCosts::bls12381_p2_sum_base => Parameter::WasmBls12381P2SumBase,
            ExtCosts::bls12381_p2_sum_element => Parameter::WasmBls12381P2SumElement,
            ExtCosts::bls12381_g1_multiexp_base => Parameter::WasmBls12381G1MultiexpBase,
            ExtCosts::bls12381_g1_multiexp_element => Parameter::WasmBls12381G1MultiexpElement,
            ExtCosts::bls12381_g2_multiexp_base => Parameter::WasmBls12381G2MultiexpBase,
            ExtCosts::bls12381_g2_multiexp_element => Parameter::WasmBls12381G2MultiexpElement,
            ExtCosts::bls12381_map_fp_to_g1_base => Parameter::WasmBls12381MapFpToG1Base,
            ExtCosts::bls12381_map_fp_to_g1_element => Parameter::WasmBls12381MapFpToG1Element,
            ExtCosts::bls12381_map_fp2_to_g2_base => Parameter::WasmBls12381MapFp2ToG2Base,
            ExtCosts::bls12381_map_fp2_to_g2_element => Parameter::WasmBls12381MapFp2ToG2Element,
            ExtCosts::bls12381_pairing_base => Parameter::WasmBls12381PairingBase,
            ExtCosts::bls12381_pairing_element => Parameter::WasmBls12381PairingElement,
            ExtCosts::bls12381_p1_decompress_base => Parameter::WasmBls12381P1DecompressBase,
            ExtCosts::bls12381_p1_decompress_element => Parameter::WasmBls12381P1DecompressElement,
            ExtCosts::bls12381_p2_decompress_base => Parameter::WasmBls12381P2DecompressBase,
            ExtCosts::bls12381_p2_decompress_element => Parameter::WasmBls12381P2DecompressElement,
        }
    }
}

/// Signature scheme of a transaction (or delegate-action) signer, used as the
/// key for per-scheme verification-cost lookups. Mirrors the schemes in
/// `near_crypto::KeyType`; kept here (rather than reusing `KeyType`) so that
/// `near-parameters` need not depend on `near-crypto`. Convert with the
/// `KeyType -> SignatureKind` match at the runtime call site.
///
/// To price a future scheme (more ML-DSA bits, hash-based schemes, ...): add
/// the `KeyType`, add a variant here, and add a `<scheme>_verification_cost`
/// runtime parameter; the compiler then forces wiring the new entry into the
/// cost map in `parameter_table.rs`.
#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug, enum_map::Enum)]
pub enum SignatureKind {
    Ed25519,
    Secp256k1,
    MlDsa65,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct RuntimeFeesConfig {
    /// Gas fees for sending and executing actions.
    pub action_fees: EnumMap<ActionCosts, Fee>,

    /// Describes fees for storage.
    pub storage_usage_config: StorageUsageConfig,

    /// Fraction of the burnt gas to reward to the contract account for execution.
    pub burnt_gas_reward: Rational32,

    /// Pessimistic gas price inflation ratio.
    pub pessimistic_gas_price_inflation_ratio: Rational32,

    /// Relative cost for gas refunds as a ratio of the refunded amount.
    ///
    /// The actual penalty is
    /// `max(gross_refund * gas_refund_penalty, min_gas_refund_penalty)`
    ///
    /// Added with [NEP-536](https://github.com/near/NEPs/pull/536)
    pub gas_refund_penalty: Rational32,
    /// Minimum cost for gas refunds.
    ///
    /// The actual penalty is
    /// `max(gross_refund * gas_refund_penalty, min_gas_refund_penalty)`
    ///
    /// Added with [NEP-536](https://github.com/near/NEPs/pull/536)
    pub min_gas_refund_penalty: Gas,

    /// Compute cost charged when applying a `GlobalContractDistribution`
    /// receipt on the receiver shard (covers precompilation overhead).
    pub deploy_global_contract_execution_base: Compute,
    /// Per-byte compute cost charged when applying a
    /// `GlobalContractDistribution` receipt, scaled by deployed code size.
    pub deploy_global_contract_execution_per_byte: Compute,

    /// Gas and compute cost charged at transaction conversion for each
    /// signature the transaction triggers verification of, keyed by signature
    /// scheme: the signer's own signature, plus each `Delegate` action's inner
    /// signer. This is the *extra* verification cost of a scheme relative to
    /// the classical schemes (whose verification is part of
    /// `action_receipt_creation`). ed25519/secp256k1 stay 0 for backwards
    /// compatibility; only ML-DSA-65 carries a charge. The signer pays it as
    /// burnt gas when buying the transaction; receipts created from within
    /// contracts are unaffected (no signing there). All 0 before
    /// `PostQuantumSignatures`.
    pub signature_verification_costs: EnumMap<SignatureKind, ParameterCost>,
}

/// Describes cost of storage per block
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct StorageUsageConfig {
    /// Amount of yN per byte required to have on the account. See
    /// <https://nomicon.io/Economics/Economics.html#state-stake> for details.
    pub storage_amount_per_byte: Balance,
    /// Number of bytes for an account record, including rounding up for account id.
    pub num_bytes_account: u64,
    /// Additional number of bytes for a k/v record
    pub num_extra_bytes_record: u64,
    /// Amount of yN burned per byte of deployed Global Contract code.
    pub global_contract_storage_amount_per_byte: Balance,
}

impl RuntimeFeesConfig {
    /// Access action fee by `ActionCosts`.
    pub fn fee(&self, cost: ActionCosts) -> &Fee {
        &self.action_fees[cost]
    }

    /// Convenience constructor to use in tests where the exact gas cost does
    /// not need to correspond to a specific protocol version.
    pub fn test_with_undercharging_factor(factor: u64) -> Self {
        // Once `ProtocolFeature::AccountCostIncrease` is enabled the test config has to keep the invariant
        // `min_gas_purchase_price * create_account.exec >= account_creation_charge` satisfied,
        // so the `create_account` fee is aligned with the real mainnet protocol values. With the
        // feature disabled we keep the historical `Fee::test_value(3_850_000_000_000)` so
        // pre-feature test expectations are unchanged.
        let create_account_fee =
            if near_primitives_core::version::ProtocolFeature::AccountCostIncrease
                .enabled(near_primitives_core::version::PROTOCOL_VERSION)
            {
                Fee::test_value_detailed(
                    500_000_000_000,
                    500_000_000_000,
                    7_200_000_000_000,
                    factor,
                )
            } else {
                Fee::test_value(3_850_000_000_000, factor)
            };
        Self {
            storage_usage_config: StorageUsageConfig::test(),
            burnt_gas_reward: Rational32::new(3, 10),
            pessimistic_gas_price_inflation_ratio: Rational32::new(103, 100),
            gas_refund_penalty: Rational32::new(5, 100),
            min_gas_refund_penalty: Gas::from_teragas(1),
            action_fees: enum_map::enum_map! {
                ActionCosts::create_account => create_account_fee.clone(),
                ActionCosts::delete_account => Fee::test_value(147489000000, factor),
                ActionCosts::deploy_contract_base => Fee::test_value(184765750000, factor),
                ActionCosts::deploy_contract_byte => Fee::test_value(6812999, factor),
                ActionCosts::function_call_base => Fee::test_value(2319861500000, factor),
                ActionCosts::function_call_byte => Fee::test_value(2235934, factor),
                ActionCosts::transfer => Fee::test_value(115123062500, factor),
                ActionCosts::stake => Fee::new(141715687500, 141715687500, 102217625000),
                ActionCosts::add_full_access_key => Fee::test_value(101765125000, factor),
                ActionCosts::add_function_call_key_base => Fee::test_value(102217625000, factor),
                ActionCosts::add_function_call_key_byte => Fee::test_value(1925331, factor),
                ActionCosts::delete_key => Fee::test_value(94946625000, factor),
                ActionCosts::new_action_receipt => Fee::test_value(108059500000, factor),
                ActionCosts::new_data_receipt_base => Fee::test_value(4697339419375, factor),
                ActionCosts::new_data_receipt_byte => Fee::test_value(59357464, factor),
                ActionCosts::delegate => Fee::test_value(200_000_000_000, factor),
                ActionCosts::deploy_global_contract_base => Fee::test_value(184_765_750_000, factor),
                ActionCosts::deploy_global_contract_byte => Fee::new(6_812_999, 6_812_999, 70_000_000),
                ActionCosts::use_global_contract_base => Fee::test_value(184_765_750_000, factor),
                ActionCosts::use_global_contract_byte => Fee::new(6_812_999, 47_683_715, 64_572_944),
                ActionCosts::deterministic_state_init_base => Fee::new(3_850_000_000_000, 3_850_000_000_000, 4_080_000_000_000),
                ActionCosts::deterministic_state_init_byte => Fee::new(72_000_000, 72_000_000, 70_000_000),
                ActionCosts::deterministic_state_init_entry => Fee::new(0, 0, 200_000_000_000),
                ActionCosts::gas_key_transfer_base => Fee::new(115_123_062_500, 115_123_062_500, 235_676_644_250),
                ActionCosts::gas_key_byte => Fee::new(59_357_464, 59_357_464, 101_435_400),
                ActionCosts::gas_key_nonce_write_base => Fee::new(0, 0, 64_196_736_000),
            },
            deploy_global_contract_execution_base: 0,
            deploy_global_contract_execution_per_byte: 0,
            signature_verification_costs: enum_map::enum_map! { _ => ParameterCost::ZERO },
        }
    }

    /// `test_with_undercharging_factor` with a factor of 1.
    pub fn test() -> RuntimeFeesConfig {
        Self::test_with_undercharging_factor(1)
    }

    pub fn free() -> Self {
        Self {
            action_fees: enum_map::enum_map! {
                _ => Fee::new(0, 0, 0)
            },
            storage_usage_config: StorageUsageConfig::free(),
            burnt_gas_reward: Rational32::from_integer(0),
            pessimistic_gas_price_inflation_ratio: Rational32::from_integer(0),
            gas_refund_penalty: Rational32::from_integer(0),
            min_gas_refund_penalty: Gas::ZERO,
            deploy_global_contract_execution_base: 0,
            deploy_global_contract_execution_per_byte: 0,
            signature_verification_costs: enum_map::enum_map! { _ => ParameterCost::ZERO },
        }
    }

    /// The minimum amount of gas required to create and execute a new receipt with a function call
    /// action.
    /// This amount is used to determine how many receipts can be created, send and executed for
    /// some amount of prepaid gas using function calls.
    pub fn min_receipt_with_function_call_gas(&self) -> Gas {
        self.fee(ActionCosts::new_action_receipt)
            .min_send_and_exec_fee()
            .checked_add(self.fee(ActionCosts::function_call_base).min_send_and_exec_fee())
            .unwrap()
    }

    /// Given a left over gas amount to be refunded, returns how much should be
    /// subtracted as a penalty introduced with NEP-536.
    ///
    /// Must return a value smaller or equal to the `gas_refund` parameter.
    pub fn gas_penalty_for_gas_refund(&self, gas_refund: Gas) -> Gas {
        let relative_cost = Gas::from_gas(
            (u128::from(gas_refund.as_gas()) * *self.gas_refund_penalty.numer() as u128
                / *self.gas_refund_penalty.denom() as u128)
                .try_into()
                .unwrap(),
        );

        let penalty = std::cmp::max(relative_cost, self.min_gas_refund_penalty);
        std::cmp::min(penalty, gas_refund)
    }
}

impl StorageUsageConfig {
    pub fn test() -> Self {
        Self {
            num_bytes_account: 100,
            num_extra_bytes_record: 40,
            storage_amount_per_byte: Balance::from_yoctonear(909 * 100_000_000_000_000_000),
            global_contract_storage_amount_per_byte: Balance::from_yoctonear(
                100_000_000_000_000_000_000,
            ),
        }
    }

    pub(crate) fn free() -> StorageUsageConfig {
        Self {
            num_bytes_account: 0,
            num_extra_bytes_record: 0,
            storage_amount_per_byte: Balance::ZERO,
            global_contract_storage_amount_per_byte: Balance::ZERO,
        }
    }
}

/// Helper functions for computing Transfer fees.
/// In case of implicit account creation they include extra fees for the CreateAccount and
/// AddFullAccessKey (for NEAR-implicit account only) actions that are implicit.
/// We can assume that no overflow will happen here.
pub fn transfer_exec_fee(
    cfg: &RuntimeFeesConfig,
    eth_implicit_accounts_enabled: bool,
    receiver_account_type: AccountType,
) -> ParameterCost {
    let transfer_fee = cfg.fee(ActionCosts::transfer).exec_fee();
    match (eth_implicit_accounts_enabled, receiver_account_type) {
        // Regular transfer to a named account.
        (_, AccountType::NamedAccount) => transfer_fee,
        // No account will be created, just a regular transfer.
        (false, AccountType::EthImplicitAccount) => transfer_fee,
        // Extra fee for the CreateAccount.
        (true, AccountType::EthImplicitAccount) => {
            transfer_fee.checked_add(cfg.fee(ActionCosts::create_account).exec_fee()).unwrap()
        }
        // Extra fees for the CreateAccount and AddFullAccessKey.
        (_, AccountType::NearImplicitAccount) => transfer_fee
            .checked_add(cfg.fee(ActionCosts::create_account).exec_fee())
            .unwrap()
            .checked_add(cfg.fee(ActionCosts::add_full_access_key).exec_fee())
            .unwrap(),
        // Extra fees for the implied CreateAccount action.
        (_, AccountType::NearDeterministicAccount) => {
            transfer_fee.checked_add(cfg.fee(ActionCosts::create_account).exec_fee()).unwrap()
        }
    }
}

pub fn transfer_send_fee(
    cfg: &RuntimeFeesConfig,
    sender_is_receiver: bool,
    eth_implicit_accounts_enabled: bool,
    receiver_account_type: AccountType,
) -> ParameterCost {
    let transfer_fee = cfg.fee(ActionCosts::transfer).send_fee(sender_is_receiver);
    match (eth_implicit_accounts_enabled, receiver_account_type) {
        // Regular transfer to a named account.
        (_, AccountType::NamedAccount) => transfer_fee,
        // No account will be created, just a regular transfer.
        (false, AccountType::EthImplicitAccount) => transfer_fee,
        // Extra fee for the CreateAccount.
        (true, AccountType::EthImplicitAccount) => transfer_fee
            .checked_add(cfg.fee(ActionCosts::create_account).send_fee(sender_is_receiver))
            .unwrap(),
        // Extra fees for the CreateAccount and AddFullAccessKey.
        (_, AccountType::NearImplicitAccount) => transfer_fee
            .checked_add(cfg.fee(ActionCosts::create_account).send_fee(sender_is_receiver))
            .unwrap()
            .checked_add(cfg.fee(ActionCosts::add_full_access_key).send_fee(sender_is_receiver))
            .unwrap(),
        // Extra fees for the implied  CreateAccount action.
        (_, AccountType::NearDeterministicAccount) => transfer_fee
            .checked_add(cfg.fee(ActionCosts::create_account).send_fee(sender_is_receiver))
            .unwrap(),
    }
}

/// Gas fee split into base and per-byte components, so callers can attribute
/// them to separate `ActionCosts` in the gas profile.
pub struct GasKeyTransferFee {
    pub base: ParameterCost,
    pub per_byte: ParameterCost,
}

impl GasKeyTransferFee {
    pub fn total(&self) -> ParameterCost {
        self.base.checked_add(self.per_byte).unwrap()
    }
}

/// Send fee for TransferToGasKey / WithdrawFromGasKey actions.
/// Based on the public key length (what the sender sees).
pub fn gas_key_transfer_send_fee(
    cfg: &RuntimeFeesConfig,
    sender_is_receiver: bool,
    public_key_len: usize,
) -> GasKeyTransferFee {
    let base = cfg.fee(ActionCosts::gas_key_transfer_base).send_fee(sender_is_receiver);
    let per_byte = cfg
        .fee(ActionCosts::gas_key_byte)
        .send_fee(sender_is_receiver)
        .checked_mul(public_key_len as u64)
        .unwrap();
    GasKeyTransferFee { base, per_byte }
}

/// Exec fee for TransferToGasKey / WithdrawFromGasKey actions.
/// Based on the access key trie key length + estimated value length (what the
/// receiver needs to read/write in the trie).
pub fn gas_key_transfer_exec_fee(
    cfg: &RuntimeFeesConfig,
    account_id_len: usize,
    public_key_len: usize,
) -> GasKeyTransferFee {
    let base = cfg.fee(ActionCosts::gas_key_transfer_base).exec_fee();
    let trie_key_len = access_key_key_len(account_id_len, public_key_len);
    let estimated_value_len = AccessKey::min_gas_key_borsh_len();
    let per_byte = cfg
        .fee(ActionCosts::gas_key_byte)
        .exec_fee()
        .checked_mul((trie_key_len + estimated_value_len) as u64)
        .unwrap();
    GasKeyTransferFee { base, per_byte }
}

/// Additional costs for adding an access key with GasKeyFunctionCall or
/// GasKeyFullAccess permissions, split into base (`gas_key_nonce_write_base`)
/// and per-byte (`gas_key_byte`) components.
pub struct GasKeyAddFee {
    pub base: ParameterCost,
    pub per_byte: ParameterCost,
}

impl GasKeyAddFee {
    pub fn total(&self) -> ParameterCost {
        self.base.checked_add(self.per_byte).unwrap()
    }
}

/// Additional send fee for gas_key_byte when adding a gas key (AddKey with
/// GasKeyFullAccess or GasKeyFunctionCall permission). Covers the serialized
/// GasKeyInfo bytes.
pub fn gas_key_add_key_send_fee(
    cfg: &RuntimeFeesConfig,
    sender_is_receiver: bool,
) -> ParameterCost {
    cfg.fee(ActionCosts::gas_key_byte)
        .send_fee(sender_is_receiver)
        .checked_mul(GasKeyInfo::borsh_len() as u64)
        .unwrap()
}

/// Exec fee when adding a gas key with `num_nonces` nonces, split into base
/// and per-byte components. Each nonce writes a trie entry of
/// (access_key_key_len + NonceIndex) key bytes and NONCE_VALUE_LEN value bytes.
pub fn gas_key_add_key_exec_fee(
    cfg: &RuntimeFeesConfig,
    account_id_len: usize,
    public_key_len: usize,
    num_nonces: NonceIndex,
) -> GasKeyAddFee {
    let num_nonces = num_nonces as u64;
    let base =
        cfg.fee(ActionCosts::gas_key_nonce_write_base).exec_fee().checked_mul(num_nonces).unwrap();
    let nonce_key_len =
        access_key_key_len(account_id_len, public_key_len) + std::mem::size_of::<NonceIndex>();
    let per_byte = cfg
        .fee(ActionCosts::gas_key_byte)
        .exec_fee()
        .checked_mul((nonce_key_len + AccessKey::NONCE_VALUE_LEN) as u64)
        .unwrap()
        .checked_mul(num_nonces)
        .unwrap();
    GasKeyAddFee { base, per_byte }
}
