Skip to content

Commit 03993a1

Browse files
authored
Merge branch 'paritytech:master' into master
2 parents 4255367 + a1f1cfc commit 03993a1

File tree

12 files changed

+300
-63
lines changed

12 files changed

+300
-63
lines changed

crates/anvil-polkadot/src/api_server/server.rs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,12 @@ use polkadot_sdk::{
6767
sp_api::{Metadata as _, ProvideRuntimeApi},
6868
sp_blockchain::Info,
6969
sp_core::{self, Hasher, keccak_256},
70-
sp_runtime::traits::BlakeTwo256,
70+
sp_runtime::{FixedU128, traits::BlakeTwo256},
7171
};
7272
use revm::primitives::hardfork::SpecId;
7373
use sqlx::sqlite::SqlitePoolOptions;
7474
use std::{collections::HashSet, sync::Arc, time::Duration};
75-
use substrate_runtime::Balance;
75+
use substrate_runtime::{Balance, constants::NATIVE_TO_ETH_RATIO};
7676
use subxt::{
7777
Metadata as SubxtMetadata, OnlineClient, backend::rpc::RpcClient,
7878
client::RuntimeVersion as SubxtRuntimeVersion, config::substrate::H256,
@@ -119,6 +119,7 @@ impl ApiServer {
119119
substrate_service.spawn_handle.clone(),
120120
)
121121
.await?;
122+
122123
Ok(Self {
123124
block_provider,
124125
req_receiver,
@@ -149,6 +150,17 @@ impl ApiServer {
149150
pub async fn execute(&mut self, req: EthRequest) -> ResponseResult {
150151
let res = match req.clone() {
151152
EthRequest::SetLogging(enabled) => self.set_logging(enabled).to_rpc_result(),
153+
//------- Gas -----------
154+
EthRequest::SetNextBlockBaseFeePerGas(base_fee) => {
155+
let latest_block = self.latest_block();
156+
// We inject in substrate storage an 1e18 denominated value after transforming it
157+
// to a 1e12.
158+
self.backend.inject_next_fee_multiplier(
159+
latest_block,
160+
FixedU128::from_rational(base_fee.to::<u128>(), NATIVE_TO_ETH_RATIO.into()),
161+
);
162+
Ok(()).to_rpc_result()
163+
}
152164

153165
//------- Mining---------
154166
EthRequest::Mine(blocks, interval) => self.mine(blocks, interval).await.to_rpc_result(),
@@ -727,9 +739,11 @@ impl ApiServer {
727739
if transaction.gas_price.is_none() {
728740
transaction.gas_price = Some(self.gas_price().await?);
729741
}
742+
730743
if transaction.nonce.is_none() {
731744
transaction.nonce = Some(self.get_transaction_count(from, latest_block_id).await?);
732745
}
746+
733747
if transaction.chain_id.is_none() {
734748
transaction.chain_id =
735749
Some(sp_core::U256::from_big_endian(&self.chain_id(latest_block).to_be_bytes()));

crates/anvil-polkadot/src/cmd.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,6 @@ impl NodeArgs {
109109
let anvil_config = AnvilNodeConfig::default()
110110
.with_gas_limit(self.evm.gas_limit)
111111
.disable_block_gas_limit(self.evm.disable_block_gas_limit)
112-
.with_gas_price(self.evm.gas_price)
113112
.with_blocktime(self.block_time)
114113
.with_no_mining(self.no_mining)
115114
.with_mixed_mining(self.mixed_mining, self.block_time)
@@ -198,10 +197,6 @@ pub struct AnvilEvmArgs {
198197
)]
199198
pub disable_code_size_limit: bool,
200199

201-
/// The gas price.
202-
#[arg(long, help_heading = "Environment config")]
203-
pub gas_price: Option<u128>,
204-
205200
/// The base fee in a block.
206201
#[arg(
207202
long,

crates/anvil-polkadot/src/config.rs

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,9 @@ pub const DEFAULT_MNEMONIC: &str = "test test test test test test test test test
4848
pub const DEFAULT_IPC_ENDPOINT: &str =
4949
if cfg!(unix) { "/tmp/anvil.ipc" } else { r"\\.\pipe\anvil.ipc" };
5050

51-
/// Initial base fee for EIP-1559 blocks.
52-
pub const INITIAL_BASE_FEE: u64 = 1_000_000_000;
53-
54-
/// Initial default gas price for the first block
55-
pub const INITIAL_GAS_PRICE: u128 = 1_875_000_000;
51+
/// In anvil this is `1_000_000_000`, in 1e18 denomination. However,
52+
/// asset-hub-westend runtime sets it to `1_000_000`.
53+
pub const INITIAL_BASE_FEE: u128 = 1_000_000;
5654

5755
const BANNER: &str = r"
5856
_ _
@@ -272,10 +270,8 @@ pub struct AnvilNodeConfig {
272270
pub gas_limit: Option<u128>,
273271
/// If set to `true`, disables the block gas limit
274272
pub disable_block_gas_limit: bool,
275-
/// Default gas price for all txs
276-
pub gas_price: Option<u128>,
277273
/// Default base fee
278-
pub base_fee: Option<u64>,
274+
pub base_fee: Option<u128>,
279275
/// If set to `true`, disables the enforcement of a minimum suggested priority fee
280276
pub disable_min_priority_fee: bool,
281277
/// Signer accounts that will be initialised with `genesis_balance` in the genesis block
@@ -482,7 +478,6 @@ Genesis Number
482478
"private_keys": private_keys,
483479
"wallet": wallet_description,
484480
"base_fee": format!("{}", self.get_base_fee()),
485-
"gas_price": format!("{}", self.get_gas_price()),
486481
"gas_limit": gas_limit,
487482
"genesis_timestamp": format!("{}", self.get_genesis_timestamp()),
488483
})
@@ -521,7 +516,6 @@ impl Default for AnvilNodeConfig {
521516
chain_id: None,
522517
gas_limit: None,
523518
disable_block_gas_limit: false,
524-
gas_price: None,
525519
signer_accounts: genesis_accounts.clone(),
526520
genesis_timestamp: None,
527521
genesis_block_number: None,
@@ -562,18 +556,19 @@ impl AnvilNodeConfig {
562556
self.memory_limit = mems_value;
563557
self
564558
}
559+
565560
/// Returns the base fee to use
566-
pub fn get_base_fee(&self) -> u64 {
561+
pub fn get_base_fee(&self) -> u128 {
567562
self.base_fee
568-
.or_else(|| self.genesis.as_ref().and_then(|g| g.base_fee_per_gas.map(|g| g as u64)))
563+
.or_else(|| {
564+
self.genesis.as_ref().and_then(|g| {
565+
// The base fee received via CLI will be transformed to 1e-12.
566+
g.base_fee_per_gas
567+
})
568+
})
569569
.unwrap_or(INITIAL_BASE_FEE)
570570
}
571571

572-
/// Returns the base fee to use
573-
pub fn get_gas_price(&self) -> u128 {
574-
self.gas_price.unwrap_or(INITIAL_GAS_PRICE)
575-
}
576-
577572
/// Sets a custom code size limit
578573
#[must_use]
579574
pub fn with_code_size_limit(mut self, code_size_limit: Option<usize>) -> Self {
@@ -624,17 +619,10 @@ impl AnvilNodeConfig {
624619
self
625620
}
626621

627-
/// Sets the gas price
628-
#[must_use]
629-
pub fn with_gas_price(mut self, gas_price: Option<u128>) -> Self {
630-
self.gas_price = gas_price;
631-
self
632-
}
633-
634622
/// Sets the base fee
635623
#[must_use]
636624
pub fn with_base_fee(mut self, base_fee: Option<u64>) -> Self {
637-
self.base_fee = base_fee;
625+
self.base_fee = base_fee.map(|bf| bf.into());
638626
self
639627
}
640628

crates/anvil-polkadot/src/substrate_node/genesis.rs

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,14 @@ use polkadot_sdk::{
1515
sp_blockchain,
1616
sp_core::{self, H160, storage::Storage},
1717
sp_runtime::{
18-
BuildStorage,
18+
BuildStorage, FixedU128,
1919
traits::{Block as BlockT, Hash as HashT, HashingFor, Header as HeaderT},
2020
},
2121
};
2222
use serde::{Deserialize, Serialize};
2323
use serde_json::{Value, json};
2424
use std::{collections::BTreeMap, marker::PhantomData, sync::Arc};
25-
use substrate_runtime::WASM_BINARY;
25+
use substrate_runtime::{WASM_BINARY, constants::NATIVE_TO_ETH_RATIO};
2626
use subxt_signer::eth::Keypair;
2727

2828
/// Genesis settings
@@ -38,7 +38,7 @@ pub struct GenesisConfig {
3838
/// The initial number for the genesis block
3939
pub number: u32,
4040
/// The genesis header base fee
41-
pub base_fee_per_gas: u64,
41+
pub base_fee_per_gas: FixedU128,
4242
/// The genesis header gas limit.
4343
pub gas_limit: Option<u128>,
4444
/// Signer accounts from account_generator
@@ -65,7 +65,10 @@ impl<'a> From<&'a AnvilNodeConfig> for GenesisConfig {
6565
.get_genesis_number()
6666
.try_into()
6767
.expect("Genesis block number overflow"),
68-
base_fee_per_gas: anvil_config.get_base_fee(),
68+
base_fee_per_gas: FixedU128::from_rational(
69+
anvil_config.get_base_fee(),
70+
NATIVE_TO_ETH_RATIO.into(),
71+
),
6972
gas_limit: anvil_config.gas_limit,
7073
genesis_accounts: anvil_config.genesis_accounts.clone(),
7174
genesis_balance: anvil_config.genesis_balance,
@@ -155,6 +158,9 @@ impl GenesisConfig {
155158
"revive": {
156159
"accounts": revive_genesis_accounts,
157160
},
161+
"transactionPayment": {
162+
"multiplier": self.base_fee_per_gas.into_inner().to_string(),
163+
}
158164
})
159165
}
160166
}
@@ -265,11 +271,13 @@ mod tests {
265271
let timestamp: u64 = 10;
266272
let chain_id: u64 = 42;
267273
let authority_id: [u8; 32] = [0xEE; 32];
274+
let base_fee_per_gas = FixedU128::from_rational(6_000_000, NATIVE_TO_ETH_RATIO.into());
268275
let genesis_config = GenesisConfig {
269276
number: block_number,
270277
timestamp,
271278
chain_id,
272279
coinbase: Some(Address::from([0xEE; 20])),
280+
base_fee_per_gas,
273281
..Default::default()
274282
};
275283
let genesis_storage = genesis_config.as_storage_key_value();

crates/anvil-polkadot/src/substrate_node/service/backend.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use polkadot_sdk::{
1313
sp_blockchain,
1414
sp_core::{H160, H256},
1515
sp_io::hashing::blake2_256,
16+
sp_runtime::FixedU128,
1617
sp_state_machine::{StorageKey, StorageValue},
1718
};
1819
use std::{collections::HashMap, num::NonZeroUsize, sync::Arc};
@@ -30,6 +31,8 @@ pub enum BackendError {
3031
MissingAuraAuthorities,
3132
#[error("Could not find timestamp in the state")]
3233
MissingTimestamp,
34+
#[error("Could not find the next fee multiplier in the state")]
35+
MissingNextFeeMultiplier,
3336
#[error("Could not find block number in the state")]
3437
MissingBlockNumber,
3538
#[error("Unable to decode total issuance {0}")]
@@ -50,6 +53,8 @@ pub enum BackendError {
5053
DecodeBlockNumber(codec::Error),
5154
#[error("Unable to decode aura authorities: {0}")]
5255
DecodeAuraAuthorities(codec::Error),
56+
#[error("Unable to decode the next fee multiplier: {0}")]
57+
DecodeNextFeeMultiplier(codec::Error),
5358
}
5459

5560
type Result<T> = std::result::Result<T, BackendError>;
@@ -175,6 +180,11 @@ impl BackendWithOverlay {
175180
overrides.set_coinbase(at, aura_authority);
176181
}
177182

183+
pub fn inject_next_fee_multiplier(&self, at: Hash, next_fee_multiplier: FixedU128) {
184+
let mut overrides = self.overrides.lock();
185+
overrides.set_next_fee_multiplier(at, next_fee_multiplier);
186+
}
187+
178188
pub fn inject_total_issuance(&self, at: Hash, value: Balance) {
179189
let mut overrides = self.overrides.lock();
180190
overrides.set_total_issuance(at, value);
@@ -274,6 +284,16 @@ impl StorageOverrides {
274284
self.add(latest_block, changeset);
275285
}
276286

287+
fn set_next_fee_multiplier(&mut self, latest_block: Hash, next_fee_multiplier: FixedU128) {
288+
let mut changeset = BlockOverrides::default();
289+
changeset.top.insert(
290+
well_known_keys::NEXT_FEE_MULTIPLIER.to_vec(),
291+
Some(next_fee_multiplier.encode()),
292+
);
293+
294+
self.add(latest_block, changeset);
295+
}
296+
277297
fn set_system_account_info(
278298
&mut self,
279299
latest_block: Hash,

crates/anvil-polkadot/src/substrate_node/service/storage.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ pub mod well_known_keys {
4848
154, 166, 12, 2, 190, 154, 220, 201, 138, 13, 29,
4949
];
5050

51+
//twox_128(b"TransactionPayment" + b"NextFeeMultiplier")
52+
pub const NEXT_FEE_MULTIPLIER: [u8; 32] = [
53+
63, 20, 103, 160, 150, 188, 215, 26, 91, 106, 12, 129, 85, 226, 8, 16, 63, 46, 223, 59,
54+
223, 56, 29, 235, 227, 49, 171, 116, 70, 173, 223, 220,
55+
];
56+
5157
pub fn system_account_info(account_id: AccountId) -> Vec<u8> {
5258
let mut key = Vec::new();
5359
key.extend_from_slice(&twox_128("System".as_bytes()));

crates/anvil-polkadot/substrate-runtime/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ polkadot-sdk = { git = "https://github.com/paritytech/polkadot-sdk.git", branch
2121
"pallet-transaction-payment",
2222
"pallet-transaction-payment-rpc-runtime-api",
2323
"parachains-common",
24+
"polkadot-runtime-common",
2425
"runtime",
2526
"sp-consensus-aura",
2627
"with-tracing",

crates/anvil-polkadot/substrate-runtime/src/lib.rs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,12 +22,13 @@ use pallet_revive::{
2222
runtime::EthExtra,
2323
},
2424
};
25-
use pallet_transaction_payment::{ConstFeeMultiplier, FeeDetails, Multiplier, RuntimeDispatchInfo};
25+
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
2626
use polkadot_sdk::{
2727
parachains_common::{
2828
AccountId, AssetHubPolkadotAuraId as AuraId, BlockNumber, Hash as CommonHash, Header,
2929
Nonce, Signature,
3030
},
31+
polkadot_runtime_common::SlowAdjustingFeeUpdate,
3132
polkadot_sdk_frame::{
3233
deps::sp_genesis_builder,
3334
runtime::{apis, prelude::*},
@@ -41,6 +42,11 @@ use polkadot_sdk::{
4142
pub use polkadot_sdk::parachains_common::Balance;
4243
use sp_weights::ConstantMultiplier;
4344

45+
pub mod constants {
46+
/// DOT precision (1e12) to ETH precision (1e18) ratio.
47+
pub const NATIVE_TO_ETH_RATIO: u32 = 1_000_000;
48+
}
49+
4450
pub mod currency {
4551
use super::Balance;
4652
pub const DOLLARS: Balance = 1_000_000_000_000;
@@ -257,17 +263,27 @@ impl pallet_sudo::Config for Runtime {}
257263
impl pallet_timestamp::Config for Runtime {}
258264

259265
parameter_types! {
260-
pub const TransactionByteFee: Balance = 10 * MILLICENTS;
261-
pub FeeMultiplier: Multiplier = Multiplier::one();
266+
// That's how asset-hub-westend sets this.
267+
pub const TransactionByteFee: Balance = MILLICENTS;
262268
}
263269

270+
// That's how asset-hub-westend sets this.
271+
pub type WeightToFee = BlockRatioFee<
272+
// p
273+
CENTS,
274+
// q
275+
{ 100 * ExtrinsicBaseWeight::get().ref_time() as u128 },
276+
Runtime,
277+
>;
278+
264279
// Implements the types required for the transaction payment pallet.
265280
#[derive_impl(pallet_transaction_payment::config_preludes::TestDefaultConfig)]
266281
impl pallet_transaction_payment::Config for Runtime {
267282
type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
268-
type WeightToFee = BlockRatioFee<1, 1, Self>;
283+
type WeightToFee = WeightToFee;
269284
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
270-
type FeeMultiplierUpdate = ConstFeeMultiplier<FeeMultiplier>;
285+
// That's how asset-hub-westend sets this.
286+
type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
271287
}
272288

273289
parameter_types! {
@@ -299,7 +315,7 @@ impl pallet_revive::Config for Runtime {
299315
// `forking` feature.
300316
type FindAuthor = BlockAuthor;
301317
type Balance = Balance;
302-
type NativeToEthRatio = ConstU32<1_000_000>;
318+
type NativeToEthRatio = ConstU32<{ constants::NATIVE_TO_ETH_RATIO }>;
303319
type UploadOrigin = EnsureSigned<Self::AccountId>;
304320
type InstantiateOrigin = EnsureSigned<Self::AccountId>;
305321
type Time = Timestamp;

0 commit comments

Comments
 (0)