difftreelog
fix evm fees burn & test (#1079)
in: master
* fix evm fees burn & test * fix tips handling
3 files changed
js-packages/tests/creditFeesToTreasury.seqtest.tsdiffbeforeafterboth--- a/js-packages/tests/creditFeesToTreasury.seqtest.ts
+++ b/js-packages/tests/creditFeesToTreasury.seqtest.ts
@@ -18,6 +18,8 @@
import {ApiPromise} from '@polkadot/api';
import {usingPlaygrounds, expect, itSub} from '@unique/test-utils/util.js';
import type {u32} from '@polkadot/types-codec';
+import { itEth } from '@unique/test-utils/eth/util.js';
+import { ITransactionResult } from '@unique-nft/playgrounds/types';
const TREASURY = '5EYCAe5ijiYfyeZ2JJCGq56LmPyNRAKzpG4QkoQkkQNB5e6Z';
const saneMinimumFee = 0.05;
@@ -163,4 +165,36 @@
expect(Math.abs(fee - expectedTransferFee)).to.be.lessThan(tolerance);
});
+
+ itEth('Evm Transactions send fees to Treasury', async ({helper}) => {
+ const value = helper.balance.getOneTokenNominal();
+ const gasPrice = await helper.getWeb3().eth.getGasPrice();
+ let result = null;
+
+ const lambda = async () => {
+ result = await helper.executeExtrinsic(alice, 'api.tx.evm.call', [
+ helper.address.substrateToEth(alice.address),
+ helper.address.substrateToEth(bob.address),
+ '0x',
+ value,
+ 25_000,
+ gasPrice,
+ null,
+ null,
+ [],
+ ]);
+ };
+
+ const totalPaid = await helper.arrange.calculcateFee({ Substrate: alice.address }, lambda);
+ const evmFees = totalPaid - value;
+
+ const treasuryDepoosited = (result as unknown as ITransactionResult).result.events
+ .filter(({ event: { method, section } }) => section == 'treasury' && method == 'Deposit')
+ .map(({ event: { data } }) => data[0].toJSON());
+
+ const deposit = BigInt(treasuryDepoosited[0]);
+
+ expect(deposit).to.be.equal(evmFees);
+ });
+
});
pallets/evm-transaction-payment/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-transaction-payment/src/lib.rs
+++ b/pallets/evm-transaction-payment/src/lib.rs
@@ -287,8 +287,7 @@
}
fn pay_priority_fee(tip: Self::LiquidityInfo) {
- <pallet_evm::EVMCurrencyAdapter<C, OU> as OnChargeEVMTransaction<T>>::pay_priority_fee(
- tip.0,
- )
+ let Some(imbalance) = tip.0 else { return };
+ OU::on_unbalanced(imbalance)
}
}
runtime/common/mod.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617pub mod config;18pub mod construct_runtime;19pub mod dispatch;20pub mod ethereum;21pub mod identity;22pub mod instance;23pub mod maintenance;24pub mod runtime_apis;2526pub mod sponsoring;27#[allow(missing_docs)]28pub mod weights;2930#[cfg(test)]31pub mod tests;3233use frame_support::{34 traits::{Currency, Imbalance, OnUnbalanced},35 weights::Weight,36};37use sp_runtime::{38 generic, impl_opaque_keys,39 traits::{BlakeTwo256, BlockNumberProvider},40};41use sp_std::vec::Vec;42#[cfg(feature = "std")]43use sp_version::NativeVersion;44use up_common::types::{AccountId, BlockNumber};4546use crate::{AllPalletsWithSystem, Aura, Balances, Runtime, RuntimeCall, Signature, Treasury};4748#[macro_export]49macro_rules! unsupported {50 () => {51 pallet_common::unsupported!($crate::Runtime)52 };53}5455/// The address format for describing accounts.56pub type Address = sp_runtime::MultiAddress<AccountId, ()>;57/// A Block signed with a Justification58pub type SignedBlock = generic::SignedBlock<Block>;59/// Frontier wrapped extrinsic60pub type UncheckedExtrinsic =61 fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;62/// Header type.63pub type Header = generic::Header<BlockNumber, BlakeTwo256>;64/// Block type.65pub type Block = generic::Block<Header, UncheckedExtrinsic>;66/// BlockId type as expected by this runtime.67pub type BlockId = generic::BlockId<Block>;6869impl_opaque_keys! {70 pub struct SessionKeys {71 pub aura: Aura,72 }73}7475/// The version information used to identify this runtime when compiled natively.76#[cfg(feature = "std")]77pub fn native_version() -> NativeVersion {78 NativeVersion {79 runtime_version: crate::VERSION,80 can_author_with: Default::default(),81 }82}8384pub type SignedExtra = (85 frame_system::CheckSpecVersion<Runtime>,86 frame_system::CheckTxVersion<Runtime>,87 frame_system::CheckGenesis<Runtime>,88 frame_system::CheckEra<Runtime>,89 pallet_charge_transaction::CheckNonce<Runtime>,90 frame_system::CheckWeight<Runtime>,91 maintenance::CheckMaintenance,92 identity::DisableIdentityCalls,93 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,94 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,95 pallet_ethereum::FakeTransactionFinalizer<Runtime>,96);9798/// Executive: handles dispatch to the various modules.99pub type Executive = frame_executive::Executive<100 Runtime,101 Block,102 frame_system::ChainContext<Runtime>,103 Runtime,104 AllPalletsWithSystem,105 AuraToCollatorSelection,106>;107108type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;109110pub struct DealWithFees;111impl OnUnbalanced<NegativeImbalance> for DealWithFees {112 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {113 if let Some(fees) = fees_then_tips.next() {114 // for fees, 100% to treasury115 let mut split = fees.ration(100, 0);116 if let Some(tips) = fees_then_tips.next() {117 // for tips, if any, 100% to treasury118 tips.ration_merge_into(100, 0, &mut split);119 }120 Treasury::on_unbalanced(split.0);121 // Author::on_unbalanced(split.1);122 }123 }124}125126pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);127128impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider129 for RelayChainBlockNumberProvider<T>130{131 type BlockNumber = BlockNumber;132133 fn current_block_number() -> Self::BlockNumber {134 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()135 .map(|d| d.relay_parent_number)136 .unwrap_or_default()137 }138 #[cfg(feature = "runtime-benchmarks")]139 fn set_block_number(block: Self::BlockNumber) {140 cumulus_pallet_parachain_system::RelaychainDataProvider::<T>::set_block_number(block)141 }142}143144#[cfg(not(feature = "lookahead"))]145pub(crate) struct CheckInherents;146147#[cfg(not(feature = "lookahead"))]148impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {149 fn check_inherents(150 block: &Block,151 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,152 ) -> sp_inherents::CheckInherentsResult {153 use crate::InherentDataExt;154155 let relay_chain_slot = relay_state_proof156 .read_slot()157 .expect("Could not read the relay chain slot from the proof");158159 let inherent_data =160 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(161 relay_chain_slot,162 sp_std::time::Duration::from_secs(6),163 )164 .create_inherent_data()165 .expect("Could not create the timestamp inherent data");166167 inherent_data.check_extrinsics(block)168 }169}170171#[derive(parity_scale_codec::Encode, parity_scale_codec::Decode)]172pub enum XCMPMessage<XAccountId, XBalance> {173 /// Transfer tokens to the given account from the Parachain account.174 TransferToken(XAccountId, XBalance),175}176177pub struct AuraToCollatorSelection;178impl frame_support::traits::OnRuntimeUpgrade for AuraToCollatorSelection {179 fn on_runtime_upgrade() -> Weight {180 #[cfg(feature = "collator-selection")]181 {182 use frame_support::{storage::migration, BoundedVec};183 use pallet_session::SessionManager;184 use sp_runtime::{traits::OpaqueKeys, RuntimeAppPublic};185186 use crate::config::pallets::MaxCollators;187188 let mut weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);189190 let version = migration::get_storage_value::<()>(191 b"AuraToCollatorSelection",192 b"StorageVersion",193 &[],194 );195196 let should_upgrade = version.is_none();197198 if should_upgrade {199 log::info!(200 target: "runtime::aura_to_collator_selection",201 "Running migration of Aura authorities to Collator Selection invulnerables"202 );203204 let invulnerables = pallet_aura::Pallet::<Runtime>::authorities()205 .iter()206 .cloned()207 .filter_map(|authority_id| {208 weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));209 let vec = authority_id.to_raw_vec();210 let slice = vec.as_slice();211 let array: Option<[u8; 32]> = match slice.try_into() {212 Ok(a) => Some(a),213 Err(_) => {214 log::error!("Failed to convert an Aura authority to a Collator Selection invulnerable: {:?}", authority_id);215 None216 },217 };218 array.map(|a| (AccountId::from(a), authority_id))219 })220 .collect::<Vec<_>>();221222 let bounded_invulnerables = BoundedVec::<_, MaxCollators>::try_from(223 invulnerables224 .iter()225 .cloned()226 .map(|(acc, _)| acc)227 .collect::<Vec<_>>(),228 )229 .expect("Existing collators/invulnerables are more than MaxCollators");230231 <pallet_collator_selection::Invulnerables<Runtime>>::put(bounded_invulnerables);232233 let keys = invulnerables234 .into_iter()235 .map(|(acc, aura)| {236 (237 acc.clone(), // account id238 acc, // validator id239 SessionKeys { aura }, // session keys240 )241 })242 .collect::<Vec<_>>();243244 for (account, val, keys) in keys.iter() {245 for id in <Runtime as pallet_session::Config>::Keys::key_ids() {246 <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), val)247 }248 <pallet_session::NextKeys<Runtime>>::insert(val, keys);249 // todo exercise caution, the following is taken from genesis250 if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(account)251 .is_err()252 {253 log::warn!(254 "We have entered an error with incrementing consumers without limit during the migration"255 );256 // This will leak a provider reference, however it only happens once (at257 // genesis) so it's really not a big deal and we assume that the user wants to258 // do this since it's the only way a non-endowed account can contain a session259 // key.260 frame_system::Pallet::<Runtime>::inc_providers(account);261 }262 }263264 let initial_validators_0 =265 <Runtime as pallet_session::Config>::SessionManager::new_session(0)266 .unwrap_or_else(|| {267 frame_support::print(268 "No initial validator provided by `SessionManager`, use \269 session config keys to generate initial validator set.",270 );271 keys.iter().map(|x| x.1.clone()).collect()272 });273 /*assert!(274 !initial_validators_0.is_empty(),275 "Empty validator set for session 0 in (pseudo) genesis block!"276 );*/277278 let initial_validators_1 =279 <Runtime as pallet_session::Config>::SessionManager::new_session(1)280 .unwrap_or_else(|| initial_validators_0.clone());281 /*assert!(282 !initial_validators_1.is_empty(),283 "Empty validator set for session 1 in (pseudo) genesis block!"284 );*/285286 let queued_keys: Vec<_> = initial_validators_1287 .iter()288 .cloned()289 .map(|v| {290 (291 v.clone(),292 <pallet_session::NextKeys<Runtime>>::get(&v)293 .expect("Validator in session 1 missing keys!"),294 )295 })296 .collect();297298 // Tell everyone about the genesis session keys -- Aura must've already initialized it299 //<Runtime as pallet_session::Config>::SessionHandler::on_genesis_session::<<Runtime as pallet_session::Config>::Keys>(&queued_keys);300301 <pallet_session::Validators<Runtime>>::put(initial_validators_0);302 <pallet_session::QueuedKeys<Runtime>>::put(queued_keys);303304 <Runtime as pallet_session::Config>::SessionManager::start_session(0);305306 log::info!(307 target: "runtime::aura_to_collator_selection",308 "Migration of Aura authorities to Collator Selection invulnerables is complete."309 );310311 migration::put_storage_value::<()>(312 b"AuraToCollatorSelection",313 b"StorageVersion",314 &[],315 (),316 );317318 weight += <Runtime as frame_system::Config>::DbWeight::get().writes(1)319 } else {320 log::info!(321 target: "runtime::aura_to_collator_selection",322 "The storage migration has already been flagged as complete. No migration needs to be done.",323 );324 }325326 weight327 }328329 #[cfg(not(feature = "collator-selection"))]330 {331 Weight::zero()332 }333 }334}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617pub mod config;18pub mod construct_runtime;19pub mod dispatch;20pub mod ethereum;21pub mod identity;22pub mod instance;23pub mod maintenance;24pub mod runtime_apis;2526pub mod sponsoring;27#[allow(missing_docs)]28pub mod weights;2930#[cfg(test)]31pub mod tests;3233use frame_support::{34 traits::{Currency, Imbalance, OnUnbalanced},35 weights::Weight,36};37use sp_runtime::{38 generic, impl_opaque_keys,39 traits::{BlakeTwo256, BlockNumberProvider},40};41use sp_std::vec::Vec;42#[cfg(feature = "std")]43use sp_version::NativeVersion;44use up_common::types::{AccountId, BlockNumber};4546use crate::{AllPalletsWithSystem, Aura, Balances, Runtime, RuntimeCall, Signature, Treasury};4748#[macro_export]49macro_rules! unsupported {50 () => {51 pallet_common::unsupported!($crate::Runtime)52 };53}5455/// The address format for describing accounts.56pub type Address = sp_runtime::MultiAddress<AccountId, ()>;57/// A Block signed with a Justification58pub type SignedBlock = generic::SignedBlock<Block>;59/// Frontier wrapped extrinsic60pub type UncheckedExtrinsic =61 fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;62/// Header type.63pub type Header = generic::Header<BlockNumber, BlakeTwo256>;64/// Block type.65pub type Block = generic::Block<Header, UncheckedExtrinsic>;66/// BlockId type as expected by this runtime.67pub type BlockId = generic::BlockId<Block>;6869impl_opaque_keys! {70 pub struct SessionKeys {71 pub aura: Aura,72 }73}7475/// The version information used to identify this runtime when compiled natively.76#[cfg(feature = "std")]77pub fn native_version() -> NativeVersion {78 NativeVersion {79 runtime_version: crate::VERSION,80 can_author_with: Default::default(),81 }82}8384pub type SignedExtra = (85 frame_system::CheckSpecVersion<Runtime>,86 frame_system::CheckTxVersion<Runtime>,87 frame_system::CheckGenesis<Runtime>,88 frame_system::CheckEra<Runtime>,89 pallet_charge_transaction::CheckNonce<Runtime>,90 frame_system::CheckWeight<Runtime>,91 maintenance::CheckMaintenance,92 identity::DisableIdentityCalls,93 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,94 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,95 pallet_ethereum::FakeTransactionFinalizer<Runtime>,96);9798/// Executive: handles dispatch to the various modules.99pub type Executive = frame_executive::Executive<100 Runtime,101 Block,102 frame_system::ChainContext<Runtime>,103 Runtime,104 AllPalletsWithSystem,105 AuraToCollatorSelection,106>;107108type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;109110pub(crate) type DealWithFees = Treasury;111112pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);113114impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider115 for RelayChainBlockNumberProvider<T>116{117 type BlockNumber = BlockNumber;118119 fn current_block_number() -> Self::BlockNumber {120 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()121 .map(|d| d.relay_parent_number)122 .unwrap_or_default()123 }124 #[cfg(feature = "runtime-benchmarks")]125 fn set_block_number(block: Self::BlockNumber) {126 cumulus_pallet_parachain_system::RelaychainDataProvider::<T>::set_block_number(block)127 }128}129130#[cfg(not(feature = "lookahead"))]131pub(crate) struct CheckInherents;132133#[cfg(not(feature = "lookahead"))]134impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {135 fn check_inherents(136 block: &Block,137 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,138 ) -> sp_inherents::CheckInherentsResult {139 use crate::InherentDataExt;140141 let relay_chain_slot = relay_state_proof142 .read_slot()143 .expect("Could not read the relay chain slot from the proof");144145 let inherent_data =146 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(147 relay_chain_slot,148 sp_std::time::Duration::from_secs(6),149 )150 .create_inherent_data()151 .expect("Could not create the timestamp inherent data");152153 inherent_data.check_extrinsics(block)154 }155}156157#[derive(parity_scale_codec::Encode, parity_scale_codec::Decode)]158pub enum XCMPMessage<XAccountId, XBalance> {159 /// Transfer tokens to the given account from the Parachain account.160 TransferToken(XAccountId, XBalance),161}162163pub struct AuraToCollatorSelection;164impl frame_support::traits::OnRuntimeUpgrade for AuraToCollatorSelection {165 fn on_runtime_upgrade() -> Weight {166 #[cfg(feature = "collator-selection")]167 {168 use frame_support::{storage::migration, BoundedVec};169 use pallet_session::SessionManager;170 use sp_runtime::{traits::OpaqueKeys, RuntimeAppPublic};171172 use crate::config::pallets::MaxCollators;173174 let mut weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);175176 let version = migration::get_storage_value::<()>(177 b"AuraToCollatorSelection",178 b"StorageVersion",179 &[],180 );181182 let should_upgrade = version.is_none();183184 if should_upgrade {185 log::info!(186 target: "runtime::aura_to_collator_selection",187 "Running migration of Aura authorities to Collator Selection invulnerables"188 );189190 let invulnerables = pallet_aura::Pallet::<Runtime>::authorities()191 .iter()192 .cloned()193 .filter_map(|authority_id| {194 weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));195 let vec = authority_id.to_raw_vec();196 let slice = vec.as_slice();197 let array: Option<[u8; 32]> = match slice.try_into() {198 Ok(a) => Some(a),199 Err(_) => {200 log::error!("Failed to convert an Aura authority to a Collator Selection invulnerable: {:?}", authority_id);201 None202 },203 };204 array.map(|a| (AccountId::from(a), authority_id))205 })206 .collect::<Vec<_>>();207208 let bounded_invulnerables = BoundedVec::<_, MaxCollators>::try_from(209 invulnerables210 .iter()211 .cloned()212 .map(|(acc, _)| acc)213 .collect::<Vec<_>>(),214 )215 .expect("Existing collators/invulnerables are more than MaxCollators");216217 <pallet_collator_selection::Invulnerables<Runtime>>::put(bounded_invulnerables);218219 let keys = invulnerables220 .into_iter()221 .map(|(acc, aura)| {222 (223 acc.clone(), // account id224 acc, // validator id225 SessionKeys { aura }, // session keys226 )227 })228 .collect::<Vec<_>>();229230 for (account, val, keys) in keys.iter() {231 for id in <Runtime as pallet_session::Config>::Keys::key_ids() {232 <pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), val)233 }234 <pallet_session::NextKeys<Runtime>>::insert(val, keys);235 // todo exercise caution, the following is taken from genesis236 if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(account)237 .is_err()238 {239 log::warn!(240 "We have entered an error with incrementing consumers without limit during the migration"241 );242 // This will leak a provider reference, however it only happens once (at243 // genesis) so it's really not a big deal and we assume that the user wants to244 // do this since it's the only way a non-endowed account can contain a session245 // key.246 frame_system::Pallet::<Runtime>::inc_providers(account);247 }248 }249250 let initial_validators_0 =251 <Runtime as pallet_session::Config>::SessionManager::new_session(0)252 .unwrap_or_else(|| {253 frame_support::print(254 "No initial validator provided by `SessionManager`, use \255 session config keys to generate initial validator set.",256 );257 keys.iter().map(|x| x.1.clone()).collect()258 });259 /*assert!(260 !initial_validators_0.is_empty(),261 "Empty validator set for session 0 in (pseudo) genesis block!"262 );*/263264 let initial_validators_1 =265 <Runtime as pallet_session::Config>::SessionManager::new_session(1)266 .unwrap_or_else(|| initial_validators_0.clone());267 /*assert!(268 !initial_validators_1.is_empty(),269 "Empty validator set for session 1 in (pseudo) genesis block!"270 );*/271272 let queued_keys: Vec<_> = initial_validators_1273 .iter()274 .cloned()275 .map(|v| {276 (277 v.clone(),278 <pallet_session::NextKeys<Runtime>>::get(&v)279 .expect("Validator in session 1 missing keys!"),280 )281 })282 .collect();283284 // Tell everyone about the genesis session keys -- Aura must've already initialized it285 //<Runtime as pallet_session::Config>::SessionHandler::on_genesis_session::<<Runtime as pallet_session::Config>::Keys>(&queued_keys);286287 <pallet_session::Validators<Runtime>>::put(initial_validators_0);288 <pallet_session::QueuedKeys<Runtime>>::put(queued_keys);289290 <Runtime as pallet_session::Config>::SessionManager::start_session(0);291292 log::info!(293 target: "runtime::aura_to_collator_selection",294 "Migration of Aura authorities to Collator Selection invulnerables is complete."295 );296297 migration::put_storage_value::<()>(298 b"AuraToCollatorSelection",299 b"StorageVersion",300 &[],301 (),302 );303304 weight += <Runtime as frame_system::Config>::DbWeight::get().writes(1)305 } else {306 log::info!(307 target: "runtime::aura_to_collator_selection",308 "The storage migration has already been flagged as complete. No migration needs to be done.",309 );310 }311312 weight313 }314315 #[cfg(not(feature = "collator-selection"))]316 {317 Weight::zero()318 }319 }320}