From 9beca8d47101c57ac28f05231dc8fed173163233 Mon Sep 17 00:00:00 2001 From: Drew Stone Date: Sat, 30 Nov 2024 22:29:54 -0700 Subject: [PATCH 1/9] Add vesting migration --- Cargo.lock | 15 +- Cargo.toml | 1 + account-util/Cargo.toml | 18 ++ account-util/src/lib.rs | 91 ++++++ runtime/mainnet/src/frontier_evm.rs | 13 +- runtime/mainnet/src/lib.rs | 33 +-- ...nvestor_team_vesting_migration_11302024.rs | 275 ++++++++++++++++++ runtime/mainnet/src/migrations/mod.rs | 2 + .../session_key_migrations_08062024.rs} | 4 +- runtime/testnet/src/lib.rs | 66 +++-- 10 files changed, 460 insertions(+), 58 deletions(-) create mode 100644 account-util/Cargo.toml create mode 100644 account-util/src/lib.rs create mode 100644 runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs create mode 100644 runtime/mainnet/src/migrations/mod.rs rename runtime/mainnet/src/{migrations.rs => migrations/session_key_migrations_08062024.rs} (94%) diff --git a/Cargo.lock b/Cargo.lock index fec4a721a..3e1b252e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "Inflector" @@ -12,6 +12,19 @@ dependencies = [ "regex", ] +[[package]] +name = "account-util" +version = "1.2.3" +dependencies = [ + "frame-support", + "pallet-airdrop-claims", + "pallet-vesting", + "sp-core", + "sp-runtime", + "sp-std", + "tangle-primitives", +] + [[package]] name = "addchain" version = "0.2.0" diff --git a/Cargo.toml b/Cargo.toml index a4437160a..e20877f0f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ exclude = ["examples"] [workspace] members = [ + "account-util", "primitives", "primitives/crypto", "primitives/rpc/*", diff --git a/account-util/Cargo.toml b/account-util/Cargo.toml new file mode 100644 index 000000000..acefeeb63 --- /dev/null +++ b/account-util/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "account-util" +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +exclude.workspace = true + +[dependencies] +frame-support = { workspace = true, features = ["std"] } +sp-core = { workspace = true, features = ["std"] } +sp-runtime = { workspace = true, features = ["std"] } +sp-std = { workspace = true, features = ["std"] } +pallet-airdrop-claims = { workspace = true, features = ["std"] } +pallet-vesting = { workspace = true, features = ["std"] } +tangle-primitives = { workspace = true, features = ["std"] } \ No newline at end of file diff --git a/account-util/src/lib.rs b/account-util/src/lib.rs new file mode 100644 index 000000000..61afd7b7e --- /dev/null +++ b/account-util/src/lib.rs @@ -0,0 +1,91 @@ +use core::str::FromStr; +use frame_support::{pallet_prelude::*, traits::OnRuntimeUpgrade}; +use pallet_airdrop_claims::MultiAddress; +use pallet_vesting::{Vesting, VestingInfo}; +use sp_core::H160; +use sp_runtime::{ + traits::{AccountIdConversion, Zero}, + AccountId32, +}; +use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; +use tangle_primitives::{AccountId, Balance}; + +pub const BLOCK_TIME: u128 = 6; +pub const ONE_YEAR_BLOCKS: u64 = (365 * 24 * 60 * 60 / BLOCK_TIME) as u64; + +pub const INVESTOR_ACCOUNTS: [(&str, Balance); 29] = [ + ("5FCviiKcJzVfdwqv451JRQc93ZTSbbC9YfgKMkN3LpNMBjS3", 100000000000000000000000), + ("0xC02ad7b9a9121fc849196E844DC869D2250DF3A6", 150000000000000000000000), + ("5HBKM8XL7sr7S7qx6ukugDJUBhm16Ubnz1KuJCdHmHQvtc7Z", 400000000000000000000000), + ("0x86f99feff4cd3268ccefc760a6bbce2e07aa4d8e", 100000000000000000000000), + ("5HCJQLeQqCf64C6uy7CSoTND35QNdi1zU66TTM6QPCG9u9BB", 500000000000000000000000), + ("5DhQMPP69vRBNvZ6w4E9qii1yj56M66YXuPkkvz12yvn5ufN", 2750000000000000000000000), + ("0x17B74Dcf1E422AF5964056eB836321aE7A820035", 200000000000000000000000), + ("5Df1Sec4ZmeidskuuPtpt4SSCL6U5St19fsv4sBAwvkwmvin", 100000000000000000000000), + ("5FerzxKQZoP9wxjRhS1PHA4v27aPQMoZpXmufcQk1JYE5xU8", 100000000000000000000000), + ("0x75afaece8cf2a7974b1e541648923afd9339b3f8", 150000000000000000000000), + ("0x5a82d0bad9995b1bfa71de79b5e524decb5bee1c", 1000000000000000000000000), + ("5Cf5SfzngS9T9fdQSsKt1GJ42BQPP7FqU4trLwgkDD1ZVBN7", 20000000000000000000000), + ("0x5da7351A4Cb03c33e11F51841bc614d985812821", 20000000000000000000000), + ("5DDTvr7P2MaUirj3rSvpcF5DLxECiAqpQegdVCzAuwxingVC", 50000000000000000000000), + ("5CXkTTyNzVuE2fwNBzSwmmtcCntnun5vMDx6Wnn5VjopGUVx", 160000000000000000000000), + ("5G9Ji4EEiTehMKa9Nfe2rGozZB3XEyRtyvJWt2wYLMRYyAyn", 180000000000000000000000), + ("5EZcQuvjvuv1K4Ugg2ofLEhAC3NXPbaCAytPR3hmUqBv1Bhe", 200000000000000000000000), + ("5Fe8pwn27TNBuM1Agz1ivCMykX795woPQkjwiWD4UoSndmQj", 220000000000000000000000), + ("5HWLv9RvMSZ6FwuQswHCo1nmYxmAqRutqh37Vapx3pmXbVU3", 240000000000000000000000), + ("5ENgRjBQue32ppyLw1u55Rbe36gDWTJgZmcbSfZwrJAyt2tZ", 781850000000000000000000), + ("5DhzryWQpJTQfdauBf7yGKpr6LW42ye4oYvEYiVbMcGN7GZt", 879590000000000000000000), + ("5C52zXiWq7BM5x55soCudf8daW12NTLtMfisBiYd5Pov1Hw1", 977320000000000000000000), + ("5HbRuwKiUw4g7yh9iNBQ6zFG63sgZyGoZ4ep61CqMYTzk4gU", 1075050000000000000000000), + ("5HnQ2onP12Vhv3dVUvmKocbWr5sMjunCmjt2MmtxMr5z5dp1", 1172780000000000000000000), + ("5CAbD6BFcATxi9jVpixNtsLKovQy6RWQMQynHtapqAtKL8vT", 338150000000000000000000), + ("5DP7RmWdPD6TWbTNgBu6iKzYsm95fHETXyy5tQvEmS6zDhPn", 380410000000000000000000), + ("5EyDntnRYxgWLuHFRmSnirioDNpMDCUTQ4bwRYV3LGHQoMxo", 422680000000000000000000), + ("5DkNqZs22mLYXKy7c2vrtstqbcQBU1ArPKw51xvC37eGsuNP", 464950000000000000000000), + ("5CQJt5A7GmEUhh7S3MtaiBGvNRTY6PFw6KHJFcTVD4ZxBty7", 507220000000000000000000), +]; + +pub const TEAM_ACCOUNT_TO_UPDATE: [(&str, Balance); 1] = + [("5FH32Ro5cTpLE1FhP3skdi16UuVariyzoQfyK7vvjE2CHEtX", 28721849310000000043843584)]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_decoding_accounts_into_account_id_32_bytes() { + for (address, _) in INVESTOR_ACCOUNTS { + let account_id = if address.starts_with("0x") { + MultiAddress::EVM( + H160::from_str(address).expect("should be a valid address").into(), + ) + .to_account_id_32() + } else { + let account = MultiAddress::Native( + AccountId32::from_str(address).expect("should be a valid address"), + ) + .to_account_id_32(); + + assert_eq!( + account, + AccountId32::from_str(address).expect("should be a valid address") + ); + + account + }; + + let account_id_bytes: [u8; 32] = account_id.into(); + println!("{:?}", account_id_bytes); + } + + for (address, _) in TEAM_ACCOUNT_TO_UPDATE { + let account_id = MultiAddress::Native( + AccountId32::from_str(address).expect("should be a valid address"), + ) + .to_account_id_32(); + + let account_id_bytes: [u8; 32] = account_id.into(); + println!("{:?}", account_id_bytes); + } + } +} diff --git a/runtime/mainnet/src/frontier_evm.rs b/runtime/mainnet/src/frontier_evm.rs index 38d046f19..e415fb75c 100644 --- a/runtime/mainnet/src/frontier_evm.rs +++ b/runtime/mainnet/src/frontier_evm.rs @@ -119,21 +119,20 @@ impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType { ) -> precompile_utils::EvmResult { Ok(match self { ProxyType::Any => true, - ProxyType::Governance => { - call.value == U256::zero() - && matches!( + ProxyType::Governance => + call.value == U256::zero() && + matches!( PrecompileName::from_address(call.to.0), Some(ref precompile) if is_governance_precompile(precompile) - ) - }, + ), // The proxy precompile does not contain method cancel_proxy ProxyType::CancelProxy => false, ProxyType::Balances => { // Allow only "simple" accounts as recipient (no code nor precompile). // Note: Checking the presence of the code is not enough because some precompiles // have no code. - !recipient_has_code - && !precompile_utils::precompile_set::is_precompile_or_fail::( + !recipient_has_code && + !precompile_utils::precompile_set::is_precompile_or_fail::( call.to.0, gas, )? }, diff --git a/runtime/mainnet/src/lib.rs b/runtime/mainnet/src/lib.rs index 59b5818e3..f287cf6e7 100644 --- a/runtime/mainnet/src/lib.rs +++ b/runtime/mainnet/src/lib.rs @@ -32,10 +32,9 @@ use frame_election_provider_support::{ bounds::{ElectionBounds, ElectionBoundsBuilder}, onchain, BalancingConfig, ElectionDataProvider, SequentialPhragmen, VoteWeight, }; -use frame_support::derive_impl; -use frame_support::genesis_builder_helper::build_state; -use frame_support::genesis_builder_helper::get_preset; use frame_support::{ + derive_impl, + genesis_builder_helper::{build_state, get_preset}, traits::{ tokens::{PayFromAccount, UnityAssetBalanceConversion}, AsEnsureOriginWithArg, Contains, OnFinalize, WithdrawReasons, @@ -657,8 +656,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) - .expect("input is padded with zeroes; qed") - % max.saturating_add(1); + .expect("input is padded with zeroes; qed") % + max.saturating_add(1); random as usize }, }; @@ -1149,15 +1148,15 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances(..) - | RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) + RuntimeCall::Balances(..) | + RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) ), ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) - | RuntimeCall::Council(..) - | RuntimeCall::Elections(..) - | RuntimeCall::Treasury(..) + RuntimeCall::Democracy(..) | + RuntimeCall::Council(..) | + RuntimeCall::Elections(..) | + RuntimeCall::Treasury(..) ), ProxyType::Staking => { matches!(c, RuntimeCall::Staking(..)) @@ -1427,7 +1426,7 @@ pub type Executive = frame_executive::Executive< frame_system::ChainContext, Runtime, AllPalletsWithSystem, - migrations::MigrateSessionKeys, + migrations::investor_team_vesting_migration_11302024::UpdateTeamInvestorVesting, >; impl fp_self_contained::SelfContainedCall for RuntimeCall { @@ -1466,9 +1465,8 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => { - call.pre_dispatch_self_contained(info, dispatch_info, len) - }, + RuntimeCall::Ethereum(call) => + call.pre_dispatch_self_contained(info, dispatch_info, len), _ => None, } } @@ -1478,11 +1476,10 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), - ))) - }, + ))), _ => None, } } diff --git a/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs b/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs new file mode 100644 index 000000000..c8cff13ce --- /dev/null +++ b/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs @@ -0,0 +1,275 @@ +use super::*; +use crate::{AccountId, Balance, BlockNumber, H160}; +use core::str::FromStr; +use frame_support::{pallet_prelude::*, traits::OnRuntimeUpgrade}; +use pallet_airdrop_claims::MultiAddress; +use pallet_ethereum::Block; +use pallet_vesting::{MaxVestingSchedulesGet, Vesting, VestingInfo}; +use sp_runtime::{ + traits::{AccountIdConversion, Convert, EnsureDiv, Header, Zero}, + AccountId32, Percent, Saturating, +}; +use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec}; + +pub const BLOCK_TIME: u128 = 6; +pub const ONE_YEAR_BLOCKS: u64 = (365 * 24 * 60 * 60 / BLOCK_TIME) as u64; + +pub const INVESTOR_ACCOUNTS: [[u8; 32]; 29] = [ + [ + 138, 249, 246, 184, 248, 138, 249, 225, 200, 68, 130, 170, 83, 137, 64, 251, 106, 197, 74, + 79, 232, 191, 177, 86, 84, 71, 188, 169, 202, 64, 231, 36, + ], + [ + 225, 94, 83, 233, 185, 41, 177, 181, 248, 143, 147, 205, 180, 83, 14, 125, 47, 25, 125, + 248, 22, 125, 226, 220, 156, 78, 175, 3, 230, 244, 140, 52, + ], + [ + 226, 56, 28, 178, 235, 59, 229, 44, 201, 146, 200, 29, 38, 152, 123, 201, 70, 248, 93, 143, + 16, 158, 67, 242, 146, 71, 119, 144, 164, 118, 131, 239, + ], + [ + 83, 94, 177, 114, 5, 76, 126, 89, 124, 208, 48, 113, 197, 113, 201, 20, 143, 244, 231, 128, + 68, 163, 167, 63, 84, 227, 193, 177, 216, 112, 208, 84, + ], + [ + 226, 248, 45, 109, 239, 71, 153, 69, 230, 189, 169, 9, 81, 83, 24, 60, 250, 169, 164, 251, + 82, 166, 31, 117, 66, 164, 222, 120, 208, 80, 196, 88, + ], + [ + 72, 57, 99, 4, 212, 215, 132, 34, 128, 223, 72, 106, 143, 56, 37, 98, 103, 77, 253, 149, + 40, 92, 6, 129, 204, 248, 163, 22, 61, 149, 207, 120, + ], + [ + 165, 243, 249, 88, 179, 113, 230, 225, 100, 88, 23, 11, 87, 179, 246, 32, 54, 85, 215, 64, + 68, 146, 82, 238, 21, 108, 206, 162, 78, 144, 200, 158, + ], + [ + 70, 101, 198, 201, 165, 102, 235, 103, 142, 23, 51, 45, 209, 4, 177, 120, 143, 223, 81, + 222, 187, 212, 130, 212, 103, 129, 129, 86, 35, 141, 167, 97, + ], + [ + 158, 193, 210, 91, 210, 217, 80, 151, 219, 193, 65, 163, 149, 70, 177, 108, 77, 81, 5, 84, + 187, 146, 59, 162, 138, 78, 236, 7, 21, 109, 42, 66, + ], + [ + 73, 92, 137, 97, 116, 188, 150, 231, 162, 97, 156, 213, 207, 65, 244, 189, 115, 96, 149, + 86, 219, 50, 223, 200, 220, 213, 143, 160, 153, 53, 153, 173, + ], + [ + 196, 215, 35, 118, 232, 152, 244, 80, 42, 241, 100, 107, 224, 191, 61, 29, 64, 54, 3, 112, + 174, 240, 158, 212, 197, 115, 20, 10, 10, 92, 116, 28, + ], + [ + 26, 55, 2, 120, 183, 66, 224, 91, 238, 81, 231, 203, 154, 226, 246, 253, 26, 45, 218, 123, + 51, 5, 122, 148, 251, 110, 109, 204, 217, 81, 117, 18, + ], + [ + 20, 148, 147, 133, 5, 238, 234, 73, 51, 154, 251, 105, 92, 63, 31, 44, 131, 42, 183, 201, + 182, 242, 211, 21, 14, 99, 22, 212, 193, 29, 186, 217, + ], + [ + 50, 234, 142, 113, 250, 70, 204, 94, 20, 44, 9, 35, 5, 25, 87, 208, 53, 96, 94, 47, 51, + 135, 10, 94, 133, 29, 179, 167, 247, 226, 137, 19, + ], + [ + 20, 160, 96, 205, 27, 33, 238, 218, 236, 77, 34, 88, 25, 163, 112, 231, 10, 110, 163, 111, + 36, 5, 110, 50, 142, 76, 49, 183, 209, 147, 179, 100, + ], + [ + 180, 115, 60, 111, 163, 25, 14, 178, 121, 79, 191, 213, 179, 191, 156, 236, 25, 37, 83, 89, + 216, 107, 123, 146, 254, 218, 30, 154, 115, 101, 39, 47, + ], + [ + 110, 132, 65, 222, 55, 201, 168, 118, 191, 249, 229, 145, 52, 219, 24, 86, 203, 255, 63, + 209, 91, 34, 206, 199, 8, 240, 78, 43, 66, 93, 224, 31, + ], + [ + 158, 51, 219, 46, 28, 186, 50, 107, 225, 183, 177, 124, 244, 215, 38, 15, 44, 229, 59, 64, + 40, 246, 80, 239, 182, 237, 129, 191, 49, 173, 231, 19, + ], + [ + 240, 187, 14, 171, 122, 87, 33, 20, 39, 68, 54, 68, 44, 137, 73, 107, 151, 54, 58, 149, + 132, 130, 222, 184, 244, 65, 148, 162, 98, 23, 127, 76, + ], + [ + 102, 46, 18, 1, 115, 40, 196, 41, 159, 117, 230, 38, 72, 10, 253, 186, 224, 229, 249, 227, + 186, 62, 32, 12, 210, 131, 42, 190, 135, 233, 142, 27, + ], + [ + 72, 173, 142, 236, 101, 180, 147, 239, 64, 70, 44, 143, 198, 254, 51, 143, 104, 149, 94, + 146, 75, 159, 40, 52, 53, 225, 28, 197, 73, 84, 189, 11, + ], + [ + 0, 64, 106, 126, 60, 179, 52, 134, 195, 43, 228, 249, 202, 36, 34, 62, 137, 47, 60, 194, + 123, 253, 171, 30, 205, 154, 28, 23, 3, 169, 223, 100, + ], + [ + 244, 156, 26, 140, 205, 108, 13, 44, 139, 130, 165, 246, 58, 203, 83, 171, 189, 21, 71, 62, + 89, 81, 150, 115, 29, 175, 114, 213, 194, 91, 164, 64, + ], + [ + 252, 249, 120, 35, 115, 244, 16, 85, 11, 113, 242, 83, 208, 86, 198, 225, 23, 163, 23, 142, + 49, 124, 81, 48, 158, 202, 185, 100, 59, 31, 218, 67, + ], + [ + 4, 125, 23, 244, 85, 187, 199, 151, 55, 109, 248, 90, 16, 134, 116, 192, 43, 28, 74, 246, + 21, 111, 172, 109, 27, 122, 88, 247, 219, 172, 88, 63, + ], + [ + 58, 69, 255, 40, 206, 137, 18, 192, 97, 105, 41, 95, 157, 205, 120, 252, 232, 50, 221, 68, + 83, 187, 60, 133, 96, 189, 35, 160, 89, 121, 188, 7, + ], + [ + 128, 133, 255, 113, 171, 251, 146, 3, 232, 220, 247, 119, 166, 113, 67, 37, 228, 170, 48, + 5, 52, 240, 26, 77, 236, 13, 180, 213, 9, 26, 219, 117, + ], + [ + 74, 126, 6, 168, 58, 228, 131, 195, 50, 142, 139, 187, 204, 130, 114, 32, 107, 105, 238, + 136, 202, 91, 109, 251, 247, 98, 9, 37, 122, 202, 33, 103, + ], + [ + 14, 243, 144, 141, 108, 213, 243, 175, 130, 92, 68, 191, 148, 27, 215, 242, 160, 27, 197, + 13, 240, 118, 166, 253, 214, 93, 174, 242, 127, 123, 238, 97, + ], +]; + +pub const TEAM_ACCOUNT_TO_UPDATE: [u8; 32] = [ + 142, 28, 43, 221, 218, 185, 87, 61, 140, 176, 148, 219, 255, 186, 36, 162, 178, 194, 27, 126, + 113, 227, 245, 182, 4, 232, 96, 116, 131, 135, 36, 67, +]; + +/// Migration to update team and investor vesting schedules to 4 years with 1 year cliff +pub struct UpdateTeamInvestorVesting(sp_std::marker::PhantomData); + +pub type BalanceOf = + <::Currency as frame_support::traits::Currency< + ::AccountId, + >>::Balance; + +pub type BlockNumberOf = + <<::Block as sp_runtime::traits::Block>::Header as Header>::Number; + +impl OnRuntimeUpgrade + for UpdateTeamInvestorVesting +{ + fn on_runtime_upgrade() -> Weight { + let mut reads = 0u64; + let mut writes = 0u64; + + // Update investor vesting schedules + for account in INVESTOR_ACCOUNTS.iter() { + let account_id: T::AccountId = + T::AccountId::decode(&mut account.as_ref()).expect("Invalid account ID"); + update_account_vesting::(&account_id, &mut reads, &mut writes); + } + + // Update team vesting schedule + let account_id: T::AccountId = + T::AccountId::decode(&mut TEAM_ACCOUNT_TO_UPDATE.as_ref()).expect("Invalid account ID"); + update_account_vesting::(&account_id, &mut reads, &mut writes); + + T::DbWeight::get().reads_writes(reads, writes) + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, &'static str> { + Ok(Vec::new()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: Vec) -> Result<(), &'static str> { + // Verify schedules for all accounts + for (address, _) in INVESTOR_ACCOUNTS { + let account_id = if address.starts_with("0x") { + MultiAddress::Evm(H160::from_str(address).expect("should be a valid address")) + .to_account_id_32() + } else { + address.parse().expect("Invalid account ID") + }; + verify_updated_schedule::(&account_id)?; + } + for (address, _) in TEAM_ACCOUNT_TO_UPDATE { + let account_id = address.parse().expect("Invalid account ID"); + verify_updated_schedule::(&account_id)?; + } + + Ok(()) + } +} + +// Update investor vesting schedules +fn update_account_vesting( + account_id: &T::AccountId, + reads: &mut u64, + writes: &mut u64, +) { + let schedules = Vesting::::get(&account_id); + *reads += 1; + if let Some(schedules) = schedules { + update_vesting_schedule::(&account_id, schedules.to_vec()); + *writes += 1; + } +} + +fn update_vesting_schedule( + account_id: &T::AccountId, + schedules: Vec, BlockNumberOf>>, +) { + // Calculate total vested amount + let total_vested = schedules + .iter() + .map(|schedule| schedule.locked()) + .fold(Zero::zero(), |acc: BalanceOf, val: BalanceOf| acc.saturating_add(val)); + + if total_vested.is_zero() { + return; + } + + // New vesting parameters + let one_year_blocks = BlockNumberOf::::from(ONE_YEAR_BLOCKS as u32); + let three_year_blocks = one_year_blocks.saturating_mul(BlockNumberOf::::from(3u32)); + let four_year_blocks = one_year_blocks.saturating_mul(BlockNumberOf::::from(4u32)); + + // At 1 year cliff, 25% unlocks + let quarter_percentage = Percent::from_percent(25); + let cliff_amount = quarter_percentage.mul_floor(total_vested); + // Remaining 75% vests linearly over 3 years + let remaining_amount = total_vested.saturating_sub(cliff_amount); + let per_block = remaining_amount + .ensure_div(T::BlockNumberToBalance::convert(three_year_blocks)) + .unwrap(); + + let mut bounded_new_schedules: BoundedVec< + VestingInfo, BlockNumberOf>, + MaxVestingSchedulesGet, + > = BoundedVec::new(); + + bounded_new_schedules + .try_push(VestingInfo::new(cliff_amount, Zero::zero(), one_year_blocks)) + .expect("Failed to push new schedules"); + bounded_new_schedules + .try_push(VestingInfo::new(remaining_amount, per_block, one_year_blocks)) + .expect("Failed to push new schedules"); + + // Update storage + Vesting::::insert(account_id, bounded_new_schedules); +} + +#[cfg(feature = "try-runtime")] +fn verify_updated_schedule( + account_id: &T::AccountId, +) -> Result<(), &'static str> { + if let Some(schedules) = Vesting::::get(account_id) { + ensure!(schedules.len() >= 2, "Schedule should have at least 2 entries"); + ensure!( + schedules[0].starting_block() == T::BlockNumber::from(ONE_YEAR_BLOCKS as u32), + "First schedule should start at 1 year" + ); + ensure!( + schedules[1].starting_block() == T::BlockNumber::from(ONE_YEAR_BLOCKS as u32), + "Second schedule should start at 1 year" + ); + ensure!(schedules[0].per_block().is_zero(), "First schedule should have zero per_block"); + } + Ok(()) +} diff --git a/runtime/mainnet/src/migrations/mod.rs b/runtime/mainnet/src/migrations/mod.rs new file mode 100644 index 000000000..7cc124004 --- /dev/null +++ b/runtime/mainnet/src/migrations/mod.rs @@ -0,0 +1,2 @@ +pub mod investor_team_vesting_migration_11302024; +pub mod session_key_migrations_08062024; diff --git a/runtime/mainnet/src/migrations.rs b/runtime/mainnet/src/migrations/session_key_migrations_08062024.rs similarity index 94% rename from runtime/mainnet/src/migrations.rs rename to runtime/mainnet/src/migrations/session_key_migrations_08062024.rs index ac7f94ee5..5d47b0c38 100644 --- a/runtime/mainnet/src/migrations.rs +++ b/runtime/mainnet/src/migrations/session_key_migrations_08062024.rs @@ -1,7 +1,9 @@ use super::*; -use frame_support::traits::OnRuntimeUpgrade; +use crate::{AccountId, Babe, Grandpa, KeyTypeId, OpaqueKeys, Session, SessionKeys}; +use frame_support::{pallet_prelude::*, traits::OnRuntimeUpgrade}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use sp_runtime::{BoundToRuntimeAppPublic, RuntimeAppPublic, RuntimeDebug}; +use sp_std::vec; /// Old session keys structure. /// diff --git a/runtime/testnet/src/lib.rs b/runtime/testnet/src/lib.rs index da36b14cc..be3080a3b 100644 --- a/runtime/testnet/src/lib.rs +++ b/runtime/testnet/src/lib.rs @@ -33,10 +33,9 @@ use frame_election_provider_support::{ bounds::{ElectionBounds, ElectionBoundsBuilder}, onchain, BalancingConfig, ElectionDataProvider, SequentialPhragmen, VoteWeight, }; -use frame_support::derive_impl; -use frame_support::genesis_builder_helper::build_state; -use frame_support::genesis_builder_helper::get_preset; use frame_support::{ + derive_impl, + genesis_builder_helper::{build_state, get_preset}, traits::{ tokens::{PayFromAccount, UnityAssetBalanceConversion}, AsEnsureOriginWithArg, Contains, OnFinalize, WithdrawReasons, @@ -664,8 +663,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) - .expect("input is padded with zeroes; qed") - % max.saturating_add(1); + .expect("input is padded with zeroes; qed") % + max.saturating_add(1); random as usize }, }; @@ -1147,15 +1146,15 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances(..) - | RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) + RuntimeCall::Balances(..) | + RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) ), ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) - | RuntimeCall::Council(..) - | RuntimeCall::Elections(..) - | RuntimeCall::Treasury(..) + RuntimeCall::Democracy(..) | + RuntimeCall::Council(..) | + RuntimeCall::Elections(..) | + RuntimeCall::Treasury(..) ), ProxyType::Staking => { matches!(c, RuntimeCall::Staking(..)) @@ -1388,9 +1387,8 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => { - call.pre_dispatch_self_contained(info, dispatch_info, len) - }, + RuntimeCall::Ethereum(call) => + call.pre_dispatch_self_contained(info, dispatch_info, len), _ => None, } } @@ -1400,11 +1398,10 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), - ))) - }, + ))), _ => None, } } @@ -1618,7 +1615,8 @@ impl pallet_multi_asset_delegation::Config for Runtime { // parameter_types! { // // tTNT: native asset is always a reserved asset // pub NativeLocation: Location = Location::here(); -// pub NativeSygmaResourceId: [u8; 32] = hex_literal::hex!("0000000000000000000000000000000000000000000000000000000000002000"); +// pub NativeSygmaResourceId: [u8; 32] = +// hex_literal::hex!("0000000000000000000000000000000000000000000000000000000000002000"); // // SygUSD: a non-reserved asset // pub SygUSDLocation: Location = Location::new( @@ -1632,7 +1630,8 @@ impl pallet_multi_asset_delegation::Config for Runtime { // // SygUSDAssetId is the substrate assetID of SygUSD // pub SygUSDAssetId: AssetId = 2000; // // SygUSDResourceId is the resourceID that mapping with the foreign asset SygUSD -// pub SygUSDResourceId: ResourceId = hex_literal::hex!("0000000000000000000000000000000000000000000000000000000000001100"); +// pub SygUSDResourceId: ResourceId = +// hex_literal::hex!("0000000000000000000000000000000000000000000000000000000000001100"); // // PHA: a reserved asset // pub PHALocation: Location = Location::new( @@ -1646,8 +1645,8 @@ impl pallet_multi_asset_delegation::Config for Runtime { // // PHAAssetId is the substrate assetID of PHA // pub PHAAssetId: AssetId = 2001; // // PHAResourceId is the resourceID that mapping with the foreign asset PHA -// pub PHAResourceId: ResourceId = hex_literal::hex!("0000000000000000000000000000000000000000000000000000000000001000"); -// } +// pub PHAResourceId: ResourceId = +// hex_literal::hex!("0000000000000000000000000000000000000000000000000000000000001000"); } // fn bridge_accounts_generator() -> BTreeMap { // let mut account_map: BTreeMap = BTreeMap::new(); @@ -1677,7 +1676,8 @@ impl pallet_multi_asset_delegation::Config for Runtime { // pub const SygmaBridgePalletId: PalletId = PalletId(*b"sygma/01"); // // Tangle testnet super admin: 5D2hZnw8Z7kg5LpQiEBb6HPG4V51wYXuKhE7sVhXiUPWj8D1 -// pub SygmaBridgeAdminAccountKey: [u8; 32] = hex_literal::hex!("2ab4c35efb6ab82377c2325467103cf46742d288ae1f8917f1d5960f4a1e9065"); +// pub SygmaBridgeAdminAccountKey: [u8; 32] = +// hex_literal::hex!("2ab4c35efb6ab82377c2325467103cf46742d288ae1f8917f1d5960f4a1e9065"); // pub SygmaBridgeAdminAccount: AccountId = SygmaBridgeAdminAccountKey::get().into(); // // SygmaBridgeFeeAccount is a substrate account and used for bridging fee collection @@ -1687,18 +1687,22 @@ impl pallet_multi_asset_delegation::Config for Runtime { // // BridgeAccountNative: 5EYCAe5jLbHcAAMKvLFSXgCTbPrLgBJusvPwfKcaKzuf5X5e // pub BridgeAccountNative: AccountId32 = SygmaBridgePalletId::get().into_account_truncating(); // // BridgeAccountOtherToken 5EYCAe5jLbHcAAMKvLFiGhk3htXY8jQncbLTDGJQnpnPMAVp -// pub BridgeAccountOtherToken: AccountId32 = SygmaBridgePalletId::get().into_sub_account_truncating(1u32); -// // BridgeAccounts is a list of accounts for holding transferred asset collection -// pub BridgeAccounts: BTreeMap = bridge_accounts_generator(); +// pub BridgeAccountOtherToken: AccountId32 = +// SygmaBridgePalletId::get().into_sub_account_truncating(1u32); // BridgeAccounts is a list of +// accounts for holding transferred asset collection pub BridgeAccounts: BTreeMap = bridge_accounts_generator(); // // EIP712ChainID is the chainID that pallet is assigned with, used in EIP712 typed data domain // // For local testing with ./scripts/sygma-setup/execute_proposal_test.js, please change it to 5 // pub EIP712ChainID: ChainID = U256::from(3799); -// // DestVerifyingContractAddress is a H160 address that is used in proposal signature verification, specifically EIP712 typed data -// // When relayers signing, this address will be included in the EIP712Domain -// // As long as the relayer and pallet configured with the same address, EIP712Domain should be recognized properly. -// pub DestVerifyingContractAddress: VerifyingContractAddress = primitive_types::H160::from_slice(hex::decode(DEST_VERIFYING_CONTRACT_ADDRESS).ok().unwrap().as_slice()); +// // DestVerifyingContractAddress is a H160 address that is used in proposal signature +// verification, specifically EIP712 typed data // When relayers signing, this address will be +// included in the EIP712Domain // As long as the relayer and pallet configured with the same +// address, EIP712Domain should be recognized properly. pub DestVerifyingContractAddress: +// VerifyingContractAddress = +// primitive_types::H160::from_slice(hex::decode(DEST_VERIFYING_CONTRACT_ADDRESS).ok().unwrap(). +// as_slice()); // pub CheckingAccount: AccountId32 = AccountId32::new([102u8; 32]); @@ -1710,8 +1714,8 @@ impl pallet_multi_asset_delegation::Config for Runtime { // (PHALocation::get().into(), PHAResourceId::get()), // ]; -// pub AssetDecimalPairs: Vec<(XcmAssetId, u8)> = vec![(NativeLocation::get().into(), 18u8), (SygUSDLocation::get().into(), 6u8), (PHALocation::get().into(), 12u8)]; -// } +// pub AssetDecimalPairs: Vec<(XcmAssetId, u8)> = vec![(NativeLocation::get().into(), 18u8), +// (SygUSDLocation::get().into(), 6u8), (PHALocation::get().into(), 12u8)]; } // pub struct ReserveChecker; // impl ContainsPair for ReserveChecker { From a46de410254731ab8d5243ff48330782137b3b38 Mon Sep 17 00:00:00 2001 From: Drew Stone Date: Sat, 30 Nov 2024 22:31:29 -0700 Subject: [PATCH 2/9] chore: remove account-util, not needed in project --- Cargo.lock | 13 ------ Cargo.toml | 1 - account-util/Cargo.toml | 18 -------- account-util/src/lib.rs | 91 ----------------------------------------- 4 files changed, 123 deletions(-) delete mode 100644 account-util/Cargo.toml delete mode 100644 account-util/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 3e1b252e1..149956621 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12,19 +12,6 @@ dependencies = [ "regex", ] -[[package]] -name = "account-util" -version = "1.2.3" -dependencies = [ - "frame-support", - "pallet-airdrop-claims", - "pallet-vesting", - "sp-core", - "sp-runtime", - "sp-std", - "tangle-primitives", -] - [[package]] name = "addchain" version = "0.2.0" diff --git a/Cargo.toml b/Cargo.toml index e20877f0f..a4437160a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,6 @@ exclude = ["examples"] [workspace] members = [ - "account-util", "primitives", "primitives/crypto", "primitives/rpc/*", diff --git a/account-util/Cargo.toml b/account-util/Cargo.toml deleted file mode 100644 index acefeeb63..000000000 --- a/account-util/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "account-util" -version.workspace = true -authors.workspace = true -edition.workspace = true -license.workspace = true -homepage.workspace = true -repository.workspace = true -exclude.workspace = true - -[dependencies] -frame-support = { workspace = true, features = ["std"] } -sp-core = { workspace = true, features = ["std"] } -sp-runtime = { workspace = true, features = ["std"] } -sp-std = { workspace = true, features = ["std"] } -pallet-airdrop-claims = { workspace = true, features = ["std"] } -pallet-vesting = { workspace = true, features = ["std"] } -tangle-primitives = { workspace = true, features = ["std"] } \ No newline at end of file diff --git a/account-util/src/lib.rs b/account-util/src/lib.rs deleted file mode 100644 index 61afd7b7e..000000000 --- a/account-util/src/lib.rs +++ /dev/null @@ -1,91 +0,0 @@ -use core::str::FromStr; -use frame_support::{pallet_prelude::*, traits::OnRuntimeUpgrade}; -use pallet_airdrop_claims::MultiAddress; -use pallet_vesting::{Vesting, VestingInfo}; -use sp_core::H160; -use sp_runtime::{ - traits::{AccountIdConversion, Zero}, - AccountId32, -}; -use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; -use tangle_primitives::{AccountId, Balance}; - -pub const BLOCK_TIME: u128 = 6; -pub const ONE_YEAR_BLOCKS: u64 = (365 * 24 * 60 * 60 / BLOCK_TIME) as u64; - -pub const INVESTOR_ACCOUNTS: [(&str, Balance); 29] = [ - ("5FCviiKcJzVfdwqv451JRQc93ZTSbbC9YfgKMkN3LpNMBjS3", 100000000000000000000000), - ("0xC02ad7b9a9121fc849196E844DC869D2250DF3A6", 150000000000000000000000), - ("5HBKM8XL7sr7S7qx6ukugDJUBhm16Ubnz1KuJCdHmHQvtc7Z", 400000000000000000000000), - ("0x86f99feff4cd3268ccefc760a6bbce2e07aa4d8e", 100000000000000000000000), - ("5HCJQLeQqCf64C6uy7CSoTND35QNdi1zU66TTM6QPCG9u9BB", 500000000000000000000000), - ("5DhQMPP69vRBNvZ6w4E9qii1yj56M66YXuPkkvz12yvn5ufN", 2750000000000000000000000), - ("0x17B74Dcf1E422AF5964056eB836321aE7A820035", 200000000000000000000000), - ("5Df1Sec4ZmeidskuuPtpt4SSCL6U5St19fsv4sBAwvkwmvin", 100000000000000000000000), - ("5FerzxKQZoP9wxjRhS1PHA4v27aPQMoZpXmufcQk1JYE5xU8", 100000000000000000000000), - ("0x75afaece8cf2a7974b1e541648923afd9339b3f8", 150000000000000000000000), - ("0x5a82d0bad9995b1bfa71de79b5e524decb5bee1c", 1000000000000000000000000), - ("5Cf5SfzngS9T9fdQSsKt1GJ42BQPP7FqU4trLwgkDD1ZVBN7", 20000000000000000000000), - ("0x5da7351A4Cb03c33e11F51841bc614d985812821", 20000000000000000000000), - ("5DDTvr7P2MaUirj3rSvpcF5DLxECiAqpQegdVCzAuwxingVC", 50000000000000000000000), - ("5CXkTTyNzVuE2fwNBzSwmmtcCntnun5vMDx6Wnn5VjopGUVx", 160000000000000000000000), - ("5G9Ji4EEiTehMKa9Nfe2rGozZB3XEyRtyvJWt2wYLMRYyAyn", 180000000000000000000000), - ("5EZcQuvjvuv1K4Ugg2ofLEhAC3NXPbaCAytPR3hmUqBv1Bhe", 200000000000000000000000), - ("5Fe8pwn27TNBuM1Agz1ivCMykX795woPQkjwiWD4UoSndmQj", 220000000000000000000000), - ("5HWLv9RvMSZ6FwuQswHCo1nmYxmAqRutqh37Vapx3pmXbVU3", 240000000000000000000000), - ("5ENgRjBQue32ppyLw1u55Rbe36gDWTJgZmcbSfZwrJAyt2tZ", 781850000000000000000000), - ("5DhzryWQpJTQfdauBf7yGKpr6LW42ye4oYvEYiVbMcGN7GZt", 879590000000000000000000), - ("5C52zXiWq7BM5x55soCudf8daW12NTLtMfisBiYd5Pov1Hw1", 977320000000000000000000), - ("5HbRuwKiUw4g7yh9iNBQ6zFG63sgZyGoZ4ep61CqMYTzk4gU", 1075050000000000000000000), - ("5HnQ2onP12Vhv3dVUvmKocbWr5sMjunCmjt2MmtxMr5z5dp1", 1172780000000000000000000), - ("5CAbD6BFcATxi9jVpixNtsLKovQy6RWQMQynHtapqAtKL8vT", 338150000000000000000000), - ("5DP7RmWdPD6TWbTNgBu6iKzYsm95fHETXyy5tQvEmS6zDhPn", 380410000000000000000000), - ("5EyDntnRYxgWLuHFRmSnirioDNpMDCUTQ4bwRYV3LGHQoMxo", 422680000000000000000000), - ("5DkNqZs22mLYXKy7c2vrtstqbcQBU1ArPKw51xvC37eGsuNP", 464950000000000000000000), - ("5CQJt5A7GmEUhh7S3MtaiBGvNRTY6PFw6KHJFcTVD4ZxBty7", 507220000000000000000000), -]; - -pub const TEAM_ACCOUNT_TO_UPDATE: [(&str, Balance); 1] = - [("5FH32Ro5cTpLE1FhP3skdi16UuVariyzoQfyK7vvjE2CHEtX", 28721849310000000043843584)]; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_decoding_accounts_into_account_id_32_bytes() { - for (address, _) in INVESTOR_ACCOUNTS { - let account_id = if address.starts_with("0x") { - MultiAddress::EVM( - H160::from_str(address).expect("should be a valid address").into(), - ) - .to_account_id_32() - } else { - let account = MultiAddress::Native( - AccountId32::from_str(address).expect("should be a valid address"), - ) - .to_account_id_32(); - - assert_eq!( - account, - AccountId32::from_str(address).expect("should be a valid address") - ); - - account - }; - - let account_id_bytes: [u8; 32] = account_id.into(); - println!("{:?}", account_id_bytes); - } - - for (address, _) in TEAM_ACCOUNT_TO_UPDATE { - let account_id = MultiAddress::Native( - AccountId32::from_str(address).expect("should be a valid address"), - ) - .to_account_id_32(); - - let account_id_bytes: [u8; 32] = account_id.into(); - println!("{:?}", account_id_bytes); - } - } -} From 1479b65dde3019de953d0f4898f1dcd4063da57f Mon Sep 17 00:00:00 2001 From: Drew Stone Date: Sat, 30 Nov 2024 22:32:04 -0700 Subject: [PATCH 3/9] chore: fix fmt --- runtime/mainnet/src/frontier_evm.rs | 13 +++++++------ runtime/mainnet/src/lib.rs | 26 ++++++++++++++------------ runtime/testnet/src/lib.rs | 26 ++++++++++++++------------ 3 files changed, 35 insertions(+), 30 deletions(-) diff --git a/runtime/mainnet/src/frontier_evm.rs b/runtime/mainnet/src/frontier_evm.rs index e415fb75c..38d046f19 100644 --- a/runtime/mainnet/src/frontier_evm.rs +++ b/runtime/mainnet/src/frontier_evm.rs @@ -119,20 +119,21 @@ impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType { ) -> precompile_utils::EvmResult { Ok(match self { ProxyType::Any => true, - ProxyType::Governance => - call.value == U256::zero() && - matches!( + ProxyType::Governance => { + call.value == U256::zero() + && matches!( PrecompileName::from_address(call.to.0), Some(ref precompile) if is_governance_precompile(precompile) - ), + ) + }, // The proxy precompile does not contain method cancel_proxy ProxyType::CancelProxy => false, ProxyType::Balances => { // Allow only "simple" accounts as recipient (no code nor precompile). // Note: Checking the presence of the code is not enough because some precompiles // have no code. - !recipient_has_code && - !precompile_utils::precompile_set::is_precompile_or_fail::( + !recipient_has_code + && !precompile_utils::precompile_set::is_precompile_or_fail::( call.to.0, gas, )? }, diff --git a/runtime/mainnet/src/lib.rs b/runtime/mainnet/src/lib.rs index f287cf6e7..120ff186d 100644 --- a/runtime/mainnet/src/lib.rs +++ b/runtime/mainnet/src/lib.rs @@ -656,8 +656,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) - .expect("input is padded with zeroes; qed") % - max.saturating_add(1); + .expect("input is padded with zeroes; qed") + % max.saturating_add(1); random as usize }, }; @@ -1148,15 +1148,15 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances(..) | - RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) + RuntimeCall::Balances(..) + | RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) ), ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) | - RuntimeCall::Council(..) | - RuntimeCall::Elections(..) | - RuntimeCall::Treasury(..) + RuntimeCall::Democracy(..) + | RuntimeCall::Council(..) + | RuntimeCall::Elections(..) + | RuntimeCall::Treasury(..) ), ProxyType::Staking => { matches!(c, RuntimeCall::Staking(..)) @@ -1465,8 +1465,9 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => - call.pre_dispatch_self_contained(info, dispatch_info, len), + RuntimeCall::Ethereum(call) => { + call.pre_dispatch_self_contained(info, dispatch_info, len) + }, _ => None, } } @@ -1476,10 +1477,11 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), - ))), + ))) + }, _ => None, } } diff --git a/runtime/testnet/src/lib.rs b/runtime/testnet/src/lib.rs index be3080a3b..2c1695cf0 100644 --- a/runtime/testnet/src/lib.rs +++ b/runtime/testnet/src/lib.rs @@ -663,8 +663,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) - .expect("input is padded with zeroes; qed") % - max.saturating_add(1); + .expect("input is padded with zeroes; qed") + % max.saturating_add(1); random as usize }, }; @@ -1146,15 +1146,15 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances(..) | - RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) + RuntimeCall::Balances(..) + | RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) ), ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) | - RuntimeCall::Council(..) | - RuntimeCall::Elections(..) | - RuntimeCall::Treasury(..) + RuntimeCall::Democracy(..) + | RuntimeCall::Council(..) + | RuntimeCall::Elections(..) + | RuntimeCall::Treasury(..) ), ProxyType::Staking => { matches!(c, RuntimeCall::Staking(..)) @@ -1387,8 +1387,9 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => - call.pre_dispatch_self_contained(info, dispatch_info, len), + RuntimeCall::Ethereum(call) => { + call.pre_dispatch_self_contained(info, dispatch_info, len) + }, _ => None, } } @@ -1398,10 +1399,11 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), - ))), + ))) + }, _ => None, } } From 4cb5dec1c3d196c632ddda3b8035c1a0af63aa2e Mon Sep 17 00:00:00 2001 From: Drew Stone Date: Mon, 2 Dec 2024 10:49:49 -0700 Subject: [PATCH 4/9] chore: clippy fix --- .../evm-tracing/src/formatters/blockscout.rs | 12 +-- .../evm-tracing/src/formatters/call_tracer.rs | 31 +++---- client/evm-tracing/src/formatters/raw.rs | 3 +- .../src/formatters/trace_filter.rs | 28 +++---- client/evm-tracing/src/listeners/call_list.rs | 81 ++++++++----------- client/evm-tracing/src/listeners/raw.rs | 7 +- client/rpc-core/txpool/src/types/content.rs | 15 ++-- client/rpc/debug/src/lib.rs | 58 +++++-------- client/rpc/trace/src/lib.rs | 45 +++++------ frost/frost-ristretto255/src/lib.rs | 5 +- frost/src/round1.rs | 6 +- frost/src/signature.rs | 4 +- node/src/distributions/mainnet.rs | 36 ++++----- node/src/manual_seal.rs | 25 +++--- node/src/service.rs | 8 +- pallets/claims/src/lib.rs | 5 +- pallets/claims/src/mock.rs | 3 +- pallets/claims/src/utils/mod.rs | 5 +- .../src/functions/delegate.rs | 15 ++-- .../src/functions/deposit.rs | 6 +- .../src/functions/operator.rs | 16 ++-- pallets/multi-asset-delegation/src/lib.rs | 12 +-- .../src/tests/operator.rs | 6 +- pallets/multi-asset-delegation/src/traits.rs | 8 +- pallets/services/rpc/src/lib.rs | 10 +-- pallets/services/src/functions.rs | 59 +++++++------- pallets/services/src/impls.rs | 3 +- pallets/services/src/lib.rs | 30 ++++--- pallets/services/src/mock.rs | 8 +- pallets/services/src/mock_evm.rs | 10 +-- pallets/services/src/tests.rs | 8 +- pallets/tangle-lst/benchmarking/src/inner.rs | 6 +- pallets/tangle-lst/benchmarking/src/mock.rs | 32 +++----- pallets/tangle-lst/src/lib.rs | 37 ++++----- pallets/tangle-lst/src/mock.rs | 9 +-- pallets/tangle-lst/src/tests.rs | 5 +- pallets/tangle-lst/src/tests/bonded_pool.rs | 3 +- pallets/tangle-lst/src/tests/create.rs | 4 +- pallets/tangle-lst/src/tests/update_roles.rs | 4 +- pallets/tangle-lst/src/types/bonded_pool.rs | 10 +-- pallets/tangle-lst/src/types/commission.rs | 2 +- precompiles/assets-erc20/src/lib.rs | 4 +- precompiles/assets-erc20/src/tests.rs | 4 +- precompiles/assets/src/lib.rs | 9 ++- precompiles/assets/src/mock.rs | 3 +- precompiles/balances-erc20/src/eip2612.rs | 3 +- precompiles/balances-erc20/src/lib.rs | 2 +- precompiles/balances-erc20/src/mock.rs | 15 ++-- precompiles/balances-erc20/src/tests.rs | 4 +- precompiles/batch/src/lib.rs | 40 ++++----- precompiles/batch/src/mock.rs | 3 +- precompiles/call-permit/src/lib.rs | 5 +- precompiles/call-permit/src/mock.rs | 3 +- .../multi-asset-delegation/src/mock.rs | 3 +- .../multi-asset-delegation/src/tests.rs | 8 +- precompiles/pallet-democracy/src/mock.rs | 3 +- precompiles/pallet-democracy/src/tests.rs | 36 ++++----- precompiles/precompile-registry/src/lib.rs | 5 +- precompiles/precompile-registry/src/mock.rs | 3 +- precompiles/preimage/src/mock.rs | 3 +- precompiles/proxy/src/lib.rs | 21 +++-- precompiles/proxy/src/mock.rs | 5 +- precompiles/services/src/lib.rs | 10 +-- precompiles/services/src/mock.rs | 10 +-- precompiles/services/src/mock_evm.rs | 17 ++-- precompiles/services/src/tests.rs | 39 ++++----- precompiles/staking/src/mock.rs | 3 +- precompiles/tangle-lst/src/lib.rs | 23 +++--- precompiles/tangle-lst/src/mock.rs | 23 +++--- .../verify-bls381-signature/src/mock.rs | 3 +- .../src/mock.rs | 3 +- .../src/mock.rs | 3 +- .../verify-ecdsa-stark-signature/src/mock.rs | 3 +- .../verify-schnorr-signatures/src/mock.rs | 3 +- primitives/rpc/evm-tracing-events/src/evm.rs | 20 ++--- .../rpc/evm-tracing-events/src/gasometer.rs | 20 ++--- .../rpc/evm-tracing-events/src/runtime.rs | 15 ++-- primitives/src/chain_identifier.rs | 16 ++-- primitives/src/services/field.rs | 16 ++-- primitives/src/services/mod.rs | 22 ++--- runtime/mainnet/src/frontier_evm.rs | 13 ++- runtime/mainnet/src/lib.rs | 26 +++--- runtime/testnet/src/lib.rs | 26 +++--- rust-toolchain.toml | 2 +- 84 files changed, 524 insertions(+), 654 deletions(-) diff --git a/client/evm-tracing/src/formatters/blockscout.rs b/client/evm-tracing/src/formatters/blockscout.rs index fa8611bb8..61b8033e2 100644 --- a/client/evm-tracing/src/formatters/blockscout.rs +++ b/client/evm-tracing/src/formatters/blockscout.rs @@ -14,11 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see . -use crate::listeners::call_list::Listener; -use crate::types::serialization::*; -use crate::types::{ - single::{Call, TransactionTrace}, - CallResult, CallType, CreateResult, +use crate::{ + listeners::call_list::Listener, + types::{ + serialization::*, + single::{Call, TransactionTrace}, + CallResult, CallType, CreateResult, + }, }; use ethereum_types::{H160, U256}; use parity_scale_codec::{Decode, Encode}; diff --git a/client/evm-tracing/src/formatters/call_tracer.rs b/client/evm-tracing/src/formatters/call_tracer.rs index b0451b0bd..165d79c3c 100644 --- a/client/evm-tracing/src/formatters/call_tracer.rs +++ b/client/evm-tracing/src/formatters/call_tracer.rs @@ -56,14 +56,13 @@ impl super::ResponseFormatter for Formatter { gas_used, trace_address: Some(trace_address.clone()), inner: match inner.clone() { - BlockscoutCallInner::Call { input, to, res, call_type } => { + BlockscoutCallInner::Call { input, to, res, call_type } => CallTracerInner::Call { call_type: match call_type { CallType::Call => "CALL".as_bytes().to_vec(), CallType::CallCode => "CALLCODE".as_bytes().to_vec(), - CallType::DelegateCall => { - "DELEGATECALL".as_bytes().to_vec() - }, + CallType::DelegateCall => + "DELEGATECALL".as_bytes().to_vec(), CallType::StaticCall => "STATICCALL".as_bytes().to_vec(), }, to, @@ -74,8 +73,7 @@ impl super::ResponseFormatter for Formatter { CallResult::Output { .. } => it.logs.clone(), CallResult::Error { .. } => Vec::new(), }, - } - }, + }, BlockscoutCallInner::Create { init, res } => CallTracerInner::Create { input: init, error: match res { @@ -89,21 +87,19 @@ impl super::ResponseFormatter for Formatter { CreateResult::Error { .. } => None, }, output: match res { - CreateResult::Success { created_contract_code, .. } => { - Some(created_contract_code) - }, + CreateResult::Success { created_contract_code, .. } => + Some(created_contract_code), CreateResult::Error { .. } => None, }, value, call_type: "CREATE".as_bytes().to_vec(), }, - BlockscoutCallInner::SelfDestruct { balance, to } => { + BlockscoutCallInner::SelfDestruct { balance, to } => CallTracerInner::SelfDestruct { value: balance, to, call_type: "SELFDESTRUCT".as_bytes().to_vec(), - } - }, + }, }, calls: Vec::new(), }) @@ -154,7 +150,7 @@ impl super::ResponseFormatter for Formatter { // // We consider an item to be `Ordering::Less` when: // - Is closer to the root or - // - Is greater than its sibling. + // - Is greater than its sibling. result.sort_by(|a, b| match (a, b) { ( Call::CallTracer(CallTracerCall { trace_address: Some(a), .. }), @@ -193,11 +189,10 @@ impl super::ResponseFormatter for Formatter { ( Call::CallTracer(CallTracerCall { trace_address: Some(a), .. }), Call::CallTracer(CallTracerCall { trace_address: Some(b), .. }), - ) => { - &b[..] - == a.get(0..a.len() - 1) - .expect("non-root element while traversing trace result") - }, + ) => + &b[..] == + a.get(0..a.len() - 1) + .expect("non-root element while traversing trace result"), _ => unreachable!(), }) { // Remove `trace_address` from result. diff --git a/client/evm-tracing/src/formatters/raw.rs b/client/evm-tracing/src/formatters/raw.rs index d3588e2fe..30e352427 100644 --- a/client/evm-tracing/src/formatters/raw.rs +++ b/client/evm-tracing/src/formatters/raw.rs @@ -14,8 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see . -use crate::listeners::raw::Listener; -use crate::types::single::TransactionTrace; +use crate::{listeners::raw::Listener, types::single::TransactionTrace}; pub struct Formatter; diff --git a/client/evm-tracing/src/formatters/trace_filter.rs b/client/evm-tracing/src/formatters/trace_filter.rs index 12266cb7e..f8844c8fd 100644 --- a/client/evm-tracing/src/formatters/trace_filter.rs +++ b/client/evm-tracing/src/formatters/trace_filter.rs @@ -15,12 +15,15 @@ // along with Moonbeam. If not, see . use super::blockscout::BlockscoutCallInner as CallInner; -use crate::listeners::call_list::Listener; -use crate::types::{ - block::{ - TransactionTrace, TransactionTraceAction, TransactionTraceOutput, TransactionTraceResult, +use crate::{ + listeners::call_list::Listener, + types::{ + block::{ + TransactionTrace, TransactionTraceAction, TransactionTraceOutput, + TransactionTraceResult, + }, + CallResult, CreateResult, CreateType, }, - CallResult, CreateResult, CreateType, }; use ethereum_types::H256; @@ -53,12 +56,11 @@ impl super::ResponseFormatter for Formatter { // Can't be known here, must be inserted upstream. block_number: 0, output: match res { - CallResult::Output(output) => { + CallResult::Output(output) => TransactionTraceOutput::Result(TransactionTraceResult::Call { gas_used: trace.gas_used, output, - }) - }, + }), CallResult::Error(error) => TransactionTraceOutput::Error(error), }, subtraces: trace.subtraces, @@ -84,16 +86,14 @@ impl super::ResponseFormatter for Formatter { CreateResult::Success { created_contract_address_hash, created_contract_code, - } => { + } => TransactionTraceOutput::Result(TransactionTraceResult::Create { gas_used: trace.gas_used, code: created_contract_code, address: created_contract_address_hash, - }) - }, - CreateResult::Error { error } => { - TransactionTraceOutput::Error(error) - }, + }), + CreateResult::Error { error } => + TransactionTraceOutput::Error(error), }, subtraces: trace.subtraces, trace_address: trace.trace_address.clone(), diff --git a/client/evm-tracing/src/listeners/call_list.rs b/client/evm-tracing/src/listeners/call_list.rs index dac7c1fb7..5ca1eb15e 100644 --- a/client/evm-tracing/src/listeners/call_list.rs +++ b/client/evm-tracing/src/listeners/call_list.rs @@ -14,9 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Moonbeam. If not, see . -use crate::formatters::blockscout::BlockscoutCall as Call; -use crate::formatters::blockscout::BlockscoutCallInner as CallInner; -use crate::types::{single::Log, CallResult, CallType, ContextType, CreateResult}; +use crate::{ + formatters::blockscout::{BlockscoutCall as Call, BlockscoutCallInner as CallInner}, + types::{single::Log, CallResult, CallType, ContextType, CreateResult}, +}; use ethereum_types::{H160, U256}; use evm_tracing_events::{ runtime::{Capture, ExitError, ExitReason, ExitSucceed}, @@ -223,9 +224,9 @@ impl Listener { pub fn gasometer_event(&mut self, event: GasometerEvent) { match event { - GasometerEvent::RecordCost { snapshot, .. } - | GasometerEvent::RecordDynamicCost { snapshot, .. } - | GasometerEvent::RecordStipend { snapshot, .. } => { + GasometerEvent::RecordCost { snapshot, .. } | + GasometerEvent::RecordDynamicCost { snapshot, .. } | + GasometerEvent::RecordStipend { snapshot, .. } => { if let Some(context) = self.context_stack.last_mut() { if context.start_gas.is_none() { context.start_gas = Some(snapshot.gas()); @@ -496,13 +497,12 @@ impl Listener { // behavior (like batch precompile does) thus we simply consider this a call. self.call_type = Some(CallType::Call); }, - EvmEvent::Log { address, topics, data } => { + EvmEvent::Log { address, topics, data } => if self.with_log { if let Some(stack) = self.context_stack.last_mut() { stack.logs.push(Log { address, topics, data }); } - } - }, + }, // We ignore other kinds of message if any (new ones may be added in the future). #[allow(unreachable_patterns)] @@ -536,15 +536,13 @@ impl Listener { match context.context_type { ContextType::Call(call_type) => { let res = match &reason { - ExitReason::Succeed(ExitSucceed::Returned) => { - CallResult::Output(return_value.to_vec()) - }, + ExitReason::Succeed(ExitSucceed::Returned) => + CallResult::Output(return_value.to_vec()), ExitReason::Succeed(_) => CallResult::Output(vec![]), ExitReason::Error(error) => CallResult::Error(error_message(error)), - ExitReason::Revert(_) => { - CallResult::Error(b"execution reverted".to_vec()) - }, + ExitReason::Revert(_) => + CallResult::Error(b"execution reverted".to_vec()), ExitReason::Fatal(_) => CallResult::Error(vec![]), }; @@ -570,12 +568,10 @@ impl Listener { created_contract_address_hash: context.to, created_contract_code: return_value.to_vec(), }, - ExitReason::Error(error) => { - CreateResult::Error { error: error_message(error) } - }, - ExitReason::Revert(_) => { - CreateResult::Error { error: b"execution reverted".to_vec() } - }, + ExitReason::Error(error) => + CreateResult::Error { error: error_message(error) }, + ExitReason::Revert(_) => + CreateResult::Error { error: b"execution reverted".to_vec() }, ExitReason::Fatal(_) => CreateResult::Error { error: vec![] }, }; @@ -624,15 +620,14 @@ impl ListenerT for Listener { Event::Gasometer(gasometer_event) => self.gasometer_event(gasometer_event), Event::Runtime(runtime_event) => self.runtime_event(runtime_event), Event::Evm(evm_event) => self.evm_event(evm_event), - Event::CallListNew() => { + Event::CallListNew() => if !self.call_list_first_transaction { self.finish_transaction(); self.skip_next_context = false; self.entries.push(BTreeMap::new()); } else { self.call_list_first_transaction = false; - } - }, + }, }; } @@ -731,9 +726,8 @@ mod tests { target: H160::default(), balance: U256::zero(), }, - TestEvmEvent::Exit => { - EvmEvent::Exit { reason: exit_reason.unwrap(), return_value: Vec::new() } - }, + TestEvmEvent::Exit => + EvmEvent::Exit { reason: exit_reason.unwrap(), return_value: Vec::new() }, TestEvmEvent::TransactCall => EvmEvent::TransactCall { caller: H160::default(), address: H160::default(), @@ -756,9 +750,8 @@ mod tests { gas_limit: 0u64, address: H160::default(), }, - TestEvmEvent::Log => { - EvmEvent::Log { address: H160::default(), topics: Vec::new(), data: Vec::new() } - }, + TestEvmEvent::Log => + EvmEvent::Log { address: H160::default(), topics: Vec::new(), data: Vec::new() }, } } @@ -771,9 +764,8 @@ mod tests { stack: test_stack(), memory: test_memory(), }, - TestRuntimeEvent::StepResult => { - RuntimeEvent::StepResult { result: Ok(()), return_value: Vec::new() } - }, + TestRuntimeEvent::StepResult => + RuntimeEvent::StepResult { result: Ok(()), return_value: Vec::new() }, TestRuntimeEvent::SLoad => RuntimeEvent::SLoad { address: H160::default(), index: H256::default(), @@ -789,24 +781,20 @@ mod tests { fn test_emit_gasometer_event(event_type: TestGasometerEvent) -> GasometerEvent { match event_type { - TestGasometerEvent::RecordCost => { - GasometerEvent::RecordCost { cost: 0u64, snapshot: test_snapshot() } - }, - TestGasometerEvent::RecordRefund => { - GasometerEvent::RecordRefund { refund: 0i64, snapshot: test_snapshot() } - }, - TestGasometerEvent::RecordStipend => { - GasometerEvent::RecordStipend { stipend: 0u64, snapshot: test_snapshot() } - }, + TestGasometerEvent::RecordCost => + GasometerEvent::RecordCost { cost: 0u64, snapshot: test_snapshot() }, + TestGasometerEvent::RecordRefund => + GasometerEvent::RecordRefund { refund: 0i64, snapshot: test_snapshot() }, + TestGasometerEvent::RecordStipend => + GasometerEvent::RecordStipend { stipend: 0u64, snapshot: test_snapshot() }, TestGasometerEvent::RecordDynamicCost => GasometerEvent::RecordDynamicCost { gas_cost: 0u64, memory_gas: 0u64, gas_refund: 0i64, snapshot: test_snapshot(), }, - TestGasometerEvent::RecordTransaction => { - GasometerEvent::RecordTransaction { cost: 0u64, snapshot: test_snapshot() } - }, + TestGasometerEvent::RecordTransaction => + GasometerEvent::RecordTransaction { cost: 0u64, snapshot: test_snapshot() }, } } @@ -1094,7 +1082,8 @@ mod tests { listener.finish_transaction(); assert_eq!(listener.entries.len(), 1); // Each nested call contains 11 elements in the callstack (main + 10 subcalls). - // There are 5 main nested calls for a total of 56 elements in the callstack: 1 main + 55 nested. + // There are 5 main nested calls for a total of 56 elements in the callstack: 1 main + 55 + // nested. assert_eq!(listener.entries[0].len(), (depth * (subdepth + 1)) + 1); } diff --git a/client/evm-tracing/src/listeners/raw.rs b/client/evm-tracing/src/listeners/raw.rs index 180fd36e2..c4e7ac328 100644 --- a/client/evm-tracing/src/listeners/raw.rs +++ b/client/evm-tracing/src/listeners/raw.rs @@ -243,7 +243,8 @@ impl Listener { .global_storage_changes .insert(context.address, context.storage_cache); - // Apply storage changes to parent, either updating its cache or map of changes. + // Apply storage changes to parent, either updating its cache or + // map of changes. for (address, mut storage) in context.global_storage_changes.into_iter() { @@ -276,8 +277,8 @@ impl Listener { _ => (), } }, - RuntimeEvent::SLoad { address: _, index, value } - | RuntimeEvent::SStore { address: _, index, value } => { + RuntimeEvent::SLoad { address: _, index, value } | + RuntimeEvent::SStore { address: _, index, value } => { if let Some(context) = self.context_stack.last_mut() { if !self.disable_storage { context.storage_cache.insert(index, value); diff --git a/client/rpc-core/txpool/src/types/content.rs b/client/rpc-core/txpool/src/types/content.rs index ec98a00f4..581be1737 100644 --- a/client/rpc-core/txpool/src/types/content.rs +++ b/client/rpc-core/txpool/src/types/content.rs @@ -66,15 +66,12 @@ where impl GetT for Transaction { fn get(hash: H256, from_address: H160, txn: &EthereumTransaction) -> Self { let (nonce, action, value, gas_price, gas_limit, input) = match txn { - EthereumTransaction::Legacy(t) => { - (t.nonce, t.action, t.value, t.gas_price, t.gas_limit, t.input.clone()) - }, - EthereumTransaction::EIP2930(t) => { - (t.nonce, t.action, t.value, t.gas_price, t.gas_limit, t.input.clone()) - }, - EthereumTransaction::EIP1559(t) => { - (t.nonce, t.action, t.value, t.max_fee_per_gas, t.gas_limit, t.input.clone()) - }, + EthereumTransaction::Legacy(t) => + (t.nonce, t.action, t.value, t.gas_price, t.gas_limit, t.input.clone()), + EthereumTransaction::EIP2930(t) => + (t.nonce, t.action, t.value, t.gas_price, t.gas_limit, t.input.clone()), + EthereumTransaction::EIP1559(t) => + (t.nonce, t.action, t.value, t.max_fee_per_gas, t.gas_limit, t.input.clone()), }; Self { hash, diff --git a/client/rpc/debug/src/lib.rs b/client/rpc/debug/src/lib.rs index 09b2b932c..69301f4f8 100644 --- a/client/rpc/debug/src/lib.rs +++ b/client/rpc/debug/src/lib.rs @@ -353,15 +353,12 @@ where let reference_id: BlockId = match request_block_id { RequestBlockId::Number(n) => Ok(BlockId::Number(n.unique_saturated_into())), - RequestBlockId::Tag(RequestBlockTag::Latest) => { - Ok(BlockId::Number(client.info().best_number)) - }, - RequestBlockId::Tag(RequestBlockTag::Earliest) => { - Ok(BlockId::Number(0u32.unique_saturated_into())) - }, - RequestBlockId::Tag(RequestBlockTag::Pending) => { - Err(internal_err("'pending' blocks are not supported")) - }, + RequestBlockId::Tag(RequestBlockTag::Latest) => + Ok(BlockId::Number(client.info().best_number)), + RequestBlockId::Tag(RequestBlockTag::Earliest) => + Ok(BlockId::Number(0u32.unique_saturated_into())), + RequestBlockId::Tag(RequestBlockTag::Pending) => + Err(internal_err("'pending' blocks are not supported")), RequestBlockId::Hash(eth_hash) => { match futures::executor::block_on(frontier_backend_client::load_hash::( client.as_ref(), @@ -473,11 +470,10 @@ where proxy.using(f)?; proxy.finish_transaction(); let response = match tracer_input { - TracerInput::CallTracer => { + TracerInput::CallTracer => client_evm_tracing::formatters::CallTracer::format(proxy) .ok_or("Trace result is empty.") - .map_err(|e| internal_err(format!("{:?}", e))) - }, + .map_err(|e| internal_err(format!("{:?}", e))), _ => Err(internal_err("Bug: failed to resolve the tracer format.".to_string())), }?; @@ -612,20 +608,17 @@ where // Pre-london update, legacy transactions. match transaction { ethereum::TransactionV2::Legacy(tx) => - { #[allow(deprecated)] api.trace_transaction_before_version_4( parent_block_hash, exts, tx, - ) - }, - _ => { + ), + _ => return Err(internal_err( "Bug: pre-london runtime expects legacy transactions" .to_string(), - )) - }, + )), } } }; @@ -666,11 +659,10 @@ where proxy.using(f)?; proxy.finish_transaction(); let response = match tracer_input { - TracerInput::Blockscout => { + TracerInput::Blockscout => client_evm_tracing::formatters::Blockscout::format(proxy) .ok_or("Trace result is empty.") - .map_err(|e| internal_err(format!("{:?}", e))) - }, + .map_err(|e| internal_err(format!("{:?}", e))), TracerInput::CallTracer => { let mut res = client_evm_tracing::formatters::CallTracer::format(proxy) @@ -706,15 +698,12 @@ where let reference_id: BlockId = match request_block_id { RequestBlockId::Number(n) => Ok(BlockId::Number(n.unique_saturated_into())), - RequestBlockId::Tag(RequestBlockTag::Latest) => { - Ok(BlockId::Number(client.info().best_number)) - }, - RequestBlockId::Tag(RequestBlockTag::Earliest) => { - Ok(BlockId::Number(0u32.unique_saturated_into())) - }, - RequestBlockId::Tag(RequestBlockTag::Pending) => { - Err(internal_err("'pending' blocks are not supported")) - }, + RequestBlockId::Tag(RequestBlockTag::Latest) => + Ok(BlockId::Number(client.info().best_number)), + RequestBlockId::Tag(RequestBlockTag::Earliest) => + Ok(BlockId::Number(0u32.unique_saturated_into())), + RequestBlockId::Tag(RequestBlockTag::Pending) => + Err(internal_err("'pending' blocks are not supported")), RequestBlockId::Hash(eth_hash) => { match futures::executor::block_on(frontier_backend_client::load_hash::( client.as_ref(), @@ -751,9 +740,7 @@ where }; if trace_api_version <= 5 { - return Err(internal_err( - "debug_traceCall not supported with old runtimes".to_string(), - )); + return Err(internal_err("debug_traceCall not supported with old runtimes".to_string())); } let TraceCallParams { @@ -860,11 +847,10 @@ where proxy.using(f)?; proxy.finish_transaction(); let response = match tracer_input { - TracerInput::Blockscout => { + TracerInput::Blockscout => client_evm_tracing::formatters::Blockscout::format(proxy) .ok_or("Trace result is empty.") - .map_err(|e| internal_err(format!("{:?}", e))) - }, + .map_err(|e| internal_err(format!("{:?}", e))), TracerInput::CallTracer => { let mut res = client_evm_tracing::formatters::CallTracer::format(proxy) .ok_or("Trace result is empty.") diff --git a/client/rpc/trace/src/lib.rs b/client/rpc/trace/src/lib.rs index a62e17945..c950d3ffc 100644 --- a/client/rpc/trace/src/lib.rs +++ b/client/rpc/trace/src/lib.rs @@ -21,8 +21,8 @@ //! The implementation is composed of multiple tasks : //! - Many calls the RPC handler `Trace::filter`, communicating with the main task. //! - A main `CacheTask` managing the cache and the communication between tasks. -//! - For each traced block an async task responsible to wait for a permit, spawn a blocking -//! task and waiting for the result, then send it to the main `CacheTask`. +//! - For each traced block an async task responsible to wait for a permit, spawn a blocking task +//! and waiting for the result, then send it to the main `CacheTask`. use futures::{select, stream::FuturesUnordered, FutureExt, StreamExt}; use std::{collections::BTreeMap, future::Future, marker::PhantomData, sync::Arc, time::Duration}; @@ -100,9 +100,8 @@ where .try_into() .map_err(|_| "Block number overflow")?), Some(RequestBlockId::Tag(RequestBlockTag::Earliest)) => Ok(0), - Some(RequestBlockId::Tag(RequestBlockTag::Pending)) => { - Err("'pending' is not supported") - }, + Some(RequestBlockId::Tag(RequestBlockTag::Pending)) => + Err("'pending' is not supported"), Some(RequestBlockId::Hash(_)) => Err("Block hash not supported"), } } @@ -174,18 +173,15 @@ where let mut block_traces: Vec<_> = block_traces .iter() .filter(|trace| match trace.action { - block::TransactionTraceAction::Call { from, to, .. } => { - (from_address.is_empty() || from_address.contains(&from)) - && (to_address.is_empty() || to_address.contains(&to)) - }, - block::TransactionTraceAction::Create { from, .. } => { - (from_address.is_empty() || from_address.contains(&from)) - && to_address.is_empty() - }, - block::TransactionTraceAction::Suicide { address, .. } => { - (from_address.is_empty() || from_address.contains(&address)) - && to_address.is_empty() - }, + block::TransactionTraceAction::Call { from, to, .. } => + (from_address.is_empty() || from_address.contains(&from)) && + (to_address.is_empty() || to_address.contains(&to)), + block::TransactionTraceAction::Create { from, .. } => + (from_address.is_empty() || from_address.contains(&from)) && + to_address.is_empty(), + block::TransactionTraceAction::Suicide { address, .. } => + (from_address.is_empty() || from_address.contains(&address)) && + to_address.is_empty(), }) .cloned() .collect(); @@ -595,9 +591,9 @@ where /// Handle a request to get the traces of the provided block. /// - If the result is stored in the cache, it sends it immediatly. - /// - If the block is currently being pooled, it is added in this block cache waiting list, - /// and all requests concerning this block will be satisfied when the tracing for this block - /// is finished. + /// - If the block is currently being pooled, it is added in this block cache waiting list, and + /// all requests concerning this block will be satisfied when the tracing for this block is + /// finished. /// - If this block is missing from the cache, it means no batch asked for it. All requested /// blocks should be contained in a batch beforehand, and thus an error is returned. #[instrument(skip(self))] @@ -652,8 +648,8 @@ where // We remove early the block cache if this batch is the last // pooling this block. if let Some(block_cache) = self.cached_blocks.get_mut(block) { - if block_cache.active_batch_count == 1 - && matches!( + if block_cache.active_batch_count == 1 && + matches!( block_cache.state, CacheBlockState::Pooled { started: false, .. } ) { @@ -760,12 +756,11 @@ where overrides.current_transaction_statuses(substrate_hash), ) { (Some(a), Some(b)) => (a, b), - _ => { + _ => return Err(format!( "Failed to get Ethereum block data for Substrate block {}", substrate_hash - )) - }, + )), }; let eth_block_hash = eth_block.header.hash(); diff --git a/frost/frost-ristretto255/src/lib.rs b/frost/frost-ristretto255/src/lib.rs index a4d955fc5..a3322ef47 100644 --- a/frost/frost-ristretto255/src/lib.rs +++ b/frost/frost-ristretto255/src/lib.rs @@ -102,13 +102,12 @@ impl Group for RistrettoGroup { .map_err(|_| GroupError::MalformedElement)? .decompress() { - Some(point) => { + Some(point) => if point == RistrettoPoint::identity() { Err(GroupError::InvalidIdentityElement) } else { Ok(WrappedRistrettoPoint(point)) - } - }, + }, None => Err(GroupError::MalformedElement), } } diff --git a/frost/src/round1.rs b/frost/src/round1.rs index 54039c005..52f7d61af 100644 --- a/frost/src/round1.rs +++ b/frost/src/round1.rs @@ -106,9 +106,9 @@ where /// Checks if the commitments are valid. pub fn is_valid(&self) -> bool { - element_is_valid::(&self.hiding.0) - && element_is_valid::(&self.binding.0) - && self.hiding.0 != self.binding.0 + element_is_valid::(&self.hiding.0) && + element_is_valid::(&self.binding.0) && + self.hiding.0 != self.binding.0 } } diff --git a/frost/src/signature.rs b/frost/src/signature.rs index 5a1f89bef..78b8e3cf5 100644 --- a/frost/src/signature.rs +++ b/frost/src/signature.rs @@ -210,8 +210,8 @@ where lambda_i: Scalar, challenge: &Challenge, ) -> Result<(), Error> { - if (::generator() * self.share) - != (group_commitment_share.0 + (verifying_share.0 * challenge.0 * lambda_i)) + if (::generator() * self.share) != + (group_commitment_share.0 + (verifying_share.0 * challenge.0 * lambda_i)) { return Err(Error::InvalidSignatureShare); } diff --git a/node/src/distributions/mainnet.rs b/node/src/distributions/mainnet.rs index b11cd7357..e8b78cea1 100644 --- a/node/src/distributions/mainnet.rs +++ b/node/src/distributions/mainnet.rs @@ -633,16 +633,16 @@ fn test_distribution_shares() { ); // 0.95% // Test total claims - let total_claims = edgeware_genesis_list.claims.len() - + edgeware_snapshot_list.claims.len() - + polkadot_genesis_list.claims.len() - + leaderboard_genesis_list.claims.len(); + let total_claims = edgeware_genesis_list.claims.len() + + edgeware_snapshot_list.claims.len() + + polkadot_genesis_list.claims.len() + + leaderboard_genesis_list.claims.len(); assert_eq!(total_claims, 29452); - let total_vesting = edgeware_genesis_list.vesting.len() - + edgeware_snapshot_list.vesting.len() - + polkadot_genesis_list.vesting.len() - + leaderboard_genesis_list.vesting.len(); + let total_vesting = edgeware_genesis_list.vesting.len() + + edgeware_snapshot_list.vesting.len() + + polkadot_genesis_list.vesting.len() + + leaderboard_genesis_list.vesting.len(); assert_eq!(total_vesting, 29452); let unique_dist = crate::distributions::get_unique_distribution_results(vec![ @@ -674,16 +674,16 @@ fn test_distribution_shares() { // get_initial_endowed_accounts().0.into_iter().map(|(_, amount)| amount).sum(); // assert_eq!(total_endowmwnent - total_treasury_amount, 8900000000000000000000); // 8900 TNT - let total_genesis_endowment = total_investor_amount - + total_direct_team_amount - + foundation_total_amount - + total_edgeware_claims_amount - + total_edgeware_snapshot_claims_amount - + total_leaderboard_claims_amount - + total_polkadot_claims_amount - + total_treasury_amount - + 5000 * UNIT - + total_team_claims_amount; + let total_genesis_endowment = total_investor_amount + + total_direct_team_amount + + foundation_total_amount + + total_edgeware_claims_amount + + total_edgeware_snapshot_claims_amount + + total_leaderboard_claims_amount + + total_polkadot_claims_amount + + total_treasury_amount + + 5000 * UNIT + + total_team_claims_amount; //+ total_endowmwnent; assert_eq!(total_genesis_endowment, 100000000000000006345897383); // 100000000 TNT diff --git a/node/src/manual_seal.rs b/node/src/manual_seal.rs index 7eef5e9ac..f9f1b26cb 100644 --- a/node/src/manual_seal.rs +++ b/node/src/manual_seal.rs @@ -14,33 +14,30 @@ // limitations under the License. //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. -use crate::cli::Sealing; pub use crate::eth::{db_config_dir, EthConfiguration}; -use crate::eth::{ - new_frontier_partial, spawn_frontier_tasks, BackendType, EthApi, FrontierBackend, - FrontierBlockImport, FrontierPartialComponents, RpcConfig, StorageOverride, - StorageOverrideHandler, +use crate::{ + cli::Sealing, + eth::{ + new_frontier_partial, spawn_frontier_tasks, BackendType, EthApi, FrontierBackend, + FrontierBlockImport, FrontierPartialComponents, RpcConfig, StorageOverride, + StorageOverrideHandler, + }, }; -use futures::future; -use futures::FutureExt; -use futures::{channel::mpsc, prelude::*}; +use futures::{channel::mpsc, future, prelude::*, FutureExt}; use futures_timer::Delay; use sc_client_api::{Backend, BlockBackend}; use sc_consensus::BasicQueue; -use sc_consensus_babe::BabeLink; -use sc_consensus_babe::{BabeWorkerHandle, SlotProportion}; +use sc_consensus_babe::{BabeLink, BabeWorkerHandle, SlotProportion}; use sc_consensus_grandpa::SharedVoterState; #[allow(deprecated)] pub use sc_executor::NativeElseWasmExecutor; use sc_service::{error::Error as ServiceError, ChainType, Configuration, TaskManager}; -use sc_telemetry::TelemetryHandle; -use sc_telemetry::{Telemetry, TelemetryWorker}; +use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker}; use sc_transaction_pool::FullPool; use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_core::U256; use sp_runtime::traits::Block as BlockT; -use std::cell::RefCell; -use std::{path::Path, sync::Arc, time::Duration}; +use std::{cell::RefCell, path::Path, sync::Arc, time::Duration}; use substrate_prometheus_endpoint::Registry; use tangle_primitives::Block; diff --git a/node/src/service.rs b/node/src/service.rs index d0649d03d..e7895f377 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -308,8 +308,8 @@ pub async fn new_full Pallet { statement: Vec, ) -> Result> { let signer = match signature { - MultiAddressSignature::EVM(ethereum_signature) => { + MultiAddressSignature::EVM(ethereum_signature) => Self::eth_recover(ðereum_signature, &data, &statement[..]) - .ok_or(Error::::InvalidEthereumSignature)? - }, + .ok_or(Error::::InvalidEthereumSignature)?, MultiAddressSignature::Native(sr25519_signature) => { ensure!(!signer.is_none(), Error::::InvalidNativeAccount); Self::sr25519_recover(signer.unwrap(), &sr25519_signature, &data, &statement[..]) diff --git a/pallets/claims/src/mock.rs b/pallets/claims/src/mock.rs index 3949bf553..4cedf8ad7 100644 --- a/pallets/claims/src/mock.rs +++ b/pallets/claims/src/mock.rs @@ -6,9 +6,8 @@ use sp_std::convert::TryFrom; // The testing primitives are very useful for avoiding having to work with signatures // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use crate::{pallet as pallet_airdrop_claims, sr25519_utils::sub, tests::get_bounded_vec}; -use frame_support::derive_impl; use frame_support::{ - ord_parameter_types, parameter_types, + derive_impl, ord_parameter_types, parameter_types, traits::{OnFinalize, OnInitialize, WithdrawReasons}, }; use pallet_balances; diff --git a/pallets/claims/src/utils/mod.rs b/pallets/claims/src/utils/mod.rs index a387457fc..f25596857 100644 --- a/pallets/claims/src/utils/mod.rs +++ b/pallets/claims/src/utils/mod.rs @@ -45,9 +45,8 @@ impl Hash for MultiAddress { impl MultiAddress { pub fn to_account_id_32(&self) -> AccountId32 { match self { - MultiAddress::EVM(ethereum_address) => { - HashedAddressMapping::::into_account_id(H160::from(ethereum_address.0)) - }, + MultiAddress::EVM(ethereum_address) => + HashedAddressMapping::::into_account_id(H160::from(ethereum_address.0)), MultiAddress::Native(substrate_address) => substrate_address.clone(), } } diff --git a/pallets/multi-asset-delegation/src/functions/delegate.rs b/pallets/multi-asset-delegation/src/functions/delegate.rs index 19225533b..5357d9529 100644 --- a/pallets/multi-asset-delegation/src/functions/delegate.rs +++ b/pallets/multi-asset-delegation/src/functions/delegate.rs @@ -15,12 +15,15 @@ // along with Tangle. If not, see . use super::*; use crate::{types::*, Pallet}; -use frame_support::traits::fungibles::Mutate; -use frame_support::traits::tokens::Preservation; -use frame_support::{ensure, pallet_prelude::DispatchResult, traits::Get}; -use sp_runtime::traits::{CheckedSub, Zero}; -use sp_runtime::DispatchError; -use sp_runtime::Percent; +use frame_support::{ + ensure, + pallet_prelude::DispatchResult, + traits::{fungibles::Mutate, tokens::Preservation, Get}, +}; +use sp_runtime::{ + traits::{CheckedSub, Zero}, + DispatchError, Percent, +}; use sp_std::vec::Vec; use tangle_primitives::BlueprintId; diff --git a/pallets/multi-asset-delegation/src/functions/deposit.rs b/pallets/multi-asset-delegation/src/functions/deposit.rs index 86e40d92f..0605ece77 100644 --- a/pallets/multi-asset-delegation/src/functions/deposit.rs +++ b/pallets/multi-asset-delegation/src/functions/deposit.rs @@ -15,11 +15,11 @@ // along with Tangle. If not, see . use super::*; use crate::{types::*, Pallet}; -use frame_support::traits::fungibles::Mutate; -use frame_support::{ensure, pallet_prelude::DispatchResult}; use frame_support::{ + ensure, + pallet_prelude::DispatchResult, sp_runtime::traits::{AccountIdConversion, CheckedAdd, Zero}, - traits::{tokens::Preservation, Get}, + traits::{fungibles::Mutate, tokens::Preservation, Get}, }; impl Pallet { diff --git a/pallets/multi-asset-delegation/src/functions/operator.rs b/pallets/multi-asset-delegation/src/functions/operator.rs index 1338b0831..c193b4ee7 100644 --- a/pallets/multi-asset-delegation/src/functions/operator.rs +++ b/pallets/multi-asset-delegation/src/functions/operator.rs @@ -17,19 +17,17 @@ /// Functions for the pallet. use super::*; use crate::{types::*, Pallet}; -use frame_support::traits::Currency; -use frame_support::traits::ExistenceRequirement; -use frame_support::BoundedVec; use frame_support::{ ensure, pallet_prelude::DispatchResult, - traits::{Get, ReservableCurrency}, + traits::{Currency, ExistenceRequirement, Get, ReservableCurrency}, + BoundedVec, }; -use sp_runtime::traits::{CheckedAdd, CheckedSub}; -use sp_runtime::DispatchError; -use sp_runtime::Percent; -use tangle_primitives::BlueprintId; -use tangle_primitives::ServiceManager; +use sp_runtime::{ + traits::{CheckedAdd, CheckedSub}, + DispatchError, Percent, +}; +use tangle_primitives::{BlueprintId, ServiceManager}; impl Pallet { /// Handles the deposit of stake amount and creation of an operator. diff --git a/pallets/multi-asset-delegation/src/lib.rs b/pallets/multi-asset-delegation/src/lib.rs index bfb50073a..0edfbd200 100644 --- a/pallets/multi-asset-delegation/src/lib.rs +++ b/pallets/multi-asset-delegation/src/lib.rs @@ -79,19 +79,19 @@ pub mod pallet { use crate::types::*; use crate::types::{delegator::DelegatorBlueprintSelection, AssetAction}; - use frame_support::traits::fungibles::Inspect; use frame_support::{ pallet_prelude::*, - traits::{tokens::fungibles, Currency, Get, LockableCurrency, ReservableCurrency}, + traits::{ + fungibles::Inspect, tokens::fungibles, Currency, Get, LockableCurrency, + ReservableCurrency, + }, PalletId, }; use frame_system::pallet_prelude::*; use scale_info::TypeInfo; use sp_runtime::traits::{MaybeSerializeDeserialize, Member, Zero}; - use sp_std::vec::Vec; - use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, prelude::*}; - use tangle_primitives::BlueprintId; - use tangle_primitives::{traits::ServiceManager, RoundIndex}; + use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, prelude::*, vec::Vec}; + use tangle_primitives::{traits::ServiceManager, BlueprintId, RoundIndex}; /// Configure the pallet by specifying the parameters and types on which it depends. #[pallet::config] diff --git a/pallets/multi-asset-delegation/src/tests/operator.rs b/pallets/multi-asset-delegation/src/tests/operator.rs index 72c33e054..e4332d031 100644 --- a/pallets/multi-asset-delegation/src/tests/operator.rs +++ b/pallets/multi-asset-delegation/src/tests/operator.rs @@ -14,8 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Tangle. If not, see . use super::*; -use crate::types::DelegatorBlueprintSelection::Fixed; -use crate::{types::OperatorStatus, CurrentRound, Error}; +use crate::{ + types::{DelegatorBlueprintSelection::Fixed, OperatorStatus}, + CurrentRound, Error, +}; use frame_support::{assert_noop, assert_ok}; use sp_runtime::Percent; diff --git a/pallets/multi-asset-delegation/src/traits.rs b/pallets/multi-asset-delegation/src/traits.rs index 2375ece5b..66b169941 100644 --- a/pallets/multi-asset-delegation/src/traits.rs +++ b/pallets/multi-asset-delegation/src/traits.rs @@ -15,11 +15,9 @@ // along with Tangle. If not, see . use super::*; use crate::types::{BalanceOf, OperatorStatus}; -use sp_runtime::traits::Zero; -use sp_runtime::Percent; +use sp_runtime::{traits::Zero, Percent}; use sp_std::prelude::*; -use tangle_primitives::BlueprintId; -use tangle_primitives::{traits::MultiAssetDelegationInfo, RoundIndex}; +use tangle_primitives::{traits::MultiAssetDelegationInfo, BlueprintId, RoundIndex}; impl MultiAssetDelegationInfo> for crate::Pallet { type AssetId = T::AssetId; @@ -34,7 +32,7 @@ impl MultiAssetDelegationInfo> for fn is_operator_active(operator: &T::AccountId) -> bool { Operators::::get(operator) - .map_or(false, |metadata| matches!(metadata.status, OperatorStatus::Active)) + .is_some_and(|metadata| matches!(metadata.status, OperatorStatus::Active)) } fn get_operator_stake(operator: &T::AccountId) -> BalanceOf { diff --git a/pallets/services/rpc/src/lib.rs b/pallets/services/rpc/src/lib.rs index e505a3a15..5798ecae7 100644 --- a/pallets/services/rpc/src/lib.rs +++ b/pallets/services/rpc/src/lib.rs @@ -113,12 +113,10 @@ impl From for i32 { fn custom_error_into_rpc_err(err: Error) -> ErrorObjectOwned { match err { - Error::RuntimeError(e) => { - ErrorObject::owned(RUNTIME_ERROR, "Runtime error", Some(format!("{e}"))) - }, - Error::DecodeError => { - ErrorObject::owned(2, "Decode error", Some("Transaction was not decodable")) - }, + Error::RuntimeError(e) => + ErrorObject::owned(RUNTIME_ERROR, "Runtime error", Some(format!("{e}"))), + Error::DecodeError => + ErrorObject::owned(2, "Decode error", Some("Transaction was not decodable")), Error::CustomDispatchError(msg) => ErrorObject::owned(3, "Dispatch error", Some(msg)), } } diff --git a/pallets/services/src/functions.rs b/pallets/services/src/functions.rs index 2008db47e..7add2f095 100644 --- a/pallets/services/src/functions.rs +++ b/pallets/services/src/functions.rs @@ -77,9 +77,8 @@ impl Pallet { pub fn mbsm_address_of(blueprint: &ServiceBlueprint) -> Result> { match blueprint.master_manager_revision { MasterBlueprintServiceManagerRevision::Specific(rev) => Self::mbsm_address(rev), - MasterBlueprintServiceManagerRevision::Latest => { - Self::mbsm_address(Self::mbsm_latest_revision()) - }, + MasterBlueprintServiceManagerRevision::Latest => + Self::mbsm_address(Self::mbsm_latest_revision()), other => unimplemented!("Got unexpected case for {:?}", other), } } @@ -95,8 +94,8 @@ impl Pallet { /// * `owner` - The owner of the blueprint. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating - /// whether the blueprint creation is allowed and the weight of the operation. + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating whether the blueprint creation is allowed and the weight of the operation. pub fn on_blueprint_created_hook( blueprint: &ServiceBlueprint, blueprint_id: u64, @@ -190,8 +189,8 @@ impl Pallet { /// * `value` - The value to be sent with the call. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating - /// whether the registration is allowed and the weight of the operation. + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating whether the registration is allowed and the weight of the operation. pub fn on_register_hook( blueprint: &ServiceBlueprint, blueprint_id: u64, @@ -241,7 +240,8 @@ impl Pallet { /// * `prefrences` - The operator preferences. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating /// whether the unregistration is allowed and the weight of the operation. pub fn on_unregister_hook( blueprint: &ServiceBlueprint, @@ -281,7 +281,8 @@ impl Pallet { /// /// # Returns /// - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating /// whether the price targets update is allowed and the weight of the operation. pub fn on_update_price_targets( blueprint: &ServiceBlueprint, @@ -323,7 +324,8 @@ impl Pallet { /// * `restaking_percent` - The restaking percent. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating /// whether the approve is allowed and the weight of the operation. pub fn on_approve_hook( blueprint: &ServiceBlueprint, @@ -380,7 +382,8 @@ impl Pallet { /// * `request_id` - The request id. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating /// whether the reject is allowed and the weight of the operation. pub fn on_reject_hook( blueprint: &ServiceBlueprint, @@ -437,8 +440,8 @@ impl Pallet { /// * `value` - The value to be sent with the call. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating - /// whether the request is allowed and the weight of the operation. + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating whether the request is allowed and the weight of the operation. pub fn on_request_hook( blueprint: &ServiceBlueprint, blueprint_id: u64, @@ -526,8 +529,8 @@ impl Pallet { ) } - /// Hook to be called when a service is initialized. This function will call the `onServiceInitialized` - /// function of the service blueprint manager contract. + /// Hook to be called when a service is initialized. This function will call the + /// `onServiceInitialized` function of the service blueprint manager contract. /// /// # Arguments /// * `blueprint` - The service blueprint. @@ -540,7 +543,8 @@ impl Pallet { /// * `ttl` - The time to live. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating /// whether the request is allowed and the weight of the operation. pub fn on_service_init_hook( blueprint: &ServiceBlueprint, @@ -618,8 +622,8 @@ impl Pallet { ) } - /// Hook to be called when a service is terminated. This function will call the `onServiceTermination` - /// function of the service blueprint manager contract. + /// Hook to be called when a service is terminated. This function will call the + /// `onServiceTermination` function of the service blueprint manager contract. /// /// # Arguments /// * `blueprint` - The service blueprint. @@ -628,7 +632,8 @@ impl Pallet { /// * `owner` - The owner of the service. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating /// whether the request is allowed and the weight of the operation. pub fn on_service_termination_hook( blueprint: &ServiceBlueprint, @@ -685,8 +690,8 @@ impl Pallet { /// * `inputs` - The input fields. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating - /// whether the job call is allowed and the weight of the operation. + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating whether the job call is allowed and the weight of the operation. pub fn on_job_call_hook( blueprint: &ServiceBlueprint, blueprint_id: u64, @@ -758,8 +763,8 @@ impl Pallet { /// * `outputs` - The output fields. /// /// # Returns - /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean indicating - /// whether the job result is allowed and the weight of the operation. + /// * `Result<(bool, Weight), DispatchErrorWithPostInfo>` - A tuple containing a boolean + /// indicating whether the job result is allowed and the weight of the operation. pub fn on_job_result_hook( blueprint: &ServiceBlueprint, blueprint_id: u64, @@ -834,8 +839,8 @@ impl Pallet { /// * `service` - The service. /// /// # Returns - /// * `Result<(Option, Weight), DispatchErrorWithPostInfo>` - A tuple containing the - /// slashing origin account id (if any) and the weight of the operation. + /// * `Result<(Option, Weight), DispatchErrorWithPostInfo>` - A tuple containing + /// the slashing origin account id (if any) and the weight of the operation. pub fn query_slashing_origin( service: &Service, T::AssetId>, ) -> Result<(Option, Weight), DispatchErrorWithPostInfo> { @@ -899,8 +904,8 @@ impl Pallet { /// * `service` - The service. /// /// # Returns - /// * `Result<(Option, Weight), DispatchErrorWithPostInfo>` - A tuple containing the - /// dispute origin account id (if any) and the weight of the operation. + /// * `Result<(Option, Weight), DispatchErrorWithPostInfo>` - A tuple containing + /// the dispute origin account id (if any) and the weight of the operation. pub fn query_dispute_origin( service: &Service, T::AssetId>, ) -> Result<(Option, Weight), DispatchErrorWithPostInfo> { diff --git a/pallets/services/src/impls.rs b/pallets/services/src/impls.rs index 4423b785f..69297d072 100644 --- a/pallets/services/src/impls.rs +++ b/pallets/services/src/impls.rs @@ -5,8 +5,7 @@ use alloc::vec::Vec; use sp_std::vec; #[cfg(feature = "std")] use std::vec::Vec; -use tangle_primitives::BlueprintId; -use tangle_primitives::{services::Constraints, traits::ServiceManager}; +use tangle_primitives::{services::Constraints, traits::ServiceManager, BlueprintId}; impl traits::EvmRunner for () { type Error = crate::Error; diff --git a/pallets/services/src/lib.rs b/pallets/services/src/lib.rs index 1e11b42c6..eb53d663f 100644 --- a/pallets/services/src/lib.rs +++ b/pallets/services/src/lib.rs @@ -60,12 +60,13 @@ pub mod module { use super::*; use frame_support::dispatch::PostDispatchInfo; use sp_core::H160; - use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize}; - use sp_runtime::Percent; + use sp_runtime::{ + traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize}, + Percent, + }; use sp_std::vec::Vec; - use tangle_primitives::services::MasterBlueprintServiceManagerRevision; use tangle_primitives::{ - services::{PriceTargets, *}, + services::{MasterBlueprintServiceManagerRevision, PriceTargets, *}, MultiAssetDelegationInfo, }; use types::*; @@ -198,7 +199,8 @@ pub mod module { impl Hooks> for Pallet { fn integrity_test() { // Ensure that the pallet's configuration is valid. - // 1. Make sure that pallet's associated AccountId value maps correctly to the EVM address. + // 1. Make sure that pallet's associated AccountId value maps correctly to the EVM + // address. let account_id = T::EvmAddressMapping::into_account_id(Self::address()); assert_eq!(account_id, Self::account_id(), "Services: AccountId mapping is incorrect."); } @@ -1000,10 +1002,10 @@ pub mod module { .operators_with_approval_state .into_iter() .filter_map(|(v, state)| match state { - ApprovalState::Approved { restaking_percent } => { - Some((v, restaking_percent)) - }, - // N.B: this should not happen, as all operators are approved and checked above. + ApprovalState::Approved { restaking_percent } => + Some((v, restaking_percent)), + // N.B: this should not happen, as all operators are approved and checked + // above. _ => None, }) .collect::>(); @@ -1244,11 +1246,12 @@ pub mod module { Ok(PostDispatchInfo { actual_weight: None, pays_fee: Pays::Yes }) } - /// Slash an operator (offender) for a service id with a given percent of their exposed stake for that service. + /// Slash an operator (offender) for a service id with a given percent of their exposed + /// stake for that service. /// /// The caller needs to be an authorized Slash Origin for this service. - /// Note that this does not apply the slash directly, but instead schedules a deferred call to apply the slash - /// by another entity. + /// Note that this does not apply the slash directly, but instead schedules a deferred call + /// to apply the slash by another entity. pub fn slash( origin: OriginFor, offender: T::AccountId, @@ -1310,7 +1313,8 @@ pub mod module { /// Dispute an [UnappliedSlash] for a given era and index. /// - /// The caller needs to be an authorized Dispute Origin for the service in the [UnappliedSlash]. + /// The caller needs to be an authorized Dispute Origin for the service in the + /// [UnappliedSlash]. pub fn dispute( origin: OriginFor, #[pallet::compact] era: u32, diff --git a/pallets/services/src/mock.rs b/pallets/services/src/mock.rs index cac0f45d0..6a5ccbe39 100644 --- a/pallets/services/src/mock.rs +++ b/pallets/services/src/mock.rs @@ -20,9 +20,8 @@ use frame_election_provider_support::{ bounds::{ElectionBounds, ElectionBoundsBuilder}, onchain, SequentialPhragmen, }; -use frame_support::derive_impl; use frame_support::{ - construct_runtime, parameter_types, + construct_runtime, derive_impl, parameter_types, traits::{ConstU128, ConstU32, OneSessionHandler}, }; use frame_system::EnsureRoot; @@ -606,11 +605,10 @@ pub fn assert_events(mut expected: Vec) { for evt in expected { let next = actual.pop().expect("RuntimeEvent expected"); match (&next, &evt) { - (left_val, right_val) => { + (left_val, right_val) => if !(*left_val == *right_val) { panic!("Events don't match\nactual: {actual:#?}\nexpected: {evt:#?}"); - } - }, + }, }; } } diff --git a/pallets/services/src/mock_evm.rs b/pallets/services/src/mock_evm.rs index 8fcccabdb..06fde6c34 100644 --- a/pallets/services/src/mock_evm.rs +++ b/pallets/services/src/mock_evm.rs @@ -266,9 +266,8 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => { - call.pre_dispatch_self_contained(info, dispatch_info, len) - }, + RuntimeCall::Ethereum(call) => + call.pre_dispatch_self_contained(info, dispatch_info, len), _ => None, } } @@ -278,9 +277,8 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { - Some(call.dispatch(RuntimeOrigin::from(RawOrigin::EthereumTransaction(info)))) - }, + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => + Some(call.dispatch(RuntimeOrigin::from(RawOrigin::EthereumTransaction(info)))), _ => None, } } diff --git a/pallets/services/src/tests.rs b/pallets/services/src/tests.rs index b7657a817..9dbdd586b 100644 --- a/pallets/services/src/tests.rs +++ b/pallets/services/src/tests.rs @@ -20,8 +20,7 @@ use frame_support::{assert_err, assert_ok}; use mock::*; use sp_core::{bounded_vec, ecdsa, ByteArray}; use sp_runtime::{KeyTypeId, Percent}; -use tangle_primitives::services::*; -use tangle_primitives::MultiAssetDelegationInfo; +use tangle_primitives::{services::*, MultiAssetDelegationInfo}; const ALICE: u8 = 1; const BOB: u8 = 2; @@ -63,9 +62,8 @@ fn price_targets(kind: MachineKind) -> PriceTargets { storage_ssd: 100, storage_nvme: 150, }, - MachineKind::Small => { - PriceTargets { cpu: 500, mem: 250, storage_hdd: 25, storage_ssd: 50, storage_nvme: 75 } - }, + MachineKind::Small => + PriceTargets { cpu: 500, mem: 250, storage_hdd: 25, storage_ssd: 50, storage_nvme: 75 }, } } diff --git a/pallets/tangle-lst/benchmarking/src/inner.rs b/pallets/tangle-lst/benchmarking/src/inner.rs index 88d70bac6..2487891f8 100644 --- a/pallets/tangle-lst/benchmarking/src/inner.rs +++ b/pallets/tangle-lst/benchmarking/src/inner.rs @@ -3,13 +3,12 @@ use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{account, whitelist_account}; use frame_election_provider_support::SortedListProvider; -use frame_support::traits::Currency; use frame_support::{ assert_ok, ensure, traits::{ fungible::{Inspect, Mutate, Unbalanced}, tokens::Preservation, - Get, Imbalance, + Currency, Get, Imbalance, }, }; use frame_system::RawOrigin as RuntimeOrigin; @@ -24,8 +23,7 @@ use sp_runtime::{ traits::{Bounded, StaticLookup, Zero}, Perbill, }; -use sp_staking::EraIndex; -use sp_staking::StakingInterface; +use sp_staking::{EraIndex, StakingInterface}; // `frame_benchmarking::benchmarks!` macro needs this use pallet_tangle_lst::Call; diff --git a/pallets/tangle-lst/benchmarking/src/mock.rs b/pallets/tangle-lst/benchmarking/src/mock.rs index f7116ecb5..375a72690 100644 --- a/pallets/tangle-lst/benchmarking/src/mock.rs +++ b/pallets/tangle-lst/benchmarking/src/mock.rs @@ -2,30 +2,20 @@ use super::*; use frame_election_provider_support::VoteWeight; -use frame_support::traits::AsEnsureOriginWithArg; -use frame_support::traits::Hooks; -use frame_support::traits::OnFinalize; -use frame_support::{assert_ok, derive_impl, parameter_types, PalletId}; +use frame_support::{ + assert_ok, derive_impl, parameter_types, + traits::{AsEnsureOriginWithArg, Hooks, OnFinalize}, + PalletId, +}; use frame_system::RawOrigin; -use pallet_tangle_lst::BondedPools; -use pallet_tangle_lst::Config; -use pallet_tangle_lst::Event; -use pallet_tangle_lst::LastPoolId; -use pallet_tangle_lst::PoolId; -use pallet_tangle_lst::PoolState; +use pallet_tangle_lst::{BondedPools, Config, Event, LastPoolId, PoolId, PoolState}; use sp_core::U256; -use sp_runtime::traits::ConstU128; -use sp_runtime::traits::ConstU32; -use sp_runtime::traits::ConstU64; -use sp_runtime::traits::Convert; -use sp_runtime::traits::Zero; -use sp_runtime::DispatchError; -use sp_runtime::DispatchResult; -use sp_runtime::Perbill; -use sp_runtime::{BuildStorage, FixedU128}; +use sp_runtime::{ + traits::{ConstU128, ConstU32, ConstU64, Convert, Zero}, + BuildStorage, DispatchError, DispatchResult, FixedU128, Perbill, +}; use sp_runtime_interface::sp_tracing; -use sp_staking::EraIndex; -use sp_staking::{OnStakingUpdate, Stake}; +use sp_staking::{EraIndex, OnStakingUpdate, Stake}; use sp_std::collections::btree_map::BTreeMap; pub type BlockNumber = u64; diff --git a/pallets/tangle-lst/src/lib.rs b/pallets/tangle-lst/src/lib.rs index 317d5ffcb..ba2d426c8 100644 --- a/pallets/tangle-lst/src/lib.rs +++ b/pallets/tangle-lst/src/lib.rs @@ -107,34 +107,29 @@ #![cfg_attr(not(feature = "std"), no_std)] use codec::Codec; -use frame_support::traits::fungibles; -use frame_support::traits::fungibles::Create; -use frame_support::traits::fungibles::Inspect as FungiblesInspect; -use frame_support::traits::fungibles::Mutate as FungiblesMutate; -use frame_support::traits::tokens::Precision; -use frame_support::traits::tokens::Preservation; -use frame_support::traits::Currency; -use frame_support::traits::ExistenceRequirement; -use frame_support::traits::LockableCurrency; -use frame_support::traits::ReservableCurrency; use frame_support::{ defensive, defensive_assert, ensure, pallet_prelude::{MaxEncodedLen, *}, storage::bounded_btree_map::BoundedBTreeMap, traits::{ - tokens::Fortitude, Defensive, DefensiveOption, DefensiveResult, DefensiveSaturating, Get, + fungibles, + fungibles::{Create, Inspect as FungiblesInspect, Mutate as FungiblesMutate}, + tokens::{Fortitude, Precision, Preservation}, + Currency, Defensive, DefensiveOption, DefensiveResult, DefensiveSaturating, + ExistenceRequirement, Get, LockableCurrency, ReservableCurrency, }, DefaultNoBound, PalletError, }; use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_core::U256; -use sp_runtime::traits::AccountIdConversion; -use sp_runtime::traits::{ - AtLeast32BitUnsigned, Bounded, CheckedAdd, Convert, Saturating, StaticLookup, Zero, +use sp_runtime::{ + traits::{ + AccountIdConversion, AtLeast32BitUnsigned, Bounded, CheckedAdd, Convert, Saturating, + StaticLookup, Zero, + }, + FixedPointNumber, Perbill, }; -use sp_runtime::FixedPointNumber; -use sp_runtime::Perbill; use sp_staking::{EraIndex, StakingInterface}; use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, ops::Div, vec::Vec}; @@ -1539,7 +1534,8 @@ impl Pallet { let bouncer = T::Lookup::lookup(bouncer)?; // ensure that pool token can be created - // if this fails, it means that the pool token already exists or the token counter needs to be incremented correctly + // if this fails, it means that the pool token already exists or the token counter needs to + // be incremented correctly ensure!( T::Fungibles::total_issuance(pool_id.into()) == 0_u32.into(), Error::::PoolTokenCreationFailed @@ -1550,7 +1546,7 @@ impl Pallet { ensure!(amount >= Pallet::::depositor_min_bond(), Error::::MinimumBondNotMet); ensure!( - MaxPools::::get().map_or(true, |max_pools| BondedPools::::count() < max_pools), + MaxPools::::get().is_none_or(|max_pools| BondedPools::::count() < max_pools), Error::::MaxPools ); let mut bonded_pool = BondedPool::::new( @@ -1618,9 +1614,8 @@ impl Pallet { bonded_pool.ok_to_join()?; let (_points_issued, bonded) = match extra { - BondExtra::FreeBalance(amount) => { - (bonded_pool.try_bond_funds(&member_account, amount, BondType::Later)?, amount) - }, + BondExtra::FreeBalance(amount) => + (bonded_pool.try_bond_funds(&member_account, amount, BondType::Later)?, amount), }; bonded_pool.ok_to_be_open()?; diff --git a/pallets/tangle-lst/src/mock.rs b/pallets/tangle-lst/src/mock.rs index 95e6f6295..eba18dd4f 100644 --- a/pallets/tangle-lst/src/mock.rs +++ b/pallets/tangle-lst/src/mock.rs @@ -2,12 +2,11 @@ use super::*; use crate::{self as pallet_lst}; -use frame_support::traits::AsEnsureOriginWithArg; -use frame_support::{assert_ok, derive_impl, parameter_types, PalletId}; +use frame_support::{ + assert_ok, derive_impl, parameter_types, traits::AsEnsureOriginWithArg, PalletId, +}; use frame_system::RawOrigin; -use sp_runtime::traits::ConstU128; -use sp_runtime::Perbill; -use sp_runtime::{BuildStorage, FixedU128}; +use sp_runtime::{traits::ConstU128, BuildStorage, FixedU128, Perbill}; use sp_staking::{OnStakingUpdate, Stake}; pub type BlockNumber = u64; diff --git a/pallets/tangle-lst/src/tests.rs b/pallets/tangle-lst/src/tests.rs index d567b1f86..5309c2d94 100644 --- a/pallets/tangle-lst/src/tests.rs +++ b/pallets/tangle-lst/src/tests.rs @@ -16,7 +16,10 @@ // the License. use super::*; -use crate::{mock::Currency, mock::*, Event}; +use crate::{ + mock::{Currency, *}, + Event, +}; use frame_support::traits::Currency as CurrencyT; mod bond_extra; diff --git a/pallets/tangle-lst/src/tests/bonded_pool.rs b/pallets/tangle-lst/src/tests/bonded_pool.rs index 4edb95851..13325ca99 100644 --- a/pallets/tangle-lst/src/tests/bonded_pool.rs +++ b/pallets/tangle-lst/src/tests/bonded_pool.rs @@ -1,7 +1,6 @@ use super::*; use crate::mock::Currency; -use frame_support::traits::Currency as CurrencyT; -use frame_support::{assert_noop, assert_ok}; +use frame_support::{assert_noop, assert_ok, traits::Currency as CurrencyT}; #[test] fn test_setup_works() { diff --git a/pallets/tangle-lst/src/tests/create.rs b/pallets/tangle-lst/src/tests/create.rs index 7779dffc6..99ee9d946 100644 --- a/pallets/tangle-lst/src/tests/create.rs +++ b/pallets/tangle-lst/src/tests/create.rs @@ -1,7 +1,5 @@ use super::*; -use frame_support::assert_err; -use frame_support::assert_noop; -use frame_support::assert_ok; +use frame_support::{assert_err, assert_noop, assert_ok}; #[test] fn create_works() { diff --git a/pallets/tangle-lst/src/tests/update_roles.rs b/pallets/tangle-lst/src/tests/update_roles.rs index c3287f9e6..346d418a8 100644 --- a/pallets/tangle-lst/src/tests/update_roles.rs +++ b/pallets/tangle-lst/src/tests/update_roles.rs @@ -1,7 +1,5 @@ use super::*; -use frame_support::assert_err; -use frame_support::assert_noop; -use frame_support::assert_ok; +use frame_support::{assert_err, assert_noop, assert_ok}; #[test] fn update_roles_works() { diff --git a/pallets/tangle-lst/src/types/bonded_pool.rs b/pallets/tangle-lst/src/types/bonded_pool.rs index bca834932..f808d9f4c 100644 --- a/pallets/tangle-lst/src/types/bonded_pool.rs +++ b/pallets/tangle-lst/src/types/bonded_pool.rs @@ -160,8 +160,8 @@ impl BondedPool { } pub fn can_nominate(&self, who: &T::AccountId) -> bool { - self.is_root(who) - || self.roles.nominator.as_ref().map_or(false, |nominator| nominator == who) + self.is_root(who) || + self.roles.nominator.as_ref().map_or(false, |nominator| nominator == who) } pub fn can_kick(&self, who: &T::AccountId) -> bool { @@ -262,9 +262,9 @@ impl BondedPool { // any unbond must comply with the balance condition: ensure!( - is_full_unbond - || balance_after_unbond - >= if is_depositor { + is_full_unbond || + balance_after_unbond >= + if is_depositor { Pallet::::depositor_min_bond() } else { MinJoinBond::::get() diff --git a/pallets/tangle-lst/src/types/commission.rs b/pallets/tangle-lst/src/types/commission.rs index 9fbee7550..845cbd754 100644 --- a/pallets/tangle-lst/src/types/commission.rs +++ b/pallets/tangle-lst/src/types/commission.rs @@ -116,7 +116,7 @@ impl Commission { Error::::CommissionExceedsGlobalMaximum ); ensure!( - self.max.map_or(true, |m| commission <= &m), + self.max.is_none_or(|m| commission <= &m), Error::::CommissionExceedsMaximum ); if commission.is_zero() { diff --git a/precompiles/assets-erc20/src/lib.rs b/precompiles/assets-erc20/src/lib.rs index d985500d7..0622ef949 100644 --- a/precompiles/assets-erc20/src/lib.rs +++ b/precompiles/assets-erc20/src/lib.rs @@ -254,8 +254,8 @@ where handle.record_db_read::(136)?; // If previous approval exists, we need to clean it - if pallet_assets::Pallet::::allowance(asset_id.clone(), &owner, &spender) - != 0u32.into() + if pallet_assets::Pallet::::allowance(asset_id.clone(), &owner, &spender) != + 0u32.into() { RuntimeHelper::::try_dispatch( handle, diff --git a/precompiles/assets-erc20/src/tests.rs b/precompiles/assets-erc20/src/tests.rs index 72e029960..a89db5452 100644 --- a/precompiles/assets-erc20/src/tests.rs +++ b/precompiles/assets-erc20/src/tests.rs @@ -441,8 +441,8 @@ fn transfer_not_enough_founds() { ForeignPCall::transfer { to: Address(Charlie.into()), value: 50.into() }, ) .execute_reverts(|output| { - from_utf8(output).unwrap().contains("Dispatched call failed with error: ") - && from_utf8(output).unwrap().contains("BalanceLow") + from_utf8(output).unwrap().contains("Dispatched call failed with error: ") && + from_utf8(output).unwrap().contains("BalanceLow") }); }); } diff --git a/precompiles/assets/src/lib.rs b/precompiles/assets/src/lib.rs index 9ad9b1c66..176d49ca0 100644 --- a/precompiles/assets/src/lib.rs +++ b/precompiles/assets/src/lib.rs @@ -1,14 +1,15 @@ #![cfg_attr(not(feature = "std"), no_std)] use fp_evm::PrecompileHandle; -use frame_support::dispatch::{GetDispatchInfo, PostDispatchInfo}; -use frame_support::traits::fungibles::Inspect; +use frame_support::{ + dispatch::{GetDispatchInfo, PostDispatchInfo}, + traits::fungibles::Inspect, +}; use pallet_evm::AddressMapping; use parity_scale_codec::MaxEncodedLen; use precompile_utils::{prelude::*, solidity}; use sp_core::U256; -use sp_runtime::traits::Dispatchable; -use sp_runtime::traits::StaticLookup; +use sp_runtime::traits::{Dispatchable, StaticLookup}; use sp_std::marker::PhantomData; type BalanceOf = ::Balance; diff --git a/precompiles/assets/src/mock.rs b/precompiles/assets/src/mock.rs index 40ac73fcb..906396e72 100644 --- a/precompiles/assets/src/mock.rs +++ b/precompiles/assets/src/mock.rs @@ -17,9 +17,8 @@ //! Test utilities use super::*; use crate::{AssetsPrecompile, AssetsPrecompileCall}; -use frame_support::derive_impl; use frame_support::{ - construct_runtime, parameter_types, + construct_runtime, derive_impl, parameter_types, traits::{AsEnsureOriginWithArg, ConstU64}, weights::Weight, }; diff --git a/precompiles/balances-erc20/src/eip2612.rs b/precompiles/balances-erc20/src/eip2612.rs index cbd2cec36..beb46e754 100644 --- a/precompiles/balances-erc20/src/eip2612.rs +++ b/precompiles/balances-erc20/src/eip2612.rs @@ -21,8 +21,7 @@ use frame_support::{ }; use sp_core::H256; use sp_io::hashing::keccak_256; -use sp_runtime::traits::UniqueSaturatedInto; -use sp_runtime::AccountId32; +use sp_runtime::{traits::UniqueSaturatedInto, AccountId32}; use sp_std::vec::Vec; /// EIP2612 permit typehash. diff --git a/precompiles/balances-erc20/src/lib.rs b/precompiles/balances-erc20/src/lib.rs index 5024ccdd1..aa3a6b4f5 100644 --- a/precompiles/balances-erc20/src/lib.rs +++ b/precompiles/balances-erc20/src/lib.rs @@ -34,10 +34,10 @@ use pallet_evm::AddressMapping; use precompile_utils::prelude::*; use sp_core::{H160, H256, U256}; use sp_runtime::AccountId32; -use sp_std::vec::Vec; use sp_std::{ convert::{TryFrom, TryInto}, marker::PhantomData, + vec::Vec, }; mod eip2612; diff --git a/precompiles/balances-erc20/src/mock.rs b/precompiles/balances-erc20/src/mock.rs index 1cddc9554..fa5d1e4bd 100644 --- a/precompiles/balances-erc20/src/mock.rs +++ b/precompiles/balances-erc20/src/mock.rs @@ -17,16 +17,15 @@ //! Testing utilities. use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, parameter_types, weights::Weight}; -use pallet_evm::AddressMapping; -use pallet_evm::{EnsureAddressNever, EnsureAddressRoot}; -use precompile_utils::testing::{Bob, CryptoAlith, CryptoBaltathar, Precompile1}; -use precompile_utils::{precompile_set::*, testing::MockAccount}; +use frame_support::{construct_runtime, derive_impl, parameter_types, weights::Weight}; +use pallet_evm::{AddressMapping, EnsureAddressNever, EnsureAddressRoot}; +use precompile_utils::{ + precompile_set::*, + testing::{Bob, CryptoAlith, CryptoBaltathar, MockAccount, Precompile1}, +}; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; -use sp_core::{ConstU32, U256}; -use sp_core::{Decode, Encode, MaxEncodedLen, H160}; +use sp_core::{ConstU32, Decode, Encode, MaxEncodedLen, H160, U256}; use sp_runtime::BuildStorage; use sp_std::ops::Deref; diff --git a/precompiles/balances-erc20/src/tests.rs b/precompiles/balances-erc20/src/tests.rs index 6e176e808..f62c1a4de 100644 --- a/precompiles/balances-erc20/src/tests.rs +++ b/precompiles/balances-erc20/src/tests.rs @@ -306,8 +306,8 @@ fn transfer_not_enough_funds() { PCall::transfer { to: Address(Bob.into()), value: 1400.into() }, ) .execute_reverts(|output| { - from_utf8(&output).unwrap().contains("Dispatched call failed with error: ") - && from_utf8(&output).unwrap().contains("FundsUnavailable") + from_utf8(&output).unwrap().contains("Dispatched call failed with error: ") && + from_utf8(&output).unwrap().contains("FundsUnavailable") }); }); } diff --git a/precompiles/batch/src/lib.rs b/precompiles/batch/src/lib.rs index 640b1b793..0c71539af 100644 --- a/precompiles/batch/src/lib.rs +++ b/precompiles/batch/src/lib.rs @@ -146,9 +146,8 @@ where let forwarded_gas = match (remaining_gas.checked_sub(log_cost), mode) { (Some(remaining), _) => remaining, - (None, Mode::BatchAll) => { - return Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }) - }, + (None, Mode::BatchAll) => + return Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }), (None, _) => return Ok(()), }; @@ -163,11 +162,10 @@ where log.record(handle)?; match mode { - Mode::BatchAll => { + Mode::BatchAll => return Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas, - }) - }, + }), Mode::BatchSomeUntilFailure => return Ok(()), Mode::BatchSome => continue, } @@ -184,11 +182,10 @@ where log.record(handle)?; match mode { - Mode::BatchAll => { + Mode::BatchAll => return Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas, - }) - }, + }), Mode::BatchSomeUntilFailure => return Ok(()), Mode::BatchSome => continue, } @@ -219,23 +216,19 @@ where // How to proceed match (mode, reason) { // _: Fatal is always fatal - (_, ExitReason::Fatal(exit_status)) => { - return Err(PrecompileFailure::Fatal { exit_status }) - }, + (_, ExitReason::Fatal(exit_status)) => + return Err(PrecompileFailure::Fatal { exit_status }), // BatchAll : Reverts and errors are immediatly forwarded. - (Mode::BatchAll, ExitReason::Revert(exit_status)) => { - return Err(PrecompileFailure::Revert { exit_status, output }) - }, - (Mode::BatchAll, ExitReason::Error(exit_status)) => { - return Err(PrecompileFailure::Error { exit_status }) - }, + (Mode::BatchAll, ExitReason::Revert(exit_status)) => + return Err(PrecompileFailure::Revert { exit_status, output }), + (Mode::BatchAll, ExitReason::Error(exit_status)) => + return Err(PrecompileFailure::Error { exit_status }), // BatchSomeUntilFailure : Reverts and errors prevent subsequent subcalls to // be executed but the precompile still succeed. - (Mode::BatchSomeUntilFailure, ExitReason::Revert(_) | ExitReason::Error(_)) => { - return Ok(()) - }, + (Mode::BatchSomeUntilFailure, ExitReason::Revert(_) | ExitReason::Error(_)) => + return Ok(()), // Success or ignored revert/error. (_, _) => (), @@ -270,9 +263,8 @@ where match mode { Mode::BatchSome => Self::batch_some { to, value, call_data, gas_limit }, - Mode::BatchSomeUntilFailure => { - Self::batch_some_until_failure { to, value, call_data, gas_limit } - }, + Mode::BatchSomeUntilFailure => + Self::batch_some_until_failure { to, value, call_data, gas_limit }, Mode::BatchAll => Self::batch_all { to, value, call_data, gas_limit }, } } diff --git a/precompiles/batch/src/mock.rs b/precompiles/batch/src/mock.rs index e9c7ec919..a2d224159 100644 --- a/precompiles/batch/src/mock.rs +++ b/precompiles/batch/src/mock.rs @@ -18,8 +18,7 @@ //! Test utilities use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, parameter_types, weights::Weight}; +use frame_support::{construct_runtime, derive_impl, parameter_types, weights::Weight}; use pallet_evm::{EnsureAddressNever, EnsureAddressRoot}; use precompile_utils::{mock_account, precompile_set::*, testing::MockAccount}; use sp_runtime::{BuildStorage, Perbill}; diff --git a/precompiles/call-permit/src/lib.rs b/precompiles/call-permit/src/lib.rs index ee64f0b89..c1bb88e69 100644 --- a/precompiles/call-permit/src/lib.rs +++ b/precompiles/call-permit/src/lib.rs @@ -216,9 +216,8 @@ where match reason { ExitReason::Error(exit_status) => Err(PrecompileFailure::Error { exit_status }), ExitReason::Fatal(exit_status) => Err(PrecompileFailure::Fatal { exit_status }), - ExitReason::Revert(_) => { - Err(PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output }) - }, + ExitReason::Revert(_) => + Err(PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output }), ExitReason::Succeed(_) => Ok(output.into()), } } diff --git a/precompiles/call-permit/src/mock.rs b/precompiles/call-permit/src/mock.rs index f9858e7c8..0e45d42d6 100644 --- a/precompiles/call-permit/src/mock.rs +++ b/precompiles/call-permit/src/mock.rs @@ -19,8 +19,7 @@ //! Test utilities use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, pallet_prelude::*, parameter_types}; +use frame_support::{construct_runtime, derive_impl, pallet_prelude::*, parameter_types}; use pallet_evm::{EnsureAddressNever, EnsureAddressRoot}; use precompile_utils::{mock_account, precompile_set::*, testing::MockAccount}; use sp_runtime::{BuildStorage, Perbill}; diff --git a/precompiles/multi-asset-delegation/src/mock.rs b/precompiles/multi-asset-delegation/src/mock.rs index a999578d2..35d911ffd 100644 --- a/precompiles/multi-asset-delegation/src/mock.rs +++ b/precompiles/multi-asset-delegation/src/mock.rs @@ -17,9 +17,8 @@ //! Test utilities use super::*; use crate::{MultiAssetDelegationPrecompile, MultiAssetDelegationPrecompileCall}; -use frame_support::derive_impl; use frame_support::{ - construct_runtime, parameter_types, + construct_runtime, derive_impl, parameter_types, traits::{AsEnsureOriginWithArg, ConstU64}, weights::Weight, PalletId, diff --git a/precompiles/multi-asset-delegation/src/tests.rs b/precompiles/multi-asset-delegation/src/tests.rs index c6ed8d645..2c7d65333 100644 --- a/precompiles/multi-asset-delegation/src/tests.rs +++ b/precompiles/multi-asset-delegation/src/tests.rs @@ -432,8 +432,8 @@ fn test_operator_go_offline_and_online() { .execute_returns(()); assert!( - MultiAssetDelegation::operator_info(operator_account).unwrap().status - == OperatorStatus::Inactive + MultiAssetDelegation::operator_info(operator_account).unwrap().status == + OperatorStatus::Inactive ); PrecompilesValue::get() @@ -441,8 +441,8 @@ fn test_operator_go_offline_and_online() { .execute_returns(()); assert!( - MultiAssetDelegation::operator_info(operator_account).unwrap().status - == OperatorStatus::Active + MultiAssetDelegation::operator_info(operator_account).unwrap().status == + OperatorStatus::Active ); assert_eq!(Balances::free_balance(operator_account), 20_000 - 10_000); diff --git a/precompiles/pallet-democracy/src/mock.rs b/precompiles/pallet-democracy/src/mock.rs index 914437668..09f7e3ab1 100644 --- a/precompiles/pallet-democracy/src/mock.rs +++ b/precompiles/pallet-democracy/src/mock.rs @@ -18,9 +18,8 @@ //! Test utilities use super::*; -use frame_support::derive_impl; use frame_support::{ - construct_runtime, parameter_types, + construct_runtime, derive_impl, parameter_types, traits::{EqualPrivilegeOnly, OnFinalize, OnInitialize, StorePreimage}, weights::Weight, }; diff --git a/precompiles/pallet-democracy/src/tests.rs b/precompiles/pallet-democracy/src/tests.rs index bdf4baf32..e8f280d05 100644 --- a/precompiles/pallet-democracy/src/tests.rs +++ b/precompiles/pallet-democracy/src/tests.rs @@ -220,9 +220,8 @@ fn lowest_unbaked_non_zero() { .dispatch(RuntimeOrigin::signed(Alice.into()))); let voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Direct { votes, delegations, prior } => { - (votes.into_inner(), delegations, prior) - }, + Voting::Direct { votes, delegations, prior } => + (votes.into_inner(), delegations, prior), _ => panic!("Votes are not direct"), }; @@ -244,9 +243,9 @@ fn lowest_unbaked_non_zero() { // Run it through until it is baked roll_to( - ::VotingPeriod::get() - + ::LaunchPeriod::get() - + 1000, + ::VotingPeriod::get() + + ::LaunchPeriod::get() + + 1000, ); precompiles() @@ -559,9 +558,8 @@ fn standard_vote_aye_works() { ); let voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Direct { votes, delegations, prior } => { - (votes.into_inner(), delegations, prior) - }, + Voting::Direct { votes, delegations, prior } => + (votes.into_inner(), delegations, prior), _ => panic!("Votes are not direct"), }; @@ -644,9 +642,8 @@ fn standard_vote_nay_conviction_works() { ); let voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Direct { votes, delegations, prior } => { - (votes.into_inner(), delegations, prior) - }, + Voting::Direct { votes, delegations, prior } => + (votes.into_inner(), delegations, prior), _ => panic!("Votes are not direct"), }; @@ -724,9 +721,8 @@ fn remove_vote_works() { ); let voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Direct { votes, delegations, prior } => { - (votes.into_inner(), delegations, prior) - }, + Voting::Direct { votes, delegations, prior } => + (votes.into_inner(), delegations, prior), _ => panic!("Votes are not direct"), }; @@ -797,9 +793,8 @@ fn delegate_works() { ); let alice_voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Delegating { balance, target, conviction, delegations, prior } => { - (balance, target, conviction, delegations, prior) - }, + Voting::Delegating { balance, target, conviction, delegations, prior } => + (balance, target, conviction, delegations, prior), _ => panic!("Votes are not delegating"), }; @@ -812,9 +807,8 @@ fn delegate_works() { let bob_voting = match pallet_democracy::VotingOf::::get(AccountId::from(Bob)) { - Voting::Direct { votes, delegations, prior } => { - (votes.into_inner(), delegations, prior) - }, + Voting::Direct { votes, delegations, prior } => + (votes.into_inner(), delegations, prior), _ => panic!("Votes are not direct"), }; diff --git a/precompiles/precompile-registry/src/lib.rs b/precompiles/precompile-registry/src/lib.rs index 5a1e864a1..f3d27795e 100644 --- a/precompiles/precompile-registry/src/lib.rs +++ b/precompiles/precompile-registry/src/lib.rs @@ -69,9 +69,8 @@ where .is_active_precompile(address.0, handle.remaining_gas()) { IsPrecompileResult::Answer { is_precompile, .. } => Ok(is_precompile), - IsPrecompileResult::OutOfGas => { - Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }) - }, + IsPrecompileResult::OutOfGas => + Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }), } } diff --git a/precompiles/precompile-registry/src/mock.rs b/precompiles/precompile-registry/src/mock.rs index 45bcc8458..079d3e658 100644 --- a/precompiles/precompile-registry/src/mock.rs +++ b/precompiles/precompile-registry/src/mock.rs @@ -19,8 +19,7 @@ //! Test utilities use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, pallet_prelude::*, parameter_types}; +use frame_support::{construct_runtime, derive_impl, pallet_prelude::*, parameter_types}; use pallet_evm::{EnsureAddressNever, EnsureAddressRoot}; use precompile_utils::{mock_account, precompile_set::*, testing::MockAccount}; use sp_runtime::{BuildStorage, Perbill}; diff --git a/precompiles/preimage/src/mock.rs b/precompiles/preimage/src/mock.rs index 9840a5693..09e1459d2 100644 --- a/precompiles/preimage/src/mock.rs +++ b/precompiles/preimage/src/mock.rs @@ -18,8 +18,7 @@ //! Test utilities use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, parameter_types, weights::Weight}; +use frame_support::{construct_runtime, derive_impl, parameter_types, weights::Weight}; use frame_system::EnsureRoot; use pallet_evm::{EnsureAddressNever, EnsureAddressRoot}; use precompile_utils::{precompile_set::*, testing::MockAccount}; diff --git a/precompiles/proxy/src/lib.rs b/precompiles/proxy/src/lib.rs index 450732435..5b3dfccd8 100644 --- a/precompiles/proxy/src/lib.rs +++ b/precompiles/proxy/src/lib.rs @@ -60,9 +60,8 @@ where fn is_allowed(_caller: H160, selector: Option) -> bool { match selector { None => false, - Some(selector) => { - ProxyPrecompileCall::::is_proxy_selectors().contains(&selector) - }, + Some(selector) => + ProxyPrecompileCall::::is_proxy_selectors().contains(&selector), } } @@ -92,12 +91,11 @@ where fn is_allowed(_caller: H160, selector: Option) -> bool { match selector { None => false, - Some(selector) => { - ProxyPrecompileCall::::is_proxy_selectors().contains(&selector) - || ProxyPrecompileCall::::proxy_selectors().contains(&selector) - || ProxyPrecompileCall::::proxy_force_type_selectors() - .contains(&selector) - }, + Some(selector) => + ProxyPrecompileCall::::is_proxy_selectors().contains(&selector) || + ProxyPrecompileCall::::proxy_selectors().contains(&selector) || + ProxyPrecompileCall::::proxy_force_type_selectors() + .contains(&selector), } } @@ -419,9 +417,8 @@ where // Return subcall result match reason { ExitReason::Fatal(exit_status) => Err(PrecompileFailure::Fatal { exit_status }), - ExitReason::Revert(exit_status) => { - Err(PrecompileFailure::Revert { exit_status, output }) - }, + ExitReason::Revert(exit_status) => + Err(PrecompileFailure::Revert { exit_status, output }), ExitReason::Error(exit_status) => Err(PrecompileFailure::Error { exit_status }), ExitReason::Succeed(_) => Ok(()), } diff --git a/precompiles/proxy/src/mock.rs b/precompiles/proxy/src/mock.rs index e9584c444..b1e097fb6 100644 --- a/precompiles/proxy/src/mock.rs +++ b/precompiles/proxy/src/mock.rs @@ -18,8 +18,9 @@ //! Test utilities use crate::{ProxyPrecompile, ProxyPrecompileCall}; -use frame_support::derive_impl; -use frame_support::{construct_runtime, parameter_types, traits::InstanceFilter, weights::Weight}; +use frame_support::{ + construct_runtime, derive_impl, parameter_types, traits::InstanceFilter, weights::Weight, +}; use pallet_evm::{EnsureAddressNever, EnsureAddressOrigin, SubstrateBlockHashMapping}; use precompile_utils::{ precompile_set::{ diff --git a/precompiles/services/src/lib.rs b/precompiles/services/src/lib.rs index 324e783af..d68bdd5ca 100644 --- a/precompiles/services/src/lib.rs +++ b/precompiles/services/src/lib.rs @@ -7,8 +7,7 @@ use pallet_services::types::BalanceOf; use parity_scale_codec::Decode; use precompile_utils::prelude::*; use sp_core::U256; -use sp_runtime::traits::Dispatchable; -use sp_runtime::Percent; +use sp_runtime::{traits::Dispatchable, Percent}; use sp_std::{marker::PhantomData, vec::Vec}; use tangle_primitives::services::{Field, OperatorPreferences, ServiceBlueprint}; @@ -280,11 +279,12 @@ where Ok(()) } - /// Slash an operator (offender) for a service id with a given percent of their exposed stake for that service. + /// Slash an operator (offender) for a service id with a given percent of their exposed stake + /// for that service. /// /// The caller needs to be an authorized Slash Origin for this service. - /// Note that this does not apply the slash directly, but instead schedules a deferred call to apply the slash - /// by another entity. + /// Note that this does not apply the slash directly, but instead schedules a deferred call to + /// apply the slash by another entity. #[precompile::public("slash(bytes,uint256,uint8)")] fn slash( handle: &mut impl PrecompileHandle, diff --git a/precompiles/services/src/mock.rs b/precompiles/services/src/mock.rs index aab536592..f220d1ed6 100644 --- a/precompiles/services/src/mock.rs +++ b/precompiles/services/src/mock.rs @@ -19,11 +19,10 @@ use frame_election_provider_support::{ bounds::{ElectionBounds, ElectionBoundsBuilder}, onchain, SequentialPhragmen, }; -use frame_support::derive_impl; -use frame_support::pallet_prelude::Hooks; -use frame_support::pallet_prelude::Weight; use frame_support::{ - construct_runtime, parameter_types, + construct_runtime, derive_impl, + pallet_prelude::{Hooks, Weight}, + parameter_types, traits::{ConstU128, OneSessionHandler}, }; use frame_system::EnsureRoot; @@ -33,8 +32,7 @@ use pallet_services::{EvmAddressMapping, EvmGasWeightMapping}; use pallet_session::historical as pallet_session_historical; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -use serde::Deserialize; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use sp_core::{self, sr25519, sr25519::Public as sr25519Public, ConstU32, RuntimeDebug, H160}; use sp_keystore::{testing::MemoryKeystore, KeystoreExt, KeystorePtr}; use sp_runtime::{ diff --git a/precompiles/services/src/mock_evm.rs b/precompiles/services/src/mock_evm.rs index 901b9a0e2..feb5292c5 100644 --- a/precompiles/services/src/mock_evm.rs +++ b/precompiles/services/src/mock_evm.rs @@ -14,11 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Tangle. If not, see . #![allow(clippy::all)] -use crate::mock::{ - AccountId, Balances, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, Timestamp, +use crate::{ + mock::{AccountId, Balances, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, Timestamp}, + ServicesPrecompile, ServicesPrecompileCall, }; -use crate::ServicesPrecompile; -use crate::ServicesPrecompileCall; use fp_evm::FeeCalculator; use frame_support::{ parameter_types, @@ -255,9 +254,8 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => { - call.pre_dispatch_self_contained(info, dispatch_info, len) - }, + RuntimeCall::Ethereum(call) => + call.pre_dispatch_self_contained(info, dispatch_info, len), _ => None, } } @@ -267,9 +265,8 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { - Some(call.dispatch(RuntimeOrigin::from(RawOrigin::EthereumTransaction(info)))) - }, + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => + Some(call.dispatch(RuntimeOrigin::from(RawOrigin::EthereumTransaction(info)))), _ => None, } } diff --git a/precompiles/services/src/tests.rs b/precompiles/services/src/tests.rs index e725bd098..bbf9ed47c 100644 --- a/precompiles/services/src/tests.rs +++ b/precompiles/services/src/tests.rs @@ -1,26 +1,18 @@ -use crate::mock::*; -use crate::mock_evm::PCall; -use crate::mock_evm::PrecompilesValue; +use crate::{ + mock::*, + mock_evm::{PCall, PrecompilesValue}, +}; use frame_support::assert_ok; -use pallet_services::types::ConstraintsOf; -use pallet_services::Instances; -use pallet_services::Operators; -use pallet_services::OperatorsProfile; +use pallet_services::{types::ConstraintsOf, Instances, Operators, OperatorsProfile}; use parity_scale_codec::Encode; -use precompile_utils::prelude::UnboundedBytes; -use precompile_utils::testing::*; -use sp_core::ecdsa; -use sp_core::{H160, U256}; -use sp_runtime::bounded_vec; -use sp_runtime::AccountId32; -use tangle_primitives::services::BlueprintServiceManager; -use tangle_primitives::services::FieldType; -use tangle_primitives::services::JobDefinition; -use tangle_primitives::services::JobMetadata; -use tangle_primitives::services::MasterBlueprintServiceManagerRevision; -use tangle_primitives::services::PriceTargets; -use tangle_primitives::services::ServiceMetadata; -use tangle_primitives::services::{OperatorPreferences, ServiceBlueprint}; +use precompile_utils::{prelude::UnboundedBytes, testing::*}; +use sp_core::{ecdsa, H160, U256}; +use sp_runtime::{bounded_vec, AccountId32}; +use tangle_primitives::services::{ + BlueprintServiceManager, FieldType, JobDefinition, JobMetadata, + MasterBlueprintServiceManagerRevision, OperatorPreferences, PriceTargets, ServiceBlueprint, + ServiceMetadata, +}; fn zero_key() -> ecdsa::Public { ecdsa::Public::from([0; 33]) @@ -53,9 +45,8 @@ fn price_targets(kind: MachineKind) -> PriceTargets { storage_ssd: 100, storage_nvme: 150, }, - MachineKind::Small => { - PriceTargets { cpu: 500, mem: 250, storage_hdd: 25, storage_ssd: 50, storage_nvme: 75 } - }, + MachineKind::Small => + PriceTargets { cpu: 500, mem: 250, storage_hdd: 25, storage_ssd: 50, storage_nvme: 75 }, } } diff --git a/precompiles/staking/src/mock.rs b/precompiles/staking/src/mock.rs index b64e4ec81..a6dbf075f 100644 --- a/precompiles/staking/src/mock.rs +++ b/precompiles/staking/src/mock.rs @@ -21,9 +21,8 @@ #![allow(clippy::all)] use super::*; use frame_election_provider_support::bounds::{ElectionBounds, ElectionBoundsBuilder}; -use frame_support::derive_impl; use frame_support::{ - assert_ok, construct_runtime, + assert_ok, construct_runtime, derive_impl, pallet_prelude::Hooks, parameter_types, traits::{ConstU64, OnFinalize, OnInitialize, OneSessionHandler}, diff --git a/precompiles/tangle-lst/src/lib.rs b/precompiles/tangle-lst/src/lib.rs index 0fdd0681d..fbd1f4e18 100644 --- a/precompiles/tangle-lst/src/lib.rs +++ b/precompiles/tangle-lst/src/lib.rs @@ -14,20 +14,22 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! This file contains the implementation of the MultiAssetDelegationPrecompile struct which provides an -//! interface between the EVM and the native MultiAssetDelegation pallet of the runtime. It allows EVM contracts -//! to call functions of the MultiAssetDelegation pallet, in order to enable EVM accounts to interact with the delegation system. +//! This file contains the implementation of the MultiAssetDelegationPrecompile struct which +//! provides an interface between the EVM and the native MultiAssetDelegation pallet of the runtime. +//! It allows EVM contracts to call functions of the MultiAssetDelegation pallet, in order to enable +//! EVM accounts to interact with the delegation system. //! -//! The MultiAssetDelegationPrecompile struct implements core methods that correspond to the functions of the -//! MultiAssetDelegation pallet. These methods can be called from EVM contracts. They include functions to join as an operator, -//! delegate assets, withdraw assets, etc. +//! The MultiAssetDelegationPrecompile struct implements core methods that correspond to the +//! functions of the MultiAssetDelegation pallet. These methods can be called from EVM contracts. +//! They include functions to join as an operator, delegate assets, withdraw assets, etc. //! //! Each method records the gas cost for the operation, performs the requested operation, and //! returns the result in a format that can be used by the EVM. //! -//! The MultiAssetDelegationPrecompile struct is generic over the Runtime type, which is the type of the runtime -//! that includes the MultiAssetDelegation pallet. This allows the precompile to work with any runtime that -//! includes the MultiAssetDelegation pallet and meets the other trait bounds required by the precompile. +//! The MultiAssetDelegationPrecompile struct is generic over the Runtime type, which is the type of +//! the runtime that includes the MultiAssetDelegation pallet. This allows the precompile to work +//! with any runtime that includes the MultiAssetDelegation pallet and meets the other trait bounds +//! required by the precompile. #![cfg_attr(not(feature = "std"), no_std)] @@ -44,8 +46,7 @@ use pallet_evm::AddressMapping; use pallet_tangle_lst::{BondExtra, PoolId, PoolState}; use precompile_utils::prelude::*; use sp_core::{H160, H256, U256}; -use sp_runtime::traits::Dispatchable; -use sp_runtime::traits::StaticLookup; +use sp_runtime::traits::{Dispatchable, StaticLookup}; use sp_std::{marker::PhantomData, vec::Vec}; use tangle_primitives::types::WrappedAccountId32; diff --git a/precompiles/tangle-lst/src/mock.rs b/precompiles/tangle-lst/src/mock.rs index 39c20ed0b..dd8edf877 100644 --- a/precompiles/tangle-lst/src/mock.rs +++ b/precompiles/tangle-lst/src/mock.rs @@ -17,10 +17,12 @@ //! Test utilities use super::*; use crate::{TangleLstPrecompile, TangleLstPrecompileCall}; -use frame_support::derive_impl; -use frame_support::traits::AsEnsureOriginWithArg; -use frame_support::PalletId; -use frame_support::{construct_runtime, parameter_types, traits::ConstU64, weights::Weight}; +use frame_support::{ + construct_runtime, derive_impl, parameter_types, + traits::{AsEnsureOriginWithArg, ConstU64}, + weights::Weight, + PalletId, +}; use pallet_evm::{EnsureAddressNever, EnsureAddressOrigin, SubstrateBlockHashMapping}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use precompile_utils::precompile_set::{AddressU64, PrecompileAt, PrecompileSetBuilder}; @@ -30,18 +32,11 @@ use sp_core::{ sr25519::{Public as sr25519Public, Signature}, ConstU32, H160, U256, }; -use sp_runtime::traits::Convert; -use sp_runtime::DispatchError; -use sp_runtime::DispatchResult; -use sp_runtime::FixedU128; -use sp_runtime::Perbill; use sp_runtime::{ - traits::{IdentifyAccount, Verify}, - AccountId32, BuildStorage, + traits::{Convert, IdentifyAccount, Verify}, + AccountId32, BuildStorage, DispatchError, DispatchResult, FixedU128, Perbill, }; -use sp_staking::EraIndex; -use sp_staking::OnStakingUpdate; -use sp_staking::Stake; +use sp_staking::{EraIndex, OnStakingUpdate, Stake}; use sp_std::collections::btree_map::BTreeMap; pub type AccountId = <::Signer as IdentifyAccount>::AccountId; diff --git a/precompiles/verify-bls381-signature/src/mock.rs b/precompiles/verify-bls381-signature/src/mock.rs index 3474c6fdd..4e98b9019 100644 --- a/precompiles/verify-bls381-signature/src/mock.rs +++ b/precompiles/verify-bls381-signature/src/mock.rs @@ -16,8 +16,7 @@ //! Test utilities use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, parameter_types, weights::Weight}; +use frame_support::{construct_runtime, derive_impl, parameter_types, weights::Weight}; use pallet_evm::{AddressMapping, EnsureAddressNever, EnsureAddressRoot}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use precompile_utils::{precompile_set::*, testing::MockAccount}; diff --git a/precompiles/verify-ecdsa-secp256k1-signature/src/mock.rs b/precompiles/verify-ecdsa-secp256k1-signature/src/mock.rs index 8d223e1a5..1e63814d5 100644 --- a/precompiles/verify-ecdsa-secp256k1-signature/src/mock.rs +++ b/precompiles/verify-ecdsa-secp256k1-signature/src/mock.rs @@ -16,8 +16,7 @@ //! Test utilities use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, parameter_types, weights::Weight}; +use frame_support::{construct_runtime, derive_impl, parameter_types, weights::Weight}; use pallet_evm::{AddressMapping, EnsureAddressNever, EnsureAddressRoot}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use precompile_utils::{precompile_set::*, testing::MockAccount}; diff --git a/precompiles/verify-ecdsa-secp256r1-signature/src/mock.rs b/precompiles/verify-ecdsa-secp256r1-signature/src/mock.rs index c17ec8bd3..17c714e4d 100644 --- a/precompiles/verify-ecdsa-secp256r1-signature/src/mock.rs +++ b/precompiles/verify-ecdsa-secp256r1-signature/src/mock.rs @@ -16,8 +16,7 @@ #![allow(clippy::all)] //! Test utilities use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, parameter_types, weights::Weight}; +use frame_support::{construct_runtime, derive_impl, parameter_types, weights::Weight}; use pallet_evm::{AddressMapping, EnsureAddressNever, EnsureAddressRoot}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use precompile_utils::{precompile_set::*, testing::MockAccount}; diff --git a/precompiles/verify-ecdsa-stark-signature/src/mock.rs b/precompiles/verify-ecdsa-stark-signature/src/mock.rs index 615cd2608..7b684ac7e 100644 --- a/precompiles/verify-ecdsa-stark-signature/src/mock.rs +++ b/precompiles/verify-ecdsa-stark-signature/src/mock.rs @@ -16,8 +16,7 @@ //! Test utilities use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, parameter_types, weights::Weight}; +use frame_support::{construct_runtime, derive_impl, parameter_types, weights::Weight}; use pallet_evm::{AddressMapping, EnsureAddressNever, EnsureAddressRoot}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use precompile_utils::{precompile_set::*, testing::MockAccount}; diff --git a/precompiles/verify-schnorr-signatures/src/mock.rs b/precompiles/verify-schnorr-signatures/src/mock.rs index b5a3849dd..6e01097e1 100644 --- a/precompiles/verify-schnorr-signatures/src/mock.rs +++ b/precompiles/verify-schnorr-signatures/src/mock.rs @@ -16,8 +16,7 @@ //! Test utilities use super::*; -use frame_support::derive_impl; -use frame_support::{construct_runtime, parameter_types, weights::Weight}; +use frame_support::{construct_runtime, derive_impl, parameter_types, weights::Weight}; use pallet_evm::{AddressMapping, EnsureAddressNever, EnsureAddressRoot}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use precompile_utils::{precompile_set::*, testing::MockAccount}; diff --git a/primitives/rpc/evm-tracing-events/src/evm.rs b/primitives/rpc/evm-tracing-events/src/evm.rs index 2b997eaeb..688861fdd 100644 --- a/primitives/rpc/evm-tracing-events/src/evm.rs +++ b/primitives/rpc/evm-tracing-events/src/evm.rs @@ -61,9 +61,8 @@ impl From for CreateScheme { fn from(i: evm_runtime::CreateScheme) -> Self { match i { evm_runtime::CreateScheme::Legacy { caller } => Self::Legacy { caller }, - evm_runtime::CreateScheme::Create2 { caller, code_hash, salt } => { - Self::Create2 { caller, code_hash, salt } - }, + evm_runtime::CreateScheme::Create2 { caller, code_hash, salt } => + Self::Create2 { caller, code_hash, salt }, evm_runtime::CreateScheme::Fixed(address) => Self::Fixed(address), } } @@ -167,15 +166,12 @@ impl<'a> From> for EvmEvent { init_code: init_code.to_vec(), target_gas, }, - evm::tracing::Event::Suicide { address, target, balance } => { - Self::Suicide { address, target, balance } - }, - evm::tracing::Event::Exit { reason, return_value } => { - Self::Exit { reason: reason.clone(), return_value: return_value.to_vec() } - }, - evm::tracing::Event::TransactCall { caller, address, value, data, gas_limit } => { - Self::TransactCall { caller, address, value, data: data.to_vec(), gas_limit } - }, + evm::tracing::Event::Suicide { address, target, balance } => + Self::Suicide { address, target, balance }, + evm::tracing::Event::Exit { reason, return_value } => + Self::Exit { reason: reason.clone(), return_value: return_value.to_vec() }, + evm::tracing::Event::TransactCall { caller, address, value, data, gas_limit } => + Self::TransactCall { caller, address, value, data: data.to_vec(), gas_limit }, evm::tracing::Event::TransactCreate { caller, value, diff --git a/primitives/rpc/evm-tracing-events/src/gasometer.rs b/primitives/rpc/evm-tracing-events/src/gasometer.rs index 85d8352ba..d1fbb453e 100644 --- a/primitives/rpc/evm-tracing-events/src/gasometer.rs +++ b/primitives/rpc/evm-tracing-events/src/gasometer.rs @@ -59,15 +59,12 @@ pub enum GasometerEvent { impl From for GasometerEvent { fn from(i: evm_gasometer::tracing::Event) -> Self { match i { - evm_gasometer::tracing::Event::RecordCost { cost, snapshot } => { - Self::RecordCost { cost, snapshot: snapshot.into() } - }, - evm_gasometer::tracing::Event::RecordRefund { refund, snapshot } => { - Self::RecordRefund { refund, snapshot: snapshot.into() } - }, - evm_gasometer::tracing::Event::RecordStipend { stipend, snapshot } => { - Self::RecordStipend { stipend, snapshot: snapshot.into() } - }, + evm_gasometer::tracing::Event::RecordCost { cost, snapshot } => + Self::RecordCost { cost, snapshot: snapshot.into() }, + evm_gasometer::tracing::Event::RecordRefund { refund, snapshot } => + Self::RecordRefund { refund, snapshot: snapshot.into() }, + evm_gasometer::tracing::Event::RecordStipend { stipend, snapshot } => + Self::RecordStipend { stipend, snapshot: snapshot.into() }, evm_gasometer::tracing::Event::RecordDynamicCost { gas_cost, memory_gas, @@ -79,9 +76,8 @@ impl From for GasometerEvent { gas_refund, snapshot: snapshot.into(), }, - evm_gasometer::tracing::Event::RecordTransaction { cost, snapshot } => { - Self::RecordTransaction { cost, snapshot: snapshot.into() } - }, + evm_gasometer::tracing::Event::RecordTransaction { cost, snapshot } => + Self::RecordTransaction { cost, snapshot: snapshot.into() }, } } } diff --git a/primitives/rpc/evm-tracing-events/src/runtime.rs b/primitives/rpc/evm-tracing-events/src/runtime.rs index 089932d55..ad738f739 100644 --- a/primitives/rpc/evm-tracing-events/src/runtime.rs +++ b/primitives/rpc/evm-tracing-events/src/runtime.rs @@ -92,7 +92,7 @@ impl RuntimeEvent { filter: crate::StepEventFilter, ) -> Self { match i { - evm_runtime::tracing::Event::Step { context, opcode, position, stack, memory } => { + evm_runtime::tracing::Event::Step { context, opcode, position, stack, memory } => Self::Step { context: context.clone().into(), opcode: opcodes_string(opcode), @@ -102,8 +102,7 @@ impl RuntimeEvent { }, stack: if filter.enable_stack { Some(stack.into()) } else { None }, memory: if filter.enable_memory { Some(memory.into()) } else { None }, - } - }, + }, evm_runtime::tracing::Event::StepResult { result, return_value } => Self::StepResult { result: match result { Ok(_) => Ok(()), @@ -114,12 +113,10 @@ impl RuntimeEvent { }, return_value: return_value.to_vec(), }, - evm_runtime::tracing::Event::SLoad { address, index, value } => { - Self::SLoad { address, index, value } - }, - evm_runtime::tracing::Event::SStore { address, index, value } => { - Self::SStore { address, index, value } - }, + evm_runtime::tracing::Event::SLoad { address, index, value } => + Self::SLoad { address, index, value }, + evm_runtime::tracing::Event::SStore { address, index, value } => + Self::SStore { address, index, value }, } } } diff --git a/primitives/src/chain_identifier.rs b/primitives/src/chain_identifier.rs index 72155a8a7..d916c2a2a 100644 --- a/primitives/src/chain_identifier.rs +++ b/primitives/src/chain_identifier.rs @@ -65,14 +65,14 @@ impl TypedChainId { #[must_use] pub const fn underlying_chain_id(&self) -> u32 { match self { - TypedChainId::Evm(id) - | TypedChainId::Substrate(id) - | TypedChainId::PolkadotParachain(id) - | TypedChainId::KusamaParachain(id) - | TypedChainId::RococoParachain(id) - | TypedChainId::Cosmos(id) - | TypedChainId::Solana(id) - | TypedChainId::Ink(id) => *id, + TypedChainId::Evm(id) | + TypedChainId::Substrate(id) | + TypedChainId::PolkadotParachain(id) | + TypedChainId::KusamaParachain(id) | + TypedChainId::RococoParachain(id) | + TypedChainId::Cosmos(id) | + TypedChainId::Solana(id) | + TypedChainId::Ink(id) => *id, Self::None => 0, } } diff --git a/primitives/src/services/field.rs b/primitives/src/services/field.rs index 55f09cf4e..934d27344 100644 --- a/primitives/src/services/field.rs +++ b/primitives/src/services/field.rs @@ -307,18 +307,16 @@ impl PartialEq for Field { (Self::Int64(_), FieldType::Int64) => true, (Self::String(_), FieldType::String) => true, (Self::Bytes(_), FieldType::Bytes) => true, - (Self::Array(a), FieldType::Array(len, b)) => { - a.len() == *len as usize && a.iter().all(|f| f.eq(b.as_ref())) - }, + (Self::Array(a), FieldType::Array(len, b)) => + a.len() == *len as usize && a.iter().all(|f| f.eq(b.as_ref())), (Self::List(a), FieldType::List(b)) => a.iter().all(|f| f.eq(b.as_ref())), (Self::AccountId(_), FieldType::AccountId) => true, - (Self::Struct(_, fields_a), FieldType::Struct(_, fields_b)) => { - fields_a.into_iter().len() == fields_b.into_iter().len() - && fields_a + (Self::Struct(_, fields_a), FieldType::Struct(_, fields_b)) => + fields_a.into_iter().len() == fields_b.into_iter().len() && + fields_a .into_iter() .zip(fields_b) - .all(|((_, v_a), (_, v_b))| v_a.as_ref().eq(v_b)) - }, + .all(|((_, v_a), (_, v_b))| v_a.as_ref().eq(v_b)), _ => false, } } @@ -528,7 +526,7 @@ impl<'de, S: Get> serde::Deserialize<'de> for BoundedString { { struct StringVisitor>(PhantomData); - impl<'de, S: Get> serde::de::Visitor<'de> for StringVisitor { + impl> serde::de::Visitor<'_> for StringVisitor { type Value = String; fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { diff --git a/primitives/src/services/mod.rs b/primitives/src/services/mod.rs index 117b7aa85..6bb4f47b2 100644 --- a/primitives/src/services/mod.rs +++ b/primitives/src/services/mod.rs @@ -361,12 +361,13 @@ pub struct ServiceBlueprint { /// The request hook that will be called before creating a service from the service blueprint. /// The parameters that are required for the service request. pub request_params: BoundedVec, - /// A Blueprint Manager is a smart contract that implements the `IBlueprintServiceManager` interface. + /// A Blueprint Manager is a smart contract that implements the `IBlueprintServiceManager` + /// interface. pub manager: BlueprintServiceManager, /// The Revision number of the Master Blueprint Service Manager. /// - /// If not sure what to use, use `MasterBlueprintServiceManagerRevision::default()` which will use - /// the latest revision available. + /// If not sure what to use, use `MasterBlueprintServiceManagerRevision::default()` which will + /// use the latest revision available. pub master_manager_revision: MasterBlueprintServiceManagerRevision, /// The gadget that will be executed for the service. pub gadget: Gadget, @@ -484,12 +485,10 @@ impl ServiceBlueprint { }, // Master Manager Revision match self.master_manager_revision { - MasterBlueprintServiceManagerRevision::Latest => { - ethabi::Token::Uint(ethabi::Uint::MAX) - }, - MasterBlueprintServiceManagerRevision::Specific(rev) => { - ethabi::Token::Uint(rev.into()) - }, + MasterBlueprintServiceManagerRevision::Latest => + ethabi::Token::Uint(ethabi::Uint::MAX), + MasterBlueprintServiceManagerRevision::Specific(rev) => + ethabi::Token::Uint(rev.into()), }, // Gadget ? ]) @@ -593,8 +592,9 @@ pub struct Service { /// The Permitted caller(s) of the service. pub permitted_callers: BoundedVec, /// The Selected operators(s) for this service with their restaking Percentage. - // This a Vec instead of a BTreeMap because the number of operators is expected to be small (smaller than 512) - // and the overhead of a BTreeMap is not worth it, plus BoundedBTreeMap is not serde compatible. + // This a Vec instead of a BTreeMap because the number of operators is expected to be small + // (smaller than 512) and the overhead of a BTreeMap is not worth it, plus BoundedBTreeMap is + // not serde compatible. pub operators: BoundedVec<(AccountId, Percent), C::MaxOperatorsPerService>, /// Asset(s) used to secure the service instance. pub assets: BoundedVec, diff --git a/runtime/mainnet/src/frontier_evm.rs b/runtime/mainnet/src/frontier_evm.rs index 38d046f19..e415fb75c 100644 --- a/runtime/mainnet/src/frontier_evm.rs +++ b/runtime/mainnet/src/frontier_evm.rs @@ -119,21 +119,20 @@ impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType { ) -> precompile_utils::EvmResult { Ok(match self { ProxyType::Any => true, - ProxyType::Governance => { - call.value == U256::zero() - && matches!( + ProxyType::Governance => + call.value == U256::zero() && + matches!( PrecompileName::from_address(call.to.0), Some(ref precompile) if is_governance_precompile(precompile) - ) - }, + ), // The proxy precompile does not contain method cancel_proxy ProxyType::CancelProxy => false, ProxyType::Balances => { // Allow only "simple" accounts as recipient (no code nor precompile). // Note: Checking the presence of the code is not enough because some precompiles // have no code. - !recipient_has_code - && !precompile_utils::precompile_set::is_precompile_or_fail::( + !recipient_has_code && + !precompile_utils::precompile_set::is_precompile_or_fail::( call.to.0, gas, )? }, diff --git a/runtime/mainnet/src/lib.rs b/runtime/mainnet/src/lib.rs index 120ff186d..f287cf6e7 100644 --- a/runtime/mainnet/src/lib.rs +++ b/runtime/mainnet/src/lib.rs @@ -656,8 +656,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) - .expect("input is padded with zeroes; qed") - % max.saturating_add(1); + .expect("input is padded with zeroes; qed") % + max.saturating_add(1); random as usize }, }; @@ -1148,15 +1148,15 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances(..) - | RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) + RuntimeCall::Balances(..) | + RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) ), ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) - | RuntimeCall::Council(..) - | RuntimeCall::Elections(..) - | RuntimeCall::Treasury(..) + RuntimeCall::Democracy(..) | + RuntimeCall::Council(..) | + RuntimeCall::Elections(..) | + RuntimeCall::Treasury(..) ), ProxyType::Staking => { matches!(c, RuntimeCall::Staking(..)) @@ -1465,9 +1465,8 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => { - call.pre_dispatch_self_contained(info, dispatch_info, len) - }, + RuntimeCall::Ethereum(call) => + call.pre_dispatch_self_contained(info, dispatch_info, len), _ => None, } } @@ -1477,11 +1476,10 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), - ))) - }, + ))), _ => None, } } diff --git a/runtime/testnet/src/lib.rs b/runtime/testnet/src/lib.rs index 2c1695cf0..be3080a3b 100644 --- a/runtime/testnet/src/lib.rs +++ b/runtime/testnet/src/lib.rs @@ -663,8 +663,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) - .expect("input is padded with zeroes; qed") - % max.saturating_add(1); + .expect("input is padded with zeroes; qed") % + max.saturating_add(1); random as usize }, }; @@ -1146,15 +1146,15 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances(..) - | RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) + RuntimeCall::Balances(..) | + RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) ), ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) - | RuntimeCall::Council(..) - | RuntimeCall::Elections(..) - | RuntimeCall::Treasury(..) + RuntimeCall::Democracy(..) | + RuntimeCall::Council(..) | + RuntimeCall::Elections(..) | + RuntimeCall::Treasury(..) ), ProxyType::Staking => { matches!(c, RuntimeCall::Staking(..)) @@ -1387,9 +1387,8 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => { - call.pre_dispatch_self_contained(info, dispatch_info, len) - }, + RuntimeCall::Ethereum(call) => + call.pre_dispatch_self_contained(info, dispatch_info, len), _ => None, } } @@ -1399,11 +1398,10 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), - ))) - }, + ))), _ => None, } } diff --git a/rust-toolchain.toml b/rust-toolchain.toml index e90983bca..79d88250b 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "1.79" +channel = "nightly" components = ["rustfmt", "clippy", "rust-src", "rust-analyzer"] targets = ["wasm32-unknown-unknown"] From c588b197b303a6c53b075fd368d3de53007c0771 Mon Sep 17 00:00:00 2001 From: Drew Stone Date: Mon, 2 Dec 2024 12:42:47 -0700 Subject: [PATCH 5/9] chore: add proper toolchain --- rust-toolchain.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 79d88250b..e90983bca 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "nightly" +channel = "1.79" components = ["rustfmt", "clippy", "rust-src", "rust-analyzer"] targets = ["wasm32-unknown-unknown"] From 9232054d3761930d365910376f31c1ef1bc67c6a Mon Sep 17 00:00:00 2001 From: Drew Stone Date: Mon, 2 Dec 2024 16:42:43 -0700 Subject: [PATCH 6/9] chore: fix --- pallets/tangle-lst/src/lib.rs | 37 ++++++++++++---------- pallets/tangle-lst/src/types/commission.rs | 2 +- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/pallets/tangle-lst/src/lib.rs b/pallets/tangle-lst/src/lib.rs index ba2d426c8..317d5ffcb 100644 --- a/pallets/tangle-lst/src/lib.rs +++ b/pallets/tangle-lst/src/lib.rs @@ -107,29 +107,34 @@ #![cfg_attr(not(feature = "std"), no_std)] use codec::Codec; +use frame_support::traits::fungibles; +use frame_support::traits::fungibles::Create; +use frame_support::traits::fungibles::Inspect as FungiblesInspect; +use frame_support::traits::fungibles::Mutate as FungiblesMutate; +use frame_support::traits::tokens::Precision; +use frame_support::traits::tokens::Preservation; +use frame_support::traits::Currency; +use frame_support::traits::ExistenceRequirement; +use frame_support::traits::LockableCurrency; +use frame_support::traits::ReservableCurrency; use frame_support::{ defensive, defensive_assert, ensure, pallet_prelude::{MaxEncodedLen, *}, storage::bounded_btree_map::BoundedBTreeMap, traits::{ - fungibles, - fungibles::{Create, Inspect as FungiblesInspect, Mutate as FungiblesMutate}, - tokens::{Fortitude, Precision, Preservation}, - Currency, Defensive, DefensiveOption, DefensiveResult, DefensiveSaturating, - ExistenceRequirement, Get, LockableCurrency, ReservableCurrency, + tokens::Fortitude, Defensive, DefensiveOption, DefensiveResult, DefensiveSaturating, Get, }, DefaultNoBound, PalletError, }; use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_core::U256; -use sp_runtime::{ - traits::{ - AccountIdConversion, AtLeast32BitUnsigned, Bounded, CheckedAdd, Convert, Saturating, - StaticLookup, Zero, - }, - FixedPointNumber, Perbill, +use sp_runtime::traits::AccountIdConversion; +use sp_runtime::traits::{ + AtLeast32BitUnsigned, Bounded, CheckedAdd, Convert, Saturating, StaticLookup, Zero, }; +use sp_runtime::FixedPointNumber; +use sp_runtime::Perbill; use sp_staking::{EraIndex, StakingInterface}; use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, ops::Div, vec::Vec}; @@ -1534,8 +1539,7 @@ impl Pallet { let bouncer = T::Lookup::lookup(bouncer)?; // ensure that pool token can be created - // if this fails, it means that the pool token already exists or the token counter needs to - // be incremented correctly + // if this fails, it means that the pool token already exists or the token counter needs to be incremented correctly ensure!( T::Fungibles::total_issuance(pool_id.into()) == 0_u32.into(), Error::::PoolTokenCreationFailed @@ -1546,7 +1550,7 @@ impl Pallet { ensure!(amount >= Pallet::::depositor_min_bond(), Error::::MinimumBondNotMet); ensure!( - MaxPools::::get().is_none_or(|max_pools| BondedPools::::count() < max_pools), + MaxPools::::get().map_or(true, |max_pools| BondedPools::::count() < max_pools), Error::::MaxPools ); let mut bonded_pool = BondedPool::::new( @@ -1614,8 +1618,9 @@ impl Pallet { bonded_pool.ok_to_join()?; let (_points_issued, bonded) = match extra { - BondExtra::FreeBalance(amount) => - (bonded_pool.try_bond_funds(&member_account, amount, BondType::Later)?, amount), + BondExtra::FreeBalance(amount) => { + (bonded_pool.try_bond_funds(&member_account, amount, BondType::Later)?, amount) + }, }; bonded_pool.ok_to_be_open()?; diff --git a/pallets/tangle-lst/src/types/commission.rs b/pallets/tangle-lst/src/types/commission.rs index 845cbd754..9fbee7550 100644 --- a/pallets/tangle-lst/src/types/commission.rs +++ b/pallets/tangle-lst/src/types/commission.rs @@ -116,7 +116,7 @@ impl Commission { Error::::CommissionExceedsGlobalMaximum ); ensure!( - self.max.is_none_or(|m| commission <= &m), + self.max.map_or(true, |m| commission <= &m), Error::::CommissionExceedsMaximum ); if commission.is_zero() { From 386eacc7564f14086f0ce5c468402129a88cc376 Mon Sep 17 00:00:00 2001 From: Drew Stone Date: Mon, 2 Dec 2024 16:42:56 -0700 Subject: [PATCH 7/9] chore: fmt --- .../evm-tracing/src/formatters/call_tracer.rs | 29 ++++---- .../src/formatters/trace_filter.rs | 15 ++-- client/evm-tracing/src/listeners/call_list.rs | 71 +++++++++++-------- client/evm-tracing/src/listeners/raw.rs | 4 +- client/rpc-core/txpool/src/types/content.rs | 15 ++-- client/rpc/debug/src/lib.rs | 58 +++++++++------ client/rpc/trace/src/lib.rs | 35 +++++---- frost/frost-ristretto255/src/lib.rs | 5 +- frost/src/round1.rs | 6 +- frost/src/signature.rs | 4 +- node/src/distributions/mainnet.rs | 36 +++++----- node/src/service.rs | 8 +-- pallets/claims/src/lib.rs | 5 +- pallets/claims/src/utils/mod.rs | 5 +- pallets/services/rpc/src/lib.rs | 10 +-- pallets/services/src/functions.rs | 5 +- pallets/services/src/lib.rs | 5 +- pallets/services/src/mock.rs | 5 +- pallets/services/src/mock_evm.rs | 10 +-- pallets/services/src/tests.rs | 5 +- pallets/tangle-lst/src/types/bonded_pool.rs | 10 +-- precompiles/assets-erc20/src/lib.rs | 4 +- precompiles/assets-erc20/src/tests.rs | 4 +- precompiles/balances-erc20/src/tests.rs | 4 +- precompiles/batch/src/lib.rs | 40 ++++++----- precompiles/call-permit/src/lib.rs | 5 +- .../multi-asset-delegation/src/tests.rs | 8 +-- precompiles/pallet-democracy/src/tests.rs | 36 ++++++---- precompiles/precompile-registry/src/lib.rs | 5 +- precompiles/proxy/src/lib.rs | 21 +++--- precompiles/services/src/mock_evm.rs | 10 +-- precompiles/services/src/tests.rs | 5 +- primitives/rpc/evm-tracing-events/src/evm.rs | 20 +++--- .../rpc/evm-tracing-events/src/gasometer.rs | 20 +++--- .../rpc/evm-tracing-events/src/runtime.rs | 15 ++-- primitives/src/chain_identifier.rs | 16 ++--- primitives/src/services/field.rs | 14 ++-- primitives/src/services/mod.rs | 10 +-- runtime/mainnet/src/frontier_evm.rs | 13 ++-- runtime/mainnet/src/lib.rs | 26 +++---- runtime/testnet/src/lib.rs | 26 +++---- 41 files changed, 372 insertions(+), 276 deletions(-) diff --git a/client/evm-tracing/src/formatters/call_tracer.rs b/client/evm-tracing/src/formatters/call_tracer.rs index 165d79c3c..6b2d7ae4a 100644 --- a/client/evm-tracing/src/formatters/call_tracer.rs +++ b/client/evm-tracing/src/formatters/call_tracer.rs @@ -56,13 +56,14 @@ impl super::ResponseFormatter for Formatter { gas_used, trace_address: Some(trace_address.clone()), inner: match inner.clone() { - BlockscoutCallInner::Call { input, to, res, call_type } => + BlockscoutCallInner::Call { input, to, res, call_type } => { CallTracerInner::Call { call_type: match call_type { CallType::Call => "CALL".as_bytes().to_vec(), CallType::CallCode => "CALLCODE".as_bytes().to_vec(), - CallType::DelegateCall => - "DELEGATECALL".as_bytes().to_vec(), + CallType::DelegateCall => { + "DELEGATECALL".as_bytes().to_vec() + }, CallType::StaticCall => "STATICCALL".as_bytes().to_vec(), }, to, @@ -73,7 +74,8 @@ impl super::ResponseFormatter for Formatter { CallResult::Output { .. } => it.logs.clone(), CallResult::Error { .. } => Vec::new(), }, - }, + } + }, BlockscoutCallInner::Create { init, res } => CallTracerInner::Create { input: init, error: match res { @@ -87,19 +89,21 @@ impl super::ResponseFormatter for Formatter { CreateResult::Error { .. } => None, }, output: match res { - CreateResult::Success { created_contract_code, .. } => - Some(created_contract_code), + CreateResult::Success { created_contract_code, .. } => { + Some(created_contract_code) + }, CreateResult::Error { .. } => None, }, value, call_type: "CREATE".as_bytes().to_vec(), }, - BlockscoutCallInner::SelfDestruct { balance, to } => + BlockscoutCallInner::SelfDestruct { balance, to } => { CallTracerInner::SelfDestruct { value: balance, to, call_type: "SELFDESTRUCT".as_bytes().to_vec(), - }, + } + }, }, calls: Vec::new(), }) @@ -189,10 +193,11 @@ impl super::ResponseFormatter for Formatter { ( Call::CallTracer(CallTracerCall { trace_address: Some(a), .. }), Call::CallTracer(CallTracerCall { trace_address: Some(b), .. }), - ) => - &b[..] == - a.get(0..a.len() - 1) - .expect("non-root element while traversing trace result"), + ) => { + &b[..] + == a.get(0..a.len() - 1) + .expect("non-root element while traversing trace result") + }, _ => unreachable!(), }) { // Remove `trace_address` from result. diff --git a/client/evm-tracing/src/formatters/trace_filter.rs b/client/evm-tracing/src/formatters/trace_filter.rs index f8844c8fd..9bb032107 100644 --- a/client/evm-tracing/src/formatters/trace_filter.rs +++ b/client/evm-tracing/src/formatters/trace_filter.rs @@ -56,11 +56,12 @@ impl super::ResponseFormatter for Formatter { // Can't be known here, must be inserted upstream. block_number: 0, output: match res { - CallResult::Output(output) => + CallResult::Output(output) => { TransactionTraceOutput::Result(TransactionTraceResult::Call { gas_used: trace.gas_used, output, - }), + }) + }, CallResult::Error(error) => TransactionTraceOutput::Error(error), }, subtraces: trace.subtraces, @@ -86,14 +87,16 @@ impl super::ResponseFormatter for Formatter { CreateResult::Success { created_contract_address_hash, created_contract_code, - } => + } => { TransactionTraceOutput::Result(TransactionTraceResult::Create { gas_used: trace.gas_used, code: created_contract_code, address: created_contract_address_hash, - }), - CreateResult::Error { error } => - TransactionTraceOutput::Error(error), + }) + }, + CreateResult::Error { error } => { + TransactionTraceOutput::Error(error) + }, }, subtraces: trace.subtraces, trace_address: trace.trace_address.clone(), diff --git a/client/evm-tracing/src/listeners/call_list.rs b/client/evm-tracing/src/listeners/call_list.rs index 5ca1eb15e..9da8a66a0 100644 --- a/client/evm-tracing/src/listeners/call_list.rs +++ b/client/evm-tracing/src/listeners/call_list.rs @@ -224,9 +224,9 @@ impl Listener { pub fn gasometer_event(&mut self, event: GasometerEvent) { match event { - GasometerEvent::RecordCost { snapshot, .. } | - GasometerEvent::RecordDynamicCost { snapshot, .. } | - GasometerEvent::RecordStipend { snapshot, .. } => { + GasometerEvent::RecordCost { snapshot, .. } + | GasometerEvent::RecordDynamicCost { snapshot, .. } + | GasometerEvent::RecordStipend { snapshot, .. } => { if let Some(context) = self.context_stack.last_mut() { if context.start_gas.is_none() { context.start_gas = Some(snapshot.gas()); @@ -497,12 +497,13 @@ impl Listener { // behavior (like batch precompile does) thus we simply consider this a call. self.call_type = Some(CallType::Call); }, - EvmEvent::Log { address, topics, data } => + EvmEvent::Log { address, topics, data } => { if self.with_log { if let Some(stack) = self.context_stack.last_mut() { stack.logs.push(Log { address, topics, data }); } - }, + } + }, // We ignore other kinds of message if any (new ones may be added in the future). #[allow(unreachable_patterns)] @@ -536,13 +537,15 @@ impl Listener { match context.context_type { ContextType::Call(call_type) => { let res = match &reason { - ExitReason::Succeed(ExitSucceed::Returned) => - CallResult::Output(return_value.to_vec()), + ExitReason::Succeed(ExitSucceed::Returned) => { + CallResult::Output(return_value.to_vec()) + }, ExitReason::Succeed(_) => CallResult::Output(vec![]), ExitReason::Error(error) => CallResult::Error(error_message(error)), - ExitReason::Revert(_) => - CallResult::Error(b"execution reverted".to_vec()), + ExitReason::Revert(_) => { + CallResult::Error(b"execution reverted".to_vec()) + }, ExitReason::Fatal(_) => CallResult::Error(vec![]), }; @@ -568,10 +571,12 @@ impl Listener { created_contract_address_hash: context.to, created_contract_code: return_value.to_vec(), }, - ExitReason::Error(error) => - CreateResult::Error { error: error_message(error) }, - ExitReason::Revert(_) => - CreateResult::Error { error: b"execution reverted".to_vec() }, + ExitReason::Error(error) => { + CreateResult::Error { error: error_message(error) } + }, + ExitReason::Revert(_) => { + CreateResult::Error { error: b"execution reverted".to_vec() } + }, ExitReason::Fatal(_) => CreateResult::Error { error: vec![] }, }; @@ -620,14 +625,15 @@ impl ListenerT for Listener { Event::Gasometer(gasometer_event) => self.gasometer_event(gasometer_event), Event::Runtime(runtime_event) => self.runtime_event(runtime_event), Event::Evm(evm_event) => self.evm_event(evm_event), - Event::CallListNew() => + Event::CallListNew() => { if !self.call_list_first_transaction { self.finish_transaction(); self.skip_next_context = false; self.entries.push(BTreeMap::new()); } else { self.call_list_first_transaction = false; - }, + } + }, }; } @@ -726,8 +732,9 @@ mod tests { target: H160::default(), balance: U256::zero(), }, - TestEvmEvent::Exit => - EvmEvent::Exit { reason: exit_reason.unwrap(), return_value: Vec::new() }, + TestEvmEvent::Exit => { + EvmEvent::Exit { reason: exit_reason.unwrap(), return_value: Vec::new() } + }, TestEvmEvent::TransactCall => EvmEvent::TransactCall { caller: H160::default(), address: H160::default(), @@ -750,8 +757,9 @@ mod tests { gas_limit: 0u64, address: H160::default(), }, - TestEvmEvent::Log => - EvmEvent::Log { address: H160::default(), topics: Vec::new(), data: Vec::new() }, + TestEvmEvent::Log => { + EvmEvent::Log { address: H160::default(), topics: Vec::new(), data: Vec::new() } + }, } } @@ -764,8 +772,9 @@ mod tests { stack: test_stack(), memory: test_memory(), }, - TestRuntimeEvent::StepResult => - RuntimeEvent::StepResult { result: Ok(()), return_value: Vec::new() }, + TestRuntimeEvent::StepResult => { + RuntimeEvent::StepResult { result: Ok(()), return_value: Vec::new() } + }, TestRuntimeEvent::SLoad => RuntimeEvent::SLoad { address: H160::default(), index: H256::default(), @@ -781,20 +790,24 @@ mod tests { fn test_emit_gasometer_event(event_type: TestGasometerEvent) -> GasometerEvent { match event_type { - TestGasometerEvent::RecordCost => - GasometerEvent::RecordCost { cost: 0u64, snapshot: test_snapshot() }, - TestGasometerEvent::RecordRefund => - GasometerEvent::RecordRefund { refund: 0i64, snapshot: test_snapshot() }, - TestGasometerEvent::RecordStipend => - GasometerEvent::RecordStipend { stipend: 0u64, snapshot: test_snapshot() }, + TestGasometerEvent::RecordCost => { + GasometerEvent::RecordCost { cost: 0u64, snapshot: test_snapshot() } + }, + TestGasometerEvent::RecordRefund => { + GasometerEvent::RecordRefund { refund: 0i64, snapshot: test_snapshot() } + }, + TestGasometerEvent::RecordStipend => { + GasometerEvent::RecordStipend { stipend: 0u64, snapshot: test_snapshot() } + }, TestGasometerEvent::RecordDynamicCost => GasometerEvent::RecordDynamicCost { gas_cost: 0u64, memory_gas: 0u64, gas_refund: 0i64, snapshot: test_snapshot(), }, - TestGasometerEvent::RecordTransaction => - GasometerEvent::RecordTransaction { cost: 0u64, snapshot: test_snapshot() }, + TestGasometerEvent::RecordTransaction => { + GasometerEvent::RecordTransaction { cost: 0u64, snapshot: test_snapshot() } + }, } } diff --git a/client/evm-tracing/src/listeners/raw.rs b/client/evm-tracing/src/listeners/raw.rs index c4e7ac328..483ea0a3d 100644 --- a/client/evm-tracing/src/listeners/raw.rs +++ b/client/evm-tracing/src/listeners/raw.rs @@ -277,8 +277,8 @@ impl Listener { _ => (), } }, - RuntimeEvent::SLoad { address: _, index, value } | - RuntimeEvent::SStore { address: _, index, value } => { + RuntimeEvent::SLoad { address: _, index, value } + | RuntimeEvent::SStore { address: _, index, value } => { if let Some(context) = self.context_stack.last_mut() { if !self.disable_storage { context.storage_cache.insert(index, value); diff --git a/client/rpc-core/txpool/src/types/content.rs b/client/rpc-core/txpool/src/types/content.rs index 581be1737..ec98a00f4 100644 --- a/client/rpc-core/txpool/src/types/content.rs +++ b/client/rpc-core/txpool/src/types/content.rs @@ -66,12 +66,15 @@ where impl GetT for Transaction { fn get(hash: H256, from_address: H160, txn: &EthereumTransaction) -> Self { let (nonce, action, value, gas_price, gas_limit, input) = match txn { - EthereumTransaction::Legacy(t) => - (t.nonce, t.action, t.value, t.gas_price, t.gas_limit, t.input.clone()), - EthereumTransaction::EIP2930(t) => - (t.nonce, t.action, t.value, t.gas_price, t.gas_limit, t.input.clone()), - EthereumTransaction::EIP1559(t) => - (t.nonce, t.action, t.value, t.max_fee_per_gas, t.gas_limit, t.input.clone()), + EthereumTransaction::Legacy(t) => { + (t.nonce, t.action, t.value, t.gas_price, t.gas_limit, t.input.clone()) + }, + EthereumTransaction::EIP2930(t) => { + (t.nonce, t.action, t.value, t.gas_price, t.gas_limit, t.input.clone()) + }, + EthereumTransaction::EIP1559(t) => { + (t.nonce, t.action, t.value, t.max_fee_per_gas, t.gas_limit, t.input.clone()) + }, }; Self { hash, diff --git a/client/rpc/debug/src/lib.rs b/client/rpc/debug/src/lib.rs index 69301f4f8..09b2b932c 100644 --- a/client/rpc/debug/src/lib.rs +++ b/client/rpc/debug/src/lib.rs @@ -353,12 +353,15 @@ where let reference_id: BlockId = match request_block_id { RequestBlockId::Number(n) => Ok(BlockId::Number(n.unique_saturated_into())), - RequestBlockId::Tag(RequestBlockTag::Latest) => - Ok(BlockId::Number(client.info().best_number)), - RequestBlockId::Tag(RequestBlockTag::Earliest) => - Ok(BlockId::Number(0u32.unique_saturated_into())), - RequestBlockId::Tag(RequestBlockTag::Pending) => - Err(internal_err("'pending' blocks are not supported")), + RequestBlockId::Tag(RequestBlockTag::Latest) => { + Ok(BlockId::Number(client.info().best_number)) + }, + RequestBlockId::Tag(RequestBlockTag::Earliest) => { + Ok(BlockId::Number(0u32.unique_saturated_into())) + }, + RequestBlockId::Tag(RequestBlockTag::Pending) => { + Err(internal_err("'pending' blocks are not supported")) + }, RequestBlockId::Hash(eth_hash) => { match futures::executor::block_on(frontier_backend_client::load_hash::( client.as_ref(), @@ -470,10 +473,11 @@ where proxy.using(f)?; proxy.finish_transaction(); let response = match tracer_input { - TracerInput::CallTracer => + TracerInput::CallTracer => { client_evm_tracing::formatters::CallTracer::format(proxy) .ok_or("Trace result is empty.") - .map_err(|e| internal_err(format!("{:?}", e))), + .map_err(|e| internal_err(format!("{:?}", e))) + }, _ => Err(internal_err("Bug: failed to resolve the tracer format.".to_string())), }?; @@ -608,17 +612,20 @@ where // Pre-london update, legacy transactions. match transaction { ethereum::TransactionV2::Legacy(tx) => + { #[allow(deprecated)] api.trace_transaction_before_version_4( parent_block_hash, exts, tx, - ), - _ => + ) + }, + _ => { return Err(internal_err( "Bug: pre-london runtime expects legacy transactions" .to_string(), - )), + )) + }, } } }; @@ -659,10 +666,11 @@ where proxy.using(f)?; proxy.finish_transaction(); let response = match tracer_input { - TracerInput::Blockscout => + TracerInput::Blockscout => { client_evm_tracing::formatters::Blockscout::format(proxy) .ok_or("Trace result is empty.") - .map_err(|e| internal_err(format!("{:?}", e))), + .map_err(|e| internal_err(format!("{:?}", e))) + }, TracerInput::CallTracer => { let mut res = client_evm_tracing::formatters::CallTracer::format(proxy) @@ -698,12 +706,15 @@ where let reference_id: BlockId = match request_block_id { RequestBlockId::Number(n) => Ok(BlockId::Number(n.unique_saturated_into())), - RequestBlockId::Tag(RequestBlockTag::Latest) => - Ok(BlockId::Number(client.info().best_number)), - RequestBlockId::Tag(RequestBlockTag::Earliest) => - Ok(BlockId::Number(0u32.unique_saturated_into())), - RequestBlockId::Tag(RequestBlockTag::Pending) => - Err(internal_err("'pending' blocks are not supported")), + RequestBlockId::Tag(RequestBlockTag::Latest) => { + Ok(BlockId::Number(client.info().best_number)) + }, + RequestBlockId::Tag(RequestBlockTag::Earliest) => { + Ok(BlockId::Number(0u32.unique_saturated_into())) + }, + RequestBlockId::Tag(RequestBlockTag::Pending) => { + Err(internal_err("'pending' blocks are not supported")) + }, RequestBlockId::Hash(eth_hash) => { match futures::executor::block_on(frontier_backend_client::load_hash::( client.as_ref(), @@ -740,7 +751,9 @@ where }; if trace_api_version <= 5 { - return Err(internal_err("debug_traceCall not supported with old runtimes".to_string())); + return Err(internal_err( + "debug_traceCall not supported with old runtimes".to_string(), + )); } let TraceCallParams { @@ -847,10 +860,11 @@ where proxy.using(f)?; proxy.finish_transaction(); let response = match tracer_input { - TracerInput::Blockscout => + TracerInput::Blockscout => { client_evm_tracing::formatters::Blockscout::format(proxy) .ok_or("Trace result is empty.") - .map_err(|e| internal_err(format!("{:?}", e))), + .map_err(|e| internal_err(format!("{:?}", e))) + }, TracerInput::CallTracer => { let mut res = client_evm_tracing::formatters::CallTracer::format(proxy) .ok_or("Trace result is empty.") diff --git a/client/rpc/trace/src/lib.rs b/client/rpc/trace/src/lib.rs index c950d3ffc..72c564dfd 100644 --- a/client/rpc/trace/src/lib.rs +++ b/client/rpc/trace/src/lib.rs @@ -100,8 +100,9 @@ where .try_into() .map_err(|_| "Block number overflow")?), Some(RequestBlockId::Tag(RequestBlockTag::Earliest)) => Ok(0), - Some(RequestBlockId::Tag(RequestBlockTag::Pending)) => - Err("'pending' is not supported"), + Some(RequestBlockId::Tag(RequestBlockTag::Pending)) => { + Err("'pending' is not supported") + }, Some(RequestBlockId::Hash(_)) => Err("Block hash not supported"), } } @@ -173,15 +174,18 @@ where let mut block_traces: Vec<_> = block_traces .iter() .filter(|trace| match trace.action { - block::TransactionTraceAction::Call { from, to, .. } => - (from_address.is_empty() || from_address.contains(&from)) && - (to_address.is_empty() || to_address.contains(&to)), - block::TransactionTraceAction::Create { from, .. } => - (from_address.is_empty() || from_address.contains(&from)) && - to_address.is_empty(), - block::TransactionTraceAction::Suicide { address, .. } => - (from_address.is_empty() || from_address.contains(&address)) && - to_address.is_empty(), + block::TransactionTraceAction::Call { from, to, .. } => { + (from_address.is_empty() || from_address.contains(&from)) + && (to_address.is_empty() || to_address.contains(&to)) + }, + block::TransactionTraceAction::Create { from, .. } => { + (from_address.is_empty() || from_address.contains(&from)) + && to_address.is_empty() + }, + block::TransactionTraceAction::Suicide { address, .. } => { + (from_address.is_empty() || from_address.contains(&address)) + && to_address.is_empty() + }, }) .cloned() .collect(); @@ -648,8 +652,8 @@ where // We remove early the block cache if this batch is the last // pooling this block. if let Some(block_cache) = self.cached_blocks.get_mut(block) { - if block_cache.active_batch_count == 1 && - matches!( + if block_cache.active_batch_count == 1 + && matches!( block_cache.state, CacheBlockState::Pooled { started: false, .. } ) { @@ -756,11 +760,12 @@ where overrides.current_transaction_statuses(substrate_hash), ) { (Some(a), Some(b)) => (a, b), - _ => + _ => { return Err(format!( "Failed to get Ethereum block data for Substrate block {}", substrate_hash - )), + )) + }, }; let eth_block_hash = eth_block.header.hash(); diff --git a/frost/frost-ristretto255/src/lib.rs b/frost/frost-ristretto255/src/lib.rs index a3322ef47..a4d955fc5 100644 --- a/frost/frost-ristretto255/src/lib.rs +++ b/frost/frost-ristretto255/src/lib.rs @@ -102,12 +102,13 @@ impl Group for RistrettoGroup { .map_err(|_| GroupError::MalformedElement)? .decompress() { - Some(point) => + Some(point) => { if point == RistrettoPoint::identity() { Err(GroupError::InvalidIdentityElement) } else { Ok(WrappedRistrettoPoint(point)) - }, + } + }, None => Err(GroupError::MalformedElement), } } diff --git a/frost/src/round1.rs b/frost/src/round1.rs index 52f7d61af..54039c005 100644 --- a/frost/src/round1.rs +++ b/frost/src/round1.rs @@ -106,9 +106,9 @@ where /// Checks if the commitments are valid. pub fn is_valid(&self) -> bool { - element_is_valid::(&self.hiding.0) && - element_is_valid::(&self.binding.0) && - self.hiding.0 != self.binding.0 + element_is_valid::(&self.hiding.0) + && element_is_valid::(&self.binding.0) + && self.hiding.0 != self.binding.0 } } diff --git a/frost/src/signature.rs b/frost/src/signature.rs index 78b8e3cf5..5a1f89bef 100644 --- a/frost/src/signature.rs +++ b/frost/src/signature.rs @@ -210,8 +210,8 @@ where lambda_i: Scalar, challenge: &Challenge, ) -> Result<(), Error> { - if (::generator() * self.share) != - (group_commitment_share.0 + (verifying_share.0 * challenge.0 * lambda_i)) + if (::generator() * self.share) + != (group_commitment_share.0 + (verifying_share.0 * challenge.0 * lambda_i)) { return Err(Error::InvalidSignatureShare); } diff --git a/node/src/distributions/mainnet.rs b/node/src/distributions/mainnet.rs index e8b78cea1..b11cd7357 100644 --- a/node/src/distributions/mainnet.rs +++ b/node/src/distributions/mainnet.rs @@ -633,16 +633,16 @@ fn test_distribution_shares() { ); // 0.95% // Test total claims - let total_claims = edgeware_genesis_list.claims.len() + - edgeware_snapshot_list.claims.len() + - polkadot_genesis_list.claims.len() + - leaderboard_genesis_list.claims.len(); + let total_claims = edgeware_genesis_list.claims.len() + + edgeware_snapshot_list.claims.len() + + polkadot_genesis_list.claims.len() + + leaderboard_genesis_list.claims.len(); assert_eq!(total_claims, 29452); - let total_vesting = edgeware_genesis_list.vesting.len() + - edgeware_snapshot_list.vesting.len() + - polkadot_genesis_list.vesting.len() + - leaderboard_genesis_list.vesting.len(); + let total_vesting = edgeware_genesis_list.vesting.len() + + edgeware_snapshot_list.vesting.len() + + polkadot_genesis_list.vesting.len() + + leaderboard_genesis_list.vesting.len(); assert_eq!(total_vesting, 29452); let unique_dist = crate::distributions::get_unique_distribution_results(vec![ @@ -674,16 +674,16 @@ fn test_distribution_shares() { // get_initial_endowed_accounts().0.into_iter().map(|(_, amount)| amount).sum(); // assert_eq!(total_endowmwnent - total_treasury_amount, 8900000000000000000000); // 8900 TNT - let total_genesis_endowment = total_investor_amount + - total_direct_team_amount + - foundation_total_amount + - total_edgeware_claims_amount + - total_edgeware_snapshot_claims_amount + - total_leaderboard_claims_amount + - total_polkadot_claims_amount + - total_treasury_amount + - 5000 * UNIT + - total_team_claims_amount; + let total_genesis_endowment = total_investor_amount + + total_direct_team_amount + + foundation_total_amount + + total_edgeware_claims_amount + + total_edgeware_snapshot_claims_amount + + total_leaderboard_claims_amount + + total_polkadot_claims_amount + + total_treasury_amount + + 5000 * UNIT + + total_team_claims_amount; //+ total_endowmwnent; assert_eq!(total_genesis_endowment, 100000000000000006345897383); // 100000000 TNT diff --git a/node/src/service.rs b/node/src/service.rs index e7895f377..d0649d03d 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -308,8 +308,8 @@ pub async fn new_full Pallet { statement: Vec, ) -> Result> { let signer = match signature { - MultiAddressSignature::EVM(ethereum_signature) => + MultiAddressSignature::EVM(ethereum_signature) => { Self::eth_recover(ðereum_signature, &data, &statement[..]) - .ok_or(Error::::InvalidEthereumSignature)?, + .ok_or(Error::::InvalidEthereumSignature)? + }, MultiAddressSignature::Native(sr25519_signature) => { ensure!(!signer.is_none(), Error::::InvalidNativeAccount); Self::sr25519_recover(signer.unwrap(), &sr25519_signature, &data, &statement[..]) diff --git a/pallets/claims/src/utils/mod.rs b/pallets/claims/src/utils/mod.rs index f25596857..a387457fc 100644 --- a/pallets/claims/src/utils/mod.rs +++ b/pallets/claims/src/utils/mod.rs @@ -45,8 +45,9 @@ impl Hash for MultiAddress { impl MultiAddress { pub fn to_account_id_32(&self) -> AccountId32 { match self { - MultiAddress::EVM(ethereum_address) => - HashedAddressMapping::::into_account_id(H160::from(ethereum_address.0)), + MultiAddress::EVM(ethereum_address) => { + HashedAddressMapping::::into_account_id(H160::from(ethereum_address.0)) + }, MultiAddress::Native(substrate_address) => substrate_address.clone(), } } diff --git a/pallets/services/rpc/src/lib.rs b/pallets/services/rpc/src/lib.rs index 5798ecae7..e505a3a15 100644 --- a/pallets/services/rpc/src/lib.rs +++ b/pallets/services/rpc/src/lib.rs @@ -113,10 +113,12 @@ impl From for i32 { fn custom_error_into_rpc_err(err: Error) -> ErrorObjectOwned { match err { - Error::RuntimeError(e) => - ErrorObject::owned(RUNTIME_ERROR, "Runtime error", Some(format!("{e}"))), - Error::DecodeError => - ErrorObject::owned(2, "Decode error", Some("Transaction was not decodable")), + Error::RuntimeError(e) => { + ErrorObject::owned(RUNTIME_ERROR, "Runtime error", Some(format!("{e}"))) + }, + Error::DecodeError => { + ErrorObject::owned(2, "Decode error", Some("Transaction was not decodable")) + }, Error::CustomDispatchError(msg) => ErrorObject::owned(3, "Dispatch error", Some(msg)), } } diff --git a/pallets/services/src/functions.rs b/pallets/services/src/functions.rs index 7add2f095..b9a6b7349 100644 --- a/pallets/services/src/functions.rs +++ b/pallets/services/src/functions.rs @@ -77,8 +77,9 @@ impl Pallet { pub fn mbsm_address_of(blueprint: &ServiceBlueprint) -> Result> { match blueprint.master_manager_revision { MasterBlueprintServiceManagerRevision::Specific(rev) => Self::mbsm_address(rev), - MasterBlueprintServiceManagerRevision::Latest => - Self::mbsm_address(Self::mbsm_latest_revision()), + MasterBlueprintServiceManagerRevision::Latest => { + Self::mbsm_address(Self::mbsm_latest_revision()) + }, other => unimplemented!("Got unexpected case for {:?}", other), } } diff --git a/pallets/services/src/lib.rs b/pallets/services/src/lib.rs index eb53d663f..bb9841df7 100644 --- a/pallets/services/src/lib.rs +++ b/pallets/services/src/lib.rs @@ -1002,8 +1002,9 @@ pub mod module { .operators_with_approval_state .into_iter() .filter_map(|(v, state)| match state { - ApprovalState::Approved { restaking_percent } => - Some((v, restaking_percent)), + ApprovalState::Approved { restaking_percent } => { + Some((v, restaking_percent)) + }, // N.B: this should not happen, as all operators are approved and checked // above. _ => None, diff --git a/pallets/services/src/mock.rs b/pallets/services/src/mock.rs index 6a5ccbe39..5a9e1f396 100644 --- a/pallets/services/src/mock.rs +++ b/pallets/services/src/mock.rs @@ -605,10 +605,11 @@ pub fn assert_events(mut expected: Vec) { for evt in expected { let next = actual.pop().expect("RuntimeEvent expected"); match (&next, &evt) { - (left_val, right_val) => + (left_val, right_val) => { if !(*left_val == *right_val) { panic!("Events don't match\nactual: {actual:#?}\nexpected: {evt:#?}"); - }, + } + }, }; } } diff --git a/pallets/services/src/mock_evm.rs b/pallets/services/src/mock_evm.rs index 06fde6c34..8fcccabdb 100644 --- a/pallets/services/src/mock_evm.rs +++ b/pallets/services/src/mock_evm.rs @@ -266,8 +266,9 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => - call.pre_dispatch_self_contained(info, dispatch_info, len), + RuntimeCall::Ethereum(call) => { + call.pre_dispatch_self_contained(info, dispatch_info, len) + }, _ => None, } } @@ -277,8 +278,9 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => - Some(call.dispatch(RuntimeOrigin::from(RawOrigin::EthereumTransaction(info)))), + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { + Some(call.dispatch(RuntimeOrigin::from(RawOrigin::EthereumTransaction(info)))) + }, _ => None, } } diff --git a/pallets/services/src/tests.rs b/pallets/services/src/tests.rs index 9dbdd586b..dab8ebfed 100644 --- a/pallets/services/src/tests.rs +++ b/pallets/services/src/tests.rs @@ -62,8 +62,9 @@ fn price_targets(kind: MachineKind) -> PriceTargets { storage_ssd: 100, storage_nvme: 150, }, - MachineKind::Small => - PriceTargets { cpu: 500, mem: 250, storage_hdd: 25, storage_ssd: 50, storage_nvme: 75 }, + MachineKind::Small => { + PriceTargets { cpu: 500, mem: 250, storage_hdd: 25, storage_ssd: 50, storage_nvme: 75 } + }, } } diff --git a/pallets/tangle-lst/src/types/bonded_pool.rs b/pallets/tangle-lst/src/types/bonded_pool.rs index f808d9f4c..bca834932 100644 --- a/pallets/tangle-lst/src/types/bonded_pool.rs +++ b/pallets/tangle-lst/src/types/bonded_pool.rs @@ -160,8 +160,8 @@ impl BondedPool { } pub fn can_nominate(&self, who: &T::AccountId) -> bool { - self.is_root(who) || - self.roles.nominator.as_ref().map_or(false, |nominator| nominator == who) + self.is_root(who) + || self.roles.nominator.as_ref().map_or(false, |nominator| nominator == who) } pub fn can_kick(&self, who: &T::AccountId) -> bool { @@ -262,9 +262,9 @@ impl BondedPool { // any unbond must comply with the balance condition: ensure!( - is_full_unbond || - balance_after_unbond >= - if is_depositor { + is_full_unbond + || balance_after_unbond + >= if is_depositor { Pallet::::depositor_min_bond() } else { MinJoinBond::::get() diff --git a/precompiles/assets-erc20/src/lib.rs b/precompiles/assets-erc20/src/lib.rs index 0622ef949..d985500d7 100644 --- a/precompiles/assets-erc20/src/lib.rs +++ b/precompiles/assets-erc20/src/lib.rs @@ -254,8 +254,8 @@ where handle.record_db_read::(136)?; // If previous approval exists, we need to clean it - if pallet_assets::Pallet::::allowance(asset_id.clone(), &owner, &spender) != - 0u32.into() + if pallet_assets::Pallet::::allowance(asset_id.clone(), &owner, &spender) + != 0u32.into() { RuntimeHelper::::try_dispatch( handle, diff --git a/precompiles/assets-erc20/src/tests.rs b/precompiles/assets-erc20/src/tests.rs index a89db5452..72e029960 100644 --- a/precompiles/assets-erc20/src/tests.rs +++ b/precompiles/assets-erc20/src/tests.rs @@ -441,8 +441,8 @@ fn transfer_not_enough_founds() { ForeignPCall::transfer { to: Address(Charlie.into()), value: 50.into() }, ) .execute_reverts(|output| { - from_utf8(output).unwrap().contains("Dispatched call failed with error: ") && - from_utf8(output).unwrap().contains("BalanceLow") + from_utf8(output).unwrap().contains("Dispatched call failed with error: ") + && from_utf8(output).unwrap().contains("BalanceLow") }); }); } diff --git a/precompiles/balances-erc20/src/tests.rs b/precompiles/balances-erc20/src/tests.rs index f62c1a4de..6e176e808 100644 --- a/precompiles/balances-erc20/src/tests.rs +++ b/precompiles/balances-erc20/src/tests.rs @@ -306,8 +306,8 @@ fn transfer_not_enough_funds() { PCall::transfer { to: Address(Bob.into()), value: 1400.into() }, ) .execute_reverts(|output| { - from_utf8(&output).unwrap().contains("Dispatched call failed with error: ") && - from_utf8(&output).unwrap().contains("FundsUnavailable") + from_utf8(&output).unwrap().contains("Dispatched call failed with error: ") + && from_utf8(&output).unwrap().contains("FundsUnavailable") }); }); } diff --git a/precompiles/batch/src/lib.rs b/precompiles/batch/src/lib.rs index 0c71539af..640b1b793 100644 --- a/precompiles/batch/src/lib.rs +++ b/precompiles/batch/src/lib.rs @@ -146,8 +146,9 @@ where let forwarded_gas = match (remaining_gas.checked_sub(log_cost), mode) { (Some(remaining), _) => remaining, - (None, Mode::BatchAll) => - return Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }), + (None, Mode::BatchAll) => { + return Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }) + }, (None, _) => return Ok(()), }; @@ -162,10 +163,11 @@ where log.record(handle)?; match mode { - Mode::BatchAll => + Mode::BatchAll => { return Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas, - }), + }) + }, Mode::BatchSomeUntilFailure => return Ok(()), Mode::BatchSome => continue, } @@ -182,10 +184,11 @@ where log.record(handle)?; match mode { - Mode::BatchAll => + Mode::BatchAll => { return Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas, - }), + }) + }, Mode::BatchSomeUntilFailure => return Ok(()), Mode::BatchSome => continue, } @@ -216,19 +219,23 @@ where // How to proceed match (mode, reason) { // _: Fatal is always fatal - (_, ExitReason::Fatal(exit_status)) => - return Err(PrecompileFailure::Fatal { exit_status }), + (_, ExitReason::Fatal(exit_status)) => { + return Err(PrecompileFailure::Fatal { exit_status }) + }, // BatchAll : Reverts and errors are immediatly forwarded. - (Mode::BatchAll, ExitReason::Revert(exit_status)) => - return Err(PrecompileFailure::Revert { exit_status, output }), - (Mode::BatchAll, ExitReason::Error(exit_status)) => - return Err(PrecompileFailure::Error { exit_status }), + (Mode::BatchAll, ExitReason::Revert(exit_status)) => { + return Err(PrecompileFailure::Revert { exit_status, output }) + }, + (Mode::BatchAll, ExitReason::Error(exit_status)) => { + return Err(PrecompileFailure::Error { exit_status }) + }, // BatchSomeUntilFailure : Reverts and errors prevent subsequent subcalls to // be executed but the precompile still succeed. - (Mode::BatchSomeUntilFailure, ExitReason::Revert(_) | ExitReason::Error(_)) => - return Ok(()), + (Mode::BatchSomeUntilFailure, ExitReason::Revert(_) | ExitReason::Error(_)) => { + return Ok(()) + }, // Success or ignored revert/error. (_, _) => (), @@ -263,8 +270,9 @@ where match mode { Mode::BatchSome => Self::batch_some { to, value, call_data, gas_limit }, - Mode::BatchSomeUntilFailure => - Self::batch_some_until_failure { to, value, call_data, gas_limit }, + Mode::BatchSomeUntilFailure => { + Self::batch_some_until_failure { to, value, call_data, gas_limit } + }, Mode::BatchAll => Self::batch_all { to, value, call_data, gas_limit }, } } diff --git a/precompiles/call-permit/src/lib.rs b/precompiles/call-permit/src/lib.rs index c1bb88e69..ee64f0b89 100644 --- a/precompiles/call-permit/src/lib.rs +++ b/precompiles/call-permit/src/lib.rs @@ -216,8 +216,9 @@ where match reason { ExitReason::Error(exit_status) => Err(PrecompileFailure::Error { exit_status }), ExitReason::Fatal(exit_status) => Err(PrecompileFailure::Fatal { exit_status }), - ExitReason::Revert(_) => - Err(PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output }), + ExitReason::Revert(_) => { + Err(PrecompileFailure::Revert { exit_status: ExitRevert::Reverted, output }) + }, ExitReason::Succeed(_) => Ok(output.into()), } } diff --git a/precompiles/multi-asset-delegation/src/tests.rs b/precompiles/multi-asset-delegation/src/tests.rs index 2c7d65333..c6ed8d645 100644 --- a/precompiles/multi-asset-delegation/src/tests.rs +++ b/precompiles/multi-asset-delegation/src/tests.rs @@ -432,8 +432,8 @@ fn test_operator_go_offline_and_online() { .execute_returns(()); assert!( - MultiAssetDelegation::operator_info(operator_account).unwrap().status == - OperatorStatus::Inactive + MultiAssetDelegation::operator_info(operator_account).unwrap().status + == OperatorStatus::Inactive ); PrecompilesValue::get() @@ -441,8 +441,8 @@ fn test_operator_go_offline_and_online() { .execute_returns(()); assert!( - MultiAssetDelegation::operator_info(operator_account).unwrap().status == - OperatorStatus::Active + MultiAssetDelegation::operator_info(operator_account).unwrap().status + == OperatorStatus::Active ); assert_eq!(Balances::free_balance(operator_account), 20_000 - 10_000); diff --git a/precompiles/pallet-democracy/src/tests.rs b/precompiles/pallet-democracy/src/tests.rs index e8f280d05..bdf4baf32 100644 --- a/precompiles/pallet-democracy/src/tests.rs +++ b/precompiles/pallet-democracy/src/tests.rs @@ -220,8 +220,9 @@ fn lowest_unbaked_non_zero() { .dispatch(RuntimeOrigin::signed(Alice.into()))); let voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Direct { votes, delegations, prior } => - (votes.into_inner(), delegations, prior), + Voting::Direct { votes, delegations, prior } => { + (votes.into_inner(), delegations, prior) + }, _ => panic!("Votes are not direct"), }; @@ -243,9 +244,9 @@ fn lowest_unbaked_non_zero() { // Run it through until it is baked roll_to( - ::VotingPeriod::get() + - ::LaunchPeriod::get() + - 1000, + ::VotingPeriod::get() + + ::LaunchPeriod::get() + + 1000, ); precompiles() @@ -558,8 +559,9 @@ fn standard_vote_aye_works() { ); let voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Direct { votes, delegations, prior } => - (votes.into_inner(), delegations, prior), + Voting::Direct { votes, delegations, prior } => { + (votes.into_inner(), delegations, prior) + }, _ => panic!("Votes are not direct"), }; @@ -642,8 +644,9 @@ fn standard_vote_nay_conviction_works() { ); let voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Direct { votes, delegations, prior } => - (votes.into_inner(), delegations, prior), + Voting::Direct { votes, delegations, prior } => { + (votes.into_inner(), delegations, prior) + }, _ => panic!("Votes are not direct"), }; @@ -721,8 +724,9 @@ fn remove_vote_works() { ); let voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Direct { votes, delegations, prior } => - (votes.into_inner(), delegations, prior), + Voting::Direct { votes, delegations, prior } => { + (votes.into_inner(), delegations, prior) + }, _ => panic!("Votes are not direct"), }; @@ -793,8 +797,9 @@ fn delegate_works() { ); let alice_voting = match pallet_democracy::VotingOf::::get(AccountId::from(Alice)) { - Voting::Delegating { balance, target, conviction, delegations, prior } => - (balance, target, conviction, delegations, prior), + Voting::Delegating { balance, target, conviction, delegations, prior } => { + (balance, target, conviction, delegations, prior) + }, _ => panic!("Votes are not delegating"), }; @@ -807,8 +812,9 @@ fn delegate_works() { let bob_voting = match pallet_democracy::VotingOf::::get(AccountId::from(Bob)) { - Voting::Direct { votes, delegations, prior } => - (votes.into_inner(), delegations, prior), + Voting::Direct { votes, delegations, prior } => { + (votes.into_inner(), delegations, prior) + }, _ => panic!("Votes are not direct"), }; diff --git a/precompiles/precompile-registry/src/lib.rs b/precompiles/precompile-registry/src/lib.rs index f3d27795e..5a1e864a1 100644 --- a/precompiles/precompile-registry/src/lib.rs +++ b/precompiles/precompile-registry/src/lib.rs @@ -69,8 +69,9 @@ where .is_active_precompile(address.0, handle.remaining_gas()) { IsPrecompileResult::Answer { is_precompile, .. } => Ok(is_precompile), - IsPrecompileResult::OutOfGas => - Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }), + IsPrecompileResult::OutOfGas => { + Err(PrecompileFailure::Error { exit_status: ExitError::OutOfGas }) + }, } } diff --git a/precompiles/proxy/src/lib.rs b/precompiles/proxy/src/lib.rs index 5b3dfccd8..450732435 100644 --- a/precompiles/proxy/src/lib.rs +++ b/precompiles/proxy/src/lib.rs @@ -60,8 +60,9 @@ where fn is_allowed(_caller: H160, selector: Option) -> bool { match selector { None => false, - Some(selector) => - ProxyPrecompileCall::::is_proxy_selectors().contains(&selector), + Some(selector) => { + ProxyPrecompileCall::::is_proxy_selectors().contains(&selector) + }, } } @@ -91,11 +92,12 @@ where fn is_allowed(_caller: H160, selector: Option) -> bool { match selector { None => false, - Some(selector) => - ProxyPrecompileCall::::is_proxy_selectors().contains(&selector) || - ProxyPrecompileCall::::proxy_selectors().contains(&selector) || - ProxyPrecompileCall::::proxy_force_type_selectors() - .contains(&selector), + Some(selector) => { + ProxyPrecompileCall::::is_proxy_selectors().contains(&selector) + || ProxyPrecompileCall::::proxy_selectors().contains(&selector) + || ProxyPrecompileCall::::proxy_force_type_selectors() + .contains(&selector) + }, } } @@ -417,8 +419,9 @@ where // Return subcall result match reason { ExitReason::Fatal(exit_status) => Err(PrecompileFailure::Fatal { exit_status }), - ExitReason::Revert(exit_status) => - Err(PrecompileFailure::Revert { exit_status, output }), + ExitReason::Revert(exit_status) => { + Err(PrecompileFailure::Revert { exit_status, output }) + }, ExitReason::Error(exit_status) => Err(PrecompileFailure::Error { exit_status }), ExitReason::Succeed(_) => Ok(()), } diff --git a/precompiles/services/src/mock_evm.rs b/precompiles/services/src/mock_evm.rs index feb5292c5..58b2c2be3 100644 --- a/precompiles/services/src/mock_evm.rs +++ b/precompiles/services/src/mock_evm.rs @@ -254,8 +254,9 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => - call.pre_dispatch_self_contained(info, dispatch_info, len), + RuntimeCall::Ethereum(call) => { + call.pre_dispatch_self_contained(info, dispatch_info, len) + }, _ => None, } } @@ -265,8 +266,9 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => - Some(call.dispatch(RuntimeOrigin::from(RawOrigin::EthereumTransaction(info)))), + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { + Some(call.dispatch(RuntimeOrigin::from(RawOrigin::EthereumTransaction(info)))) + }, _ => None, } } diff --git a/precompiles/services/src/tests.rs b/precompiles/services/src/tests.rs index bbf9ed47c..0be0fb350 100644 --- a/precompiles/services/src/tests.rs +++ b/precompiles/services/src/tests.rs @@ -45,8 +45,9 @@ fn price_targets(kind: MachineKind) -> PriceTargets { storage_ssd: 100, storage_nvme: 150, }, - MachineKind::Small => - PriceTargets { cpu: 500, mem: 250, storage_hdd: 25, storage_ssd: 50, storage_nvme: 75 }, + MachineKind::Small => { + PriceTargets { cpu: 500, mem: 250, storage_hdd: 25, storage_ssd: 50, storage_nvme: 75 } + }, } } diff --git a/primitives/rpc/evm-tracing-events/src/evm.rs b/primitives/rpc/evm-tracing-events/src/evm.rs index 688861fdd..2b997eaeb 100644 --- a/primitives/rpc/evm-tracing-events/src/evm.rs +++ b/primitives/rpc/evm-tracing-events/src/evm.rs @@ -61,8 +61,9 @@ impl From for CreateScheme { fn from(i: evm_runtime::CreateScheme) -> Self { match i { evm_runtime::CreateScheme::Legacy { caller } => Self::Legacy { caller }, - evm_runtime::CreateScheme::Create2 { caller, code_hash, salt } => - Self::Create2 { caller, code_hash, salt }, + evm_runtime::CreateScheme::Create2 { caller, code_hash, salt } => { + Self::Create2 { caller, code_hash, salt } + }, evm_runtime::CreateScheme::Fixed(address) => Self::Fixed(address), } } @@ -166,12 +167,15 @@ impl<'a> From> for EvmEvent { init_code: init_code.to_vec(), target_gas, }, - evm::tracing::Event::Suicide { address, target, balance } => - Self::Suicide { address, target, balance }, - evm::tracing::Event::Exit { reason, return_value } => - Self::Exit { reason: reason.clone(), return_value: return_value.to_vec() }, - evm::tracing::Event::TransactCall { caller, address, value, data, gas_limit } => - Self::TransactCall { caller, address, value, data: data.to_vec(), gas_limit }, + evm::tracing::Event::Suicide { address, target, balance } => { + Self::Suicide { address, target, balance } + }, + evm::tracing::Event::Exit { reason, return_value } => { + Self::Exit { reason: reason.clone(), return_value: return_value.to_vec() } + }, + evm::tracing::Event::TransactCall { caller, address, value, data, gas_limit } => { + Self::TransactCall { caller, address, value, data: data.to_vec(), gas_limit } + }, evm::tracing::Event::TransactCreate { caller, value, diff --git a/primitives/rpc/evm-tracing-events/src/gasometer.rs b/primitives/rpc/evm-tracing-events/src/gasometer.rs index d1fbb453e..85d8352ba 100644 --- a/primitives/rpc/evm-tracing-events/src/gasometer.rs +++ b/primitives/rpc/evm-tracing-events/src/gasometer.rs @@ -59,12 +59,15 @@ pub enum GasometerEvent { impl From for GasometerEvent { fn from(i: evm_gasometer::tracing::Event) -> Self { match i { - evm_gasometer::tracing::Event::RecordCost { cost, snapshot } => - Self::RecordCost { cost, snapshot: snapshot.into() }, - evm_gasometer::tracing::Event::RecordRefund { refund, snapshot } => - Self::RecordRefund { refund, snapshot: snapshot.into() }, - evm_gasometer::tracing::Event::RecordStipend { stipend, snapshot } => - Self::RecordStipend { stipend, snapshot: snapshot.into() }, + evm_gasometer::tracing::Event::RecordCost { cost, snapshot } => { + Self::RecordCost { cost, snapshot: snapshot.into() } + }, + evm_gasometer::tracing::Event::RecordRefund { refund, snapshot } => { + Self::RecordRefund { refund, snapshot: snapshot.into() } + }, + evm_gasometer::tracing::Event::RecordStipend { stipend, snapshot } => { + Self::RecordStipend { stipend, snapshot: snapshot.into() } + }, evm_gasometer::tracing::Event::RecordDynamicCost { gas_cost, memory_gas, @@ -76,8 +79,9 @@ impl From for GasometerEvent { gas_refund, snapshot: snapshot.into(), }, - evm_gasometer::tracing::Event::RecordTransaction { cost, snapshot } => - Self::RecordTransaction { cost, snapshot: snapshot.into() }, + evm_gasometer::tracing::Event::RecordTransaction { cost, snapshot } => { + Self::RecordTransaction { cost, snapshot: snapshot.into() } + }, } } } diff --git a/primitives/rpc/evm-tracing-events/src/runtime.rs b/primitives/rpc/evm-tracing-events/src/runtime.rs index ad738f739..089932d55 100644 --- a/primitives/rpc/evm-tracing-events/src/runtime.rs +++ b/primitives/rpc/evm-tracing-events/src/runtime.rs @@ -92,7 +92,7 @@ impl RuntimeEvent { filter: crate::StepEventFilter, ) -> Self { match i { - evm_runtime::tracing::Event::Step { context, opcode, position, stack, memory } => + evm_runtime::tracing::Event::Step { context, opcode, position, stack, memory } => { Self::Step { context: context.clone().into(), opcode: opcodes_string(opcode), @@ -102,7 +102,8 @@ impl RuntimeEvent { }, stack: if filter.enable_stack { Some(stack.into()) } else { None }, memory: if filter.enable_memory { Some(memory.into()) } else { None }, - }, + } + }, evm_runtime::tracing::Event::StepResult { result, return_value } => Self::StepResult { result: match result { Ok(_) => Ok(()), @@ -113,10 +114,12 @@ impl RuntimeEvent { }, return_value: return_value.to_vec(), }, - evm_runtime::tracing::Event::SLoad { address, index, value } => - Self::SLoad { address, index, value }, - evm_runtime::tracing::Event::SStore { address, index, value } => - Self::SStore { address, index, value }, + evm_runtime::tracing::Event::SLoad { address, index, value } => { + Self::SLoad { address, index, value } + }, + evm_runtime::tracing::Event::SStore { address, index, value } => { + Self::SStore { address, index, value } + }, } } } diff --git a/primitives/src/chain_identifier.rs b/primitives/src/chain_identifier.rs index d916c2a2a..72155a8a7 100644 --- a/primitives/src/chain_identifier.rs +++ b/primitives/src/chain_identifier.rs @@ -65,14 +65,14 @@ impl TypedChainId { #[must_use] pub const fn underlying_chain_id(&self) -> u32 { match self { - TypedChainId::Evm(id) | - TypedChainId::Substrate(id) | - TypedChainId::PolkadotParachain(id) | - TypedChainId::KusamaParachain(id) | - TypedChainId::RococoParachain(id) | - TypedChainId::Cosmos(id) | - TypedChainId::Solana(id) | - TypedChainId::Ink(id) => *id, + TypedChainId::Evm(id) + | TypedChainId::Substrate(id) + | TypedChainId::PolkadotParachain(id) + | TypedChainId::KusamaParachain(id) + | TypedChainId::RococoParachain(id) + | TypedChainId::Cosmos(id) + | TypedChainId::Solana(id) + | TypedChainId::Ink(id) => *id, Self::None => 0, } } diff --git a/primitives/src/services/field.rs b/primitives/src/services/field.rs index 934d27344..96d7338ab 100644 --- a/primitives/src/services/field.rs +++ b/primitives/src/services/field.rs @@ -307,16 +307,18 @@ impl PartialEq for Field { (Self::Int64(_), FieldType::Int64) => true, (Self::String(_), FieldType::String) => true, (Self::Bytes(_), FieldType::Bytes) => true, - (Self::Array(a), FieldType::Array(len, b)) => - a.len() == *len as usize && a.iter().all(|f| f.eq(b.as_ref())), + (Self::Array(a), FieldType::Array(len, b)) => { + a.len() == *len as usize && a.iter().all(|f| f.eq(b.as_ref())) + }, (Self::List(a), FieldType::List(b)) => a.iter().all(|f| f.eq(b.as_ref())), (Self::AccountId(_), FieldType::AccountId) => true, - (Self::Struct(_, fields_a), FieldType::Struct(_, fields_b)) => - fields_a.into_iter().len() == fields_b.into_iter().len() && - fields_a + (Self::Struct(_, fields_a), FieldType::Struct(_, fields_b)) => { + fields_a.into_iter().len() == fields_b.into_iter().len() + && fields_a .into_iter() .zip(fields_b) - .all(|((_, v_a), (_, v_b))| v_a.as_ref().eq(v_b)), + .all(|((_, v_a), (_, v_b))| v_a.as_ref().eq(v_b)) + }, _ => false, } } diff --git a/primitives/src/services/mod.rs b/primitives/src/services/mod.rs index 6bb4f47b2..5a6d2ac5c 100644 --- a/primitives/src/services/mod.rs +++ b/primitives/src/services/mod.rs @@ -485,10 +485,12 @@ impl ServiceBlueprint { }, // Master Manager Revision match self.master_manager_revision { - MasterBlueprintServiceManagerRevision::Latest => - ethabi::Token::Uint(ethabi::Uint::MAX), - MasterBlueprintServiceManagerRevision::Specific(rev) => - ethabi::Token::Uint(rev.into()), + MasterBlueprintServiceManagerRevision::Latest => { + ethabi::Token::Uint(ethabi::Uint::MAX) + }, + MasterBlueprintServiceManagerRevision::Specific(rev) => { + ethabi::Token::Uint(rev.into()) + }, }, // Gadget ? ]) diff --git a/runtime/mainnet/src/frontier_evm.rs b/runtime/mainnet/src/frontier_evm.rs index e415fb75c..38d046f19 100644 --- a/runtime/mainnet/src/frontier_evm.rs +++ b/runtime/mainnet/src/frontier_evm.rs @@ -119,20 +119,21 @@ impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType { ) -> precompile_utils::EvmResult { Ok(match self { ProxyType::Any => true, - ProxyType::Governance => - call.value == U256::zero() && - matches!( + ProxyType::Governance => { + call.value == U256::zero() + && matches!( PrecompileName::from_address(call.to.0), Some(ref precompile) if is_governance_precompile(precompile) - ), + ) + }, // The proxy precompile does not contain method cancel_proxy ProxyType::CancelProxy => false, ProxyType::Balances => { // Allow only "simple" accounts as recipient (no code nor precompile). // Note: Checking the presence of the code is not enough because some precompiles // have no code. - !recipient_has_code && - !precompile_utils::precompile_set::is_precompile_or_fail::( + !recipient_has_code + && !precompile_utils::precompile_set::is_precompile_or_fail::( call.to.0, gas, )? }, diff --git a/runtime/mainnet/src/lib.rs b/runtime/mainnet/src/lib.rs index f287cf6e7..120ff186d 100644 --- a/runtime/mainnet/src/lib.rs +++ b/runtime/mainnet/src/lib.rs @@ -656,8 +656,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) - .expect("input is padded with zeroes; qed") % - max.saturating_add(1); + .expect("input is padded with zeroes; qed") + % max.saturating_add(1); random as usize }, }; @@ -1148,15 +1148,15 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances(..) | - RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) + RuntimeCall::Balances(..) + | RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) ), ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) | - RuntimeCall::Council(..) | - RuntimeCall::Elections(..) | - RuntimeCall::Treasury(..) + RuntimeCall::Democracy(..) + | RuntimeCall::Council(..) + | RuntimeCall::Elections(..) + | RuntimeCall::Treasury(..) ), ProxyType::Staking => { matches!(c, RuntimeCall::Staking(..)) @@ -1465,8 +1465,9 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => - call.pre_dispatch_self_contained(info, dispatch_info, len), + RuntimeCall::Ethereum(call) => { + call.pre_dispatch_self_contained(info, dispatch_info, len) + }, _ => None, } } @@ -1476,10 +1477,11 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), - ))), + ))) + }, _ => None, } } diff --git a/runtime/testnet/src/lib.rs b/runtime/testnet/src/lib.rs index be3080a3b..2c1695cf0 100644 --- a/runtime/testnet/src/lib.rs +++ b/runtime/testnet/src/lib.rs @@ -663,8 +663,8 @@ impl Get> for OffchainRandomBalancing { max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) - .expect("input is padded with zeroes; qed") % - max.saturating_add(1); + .expect("input is padded with zeroes; qed") + % max.saturating_add(1); random as usize }, }; @@ -1146,15 +1146,15 @@ impl InstanceFilter for ProxyType { ProxyType::Any => true, ProxyType::NonTransfer => !matches!( c, - RuntimeCall::Balances(..) | - RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) + RuntimeCall::Balances(..) + | RuntimeCall::Vesting(pallet_vesting::Call::vested_transfer { .. }) ), ProxyType::Governance => matches!( c, - RuntimeCall::Democracy(..) | - RuntimeCall::Council(..) | - RuntimeCall::Elections(..) | - RuntimeCall::Treasury(..) + RuntimeCall::Democracy(..) + | RuntimeCall::Council(..) + | RuntimeCall::Elections(..) + | RuntimeCall::Treasury(..) ), ProxyType::Staking => { matches!(c, RuntimeCall::Staking(..)) @@ -1387,8 +1387,9 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { len: usize, ) -> Option> { match self { - RuntimeCall::Ethereum(call) => - call.pre_dispatch_self_contained(info, dispatch_info, len), + RuntimeCall::Ethereum(call) => { + call.pre_dispatch_self_contained(info, dispatch_info, len) + }, _ => None, } } @@ -1398,10 +1399,11 @@ impl fp_self_contained::SelfContainedCall for RuntimeCall { info: Self::SignedInfo, ) -> Option>> { match self { - call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => + call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), - ))), + ))) + }, _ => None, } } From e17868656c3432067b45769ae9e1793b4faa6abe Mon Sep 17 00:00:00 2001 From: Drew Stone Date: Tue, 3 Dec 2024 00:28:07 -0700 Subject: [PATCH 8/9] chore: fix clippy --- .../investor_team_vesting_migration_11302024.rs | 16 ++++++---------- .../session_key_migrations_08062024.rs | 2 -- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs b/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs index c8cff13ce..b862c66cd 100644 --- a/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs +++ b/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs @@ -1,15 +1,12 @@ -use super::*; -use crate::{AccountId, Balance, BlockNumber, H160}; -use core::str::FromStr; use frame_support::{pallet_prelude::*, traits::OnRuntimeUpgrade}; +#[cfg(feature = "try-runtime")] use pallet_airdrop_claims::MultiAddress; -use pallet_ethereum::Block; use pallet_vesting::{MaxVestingSchedulesGet, Vesting, VestingInfo}; use sp_runtime::{ - traits::{AccountIdConversion, Convert, EnsureDiv, Header, Zero}, - AccountId32, Percent, Saturating, + traits::{Convert, EnsureDiv, Header, Zero}, + Percent, Saturating, }; -use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec}; +use sp_std::vec::Vec; pub const BLOCK_TIME: u128 = 6; pub const ONE_YEAR_BLOCKS: u64 = (365 * 24 * 60 * 60 / BLOCK_TIME) as u64; @@ -203,10 +200,10 @@ fn update_account_vesting( reads: &mut u64, writes: &mut u64, ) { - let schedules = Vesting::::get(&account_id); + let schedules = Vesting::::get(account_id); *reads += 1; if let Some(schedules) = schedules { - update_vesting_schedule::(&account_id, schedules.to_vec()); + update_vesting_schedule::(account_id, schedules.to_vec()); *writes += 1; } } @@ -228,7 +225,6 @@ fn update_vesting_schedule( // New vesting parameters let one_year_blocks = BlockNumberOf::::from(ONE_YEAR_BLOCKS as u32); let three_year_blocks = one_year_blocks.saturating_mul(BlockNumberOf::::from(3u32)); - let four_year_blocks = one_year_blocks.saturating_mul(BlockNumberOf::::from(4u32)); // At 1 year cliff, 25% unlocks let quarter_percentage = Percent::from_percent(25); diff --git a/runtime/mainnet/src/migrations/session_key_migrations_08062024.rs b/runtime/mainnet/src/migrations/session_key_migrations_08062024.rs index 5d47b0c38..9ee6e0e6c 100644 --- a/runtime/mainnet/src/migrations/session_key_migrations_08062024.rs +++ b/runtime/mainnet/src/migrations/session_key_migrations_08062024.rs @@ -1,9 +1,7 @@ -use super::*; use crate::{AccountId, Babe, Grandpa, KeyTypeId, OpaqueKeys, Session, SessionKeys}; use frame_support::{pallet_prelude::*, traits::OnRuntimeUpgrade}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use sp_runtime::{BoundToRuntimeAppPublic, RuntimeAppPublic, RuntimeDebug}; -use sp_std::vec; /// Old session keys structure. /// From fd1a1b05b96caa5d1d39afb98e153a9ec3dcbcc8 Mon Sep 17 00:00:00 2001 From: Drew Stone Date: Tue, 14 Jan 2025 16:30:39 +0900 Subject: [PATCH 9/9] chore: update with all team accounts --- Cargo.lock | 13 +++ Cargo.toml | 1 + account-util/Cargo.toml | 18 ++++ account-util/src/lib.rs | 96 +++++++++++++++++++ pallets/multi-asset-delegation/src/lib.rs | 5 +- primitives/src/services/mod.rs | 3 +- runtime/mainnet/Cargo.toml | 22 +++++ ...nvestor_team_vesting_migration_11302024.rs | 70 ++++++++++++-- 8 files changed, 212 insertions(+), 16 deletions(-) create mode 100644 account-util/Cargo.toml create mode 100644 account-util/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 11269582e..aca282c03 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12,6 +12,19 @@ dependencies = [ "regex", ] +[[package]] +name = "account-util" +version = "1.2.5" +dependencies = [ + "frame-support", + "pallet-airdrop-claims", + "pallet-vesting", + "sp-core", + "sp-runtime", + "sp-std", + "tangle-primitives", +] + [[package]] name = "addchain" version = "0.2.0" diff --git a/Cargo.toml b/Cargo.toml index b61ad255d..6938be613 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ exclude = ["examples"] [workspace] members = [ + "account-util", "primitives", "primitives/crypto", "primitives/rpc/*", diff --git a/account-util/Cargo.toml b/account-util/Cargo.toml new file mode 100644 index 000000000..acefeeb63 --- /dev/null +++ b/account-util/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "account-util" +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +exclude.workspace = true + +[dependencies] +frame-support = { workspace = true, features = ["std"] } +sp-core = { workspace = true, features = ["std"] } +sp-runtime = { workspace = true, features = ["std"] } +sp-std = { workspace = true, features = ["std"] } +pallet-airdrop-claims = { workspace = true, features = ["std"] } +pallet-vesting = { workspace = true, features = ["std"] } +tangle-primitives = { workspace = true, features = ["std"] } \ No newline at end of file diff --git a/account-util/src/lib.rs b/account-util/src/lib.rs new file mode 100644 index 000000000..536980440 --- /dev/null +++ b/account-util/src/lib.rs @@ -0,0 +1,96 @@ +use tangle_primitives::Balance; + +pub const BLOCK_TIME: u128 = 6; +pub const ONE_YEAR_BLOCKS: u64 = (365 * 24 * 60 * 60 / BLOCK_TIME) as u64; + +pub const INVESTOR_ACCOUNTS: [(&str, Balance); 29] = [ + ("5FCviiKcJzVfdwqv451JRQc93ZTSbbC9YfgKMkN3LpNMBjS3", 100000000000000000000000), + ("0xC02ad7b9a9121fc849196E844DC869D2250DF3A6", 150000000000000000000000), + ("5HBKM8XL7sr7S7qx6ukugDJUBhm16Ubnz1KuJCdHmHQvtc7Z", 400000000000000000000000), + ("0x86f99feff4cd3268ccefc760a6bbce2e07aa4d8e", 100000000000000000000000), + ("5HCJQLeQqCf64C6uy7CSoTND35QNdi1zU66TTM6QPCG9u9BB", 500000000000000000000000), + ("5DhQMPP69vRBNvZ6w4E9qii1yj56M66YXuPkkvz12yvn5ufN", 2750000000000000000000000), + ("0x17B74Dcf1E422AF5964056eB836321aE7A820035", 200000000000000000000000), + ("5Df1Sec4ZmeidskuuPtpt4SSCL6U5St19fsv4sBAwvkwmvin", 100000000000000000000000), + ("5FerzxKQZoP9wxjRhS1PHA4v27aPQMoZpXmufcQk1JYE5xU8", 100000000000000000000000), + ("0x75afaece8cf2a7974b1e541648923afd9339b3f8", 150000000000000000000000), + ("0x5a82d0bad9995b1bfa71de79b5e524decb5bee1c", 1000000000000000000000000), + ("5Cf5SfzngS9T9fdQSsKt1GJ42BQPP7FqU4trLwgkDD1ZVBN7", 20000000000000000000000), + ("0x5da7351A4Cb03c33e11F51841bc614d985812821", 20000000000000000000000), + ("5DDTvr7P2MaUirj3rSvpcF5DLxECiAqpQegdVCzAuwxingVC", 50000000000000000000000), + ("5CXkTTyNzVuE2fwNBzSwmmtcCntnun5vMDx6Wnn5VjopGUVx", 160000000000000000000000), + ("5G9Ji4EEiTehMKa9Nfe2rGozZB3XEyRtyvJWt2wYLMRYyAyn", 180000000000000000000000), + ("5EZcQuvjvuv1K4Ugg2ofLEhAC3NXPbaCAytPR3hmUqBv1Bhe", 200000000000000000000000), + ("5Fe8pwn27TNBuM1Agz1ivCMykX795woPQkjwiWD4UoSndmQj", 220000000000000000000000), + ("5HWLv9RvMSZ6FwuQswHCo1nmYxmAqRutqh37Vapx3pmXbVU3", 240000000000000000000000), + ("5ENgRjBQue32ppyLw1u55Rbe36gDWTJgZmcbSfZwrJAyt2tZ", 781850000000000000000000), + ("5DhzryWQpJTQfdauBf7yGKpr6LW42ye4oYvEYiVbMcGN7GZt", 879590000000000000000000), + ("5C52zXiWq7BM5x55soCudf8daW12NTLtMfisBiYd5Pov1Hw1", 977320000000000000000000), + ("5HbRuwKiUw4g7yh9iNBQ6zFG63sgZyGoZ4ep61CqMYTzk4gU", 1075050000000000000000000), + ("5HnQ2onP12Vhv3dVUvmKocbWr5sMjunCmjt2MmtxMr5z5dp1", 1172780000000000000000000), + ("5CAbD6BFcATxi9jVpixNtsLKovQy6RWQMQynHtapqAtKL8vT", 338150000000000000000000), + ("5DP7RmWdPD6TWbTNgBu6iKzYsm95fHETXyy5tQvEmS6zDhPn", 380410000000000000000000), + ("5EyDntnRYxgWLuHFRmSnirioDNpMDCUTQ4bwRYV3LGHQoMxo", 422680000000000000000000), + ("5DkNqZs22mLYXKy7c2vrtstqbcQBU1ArPKw51xvC37eGsuNP", 464950000000000000000000), + ("5CQJt5A7GmEUhh7S3MtaiBGvNRTY6PFw6KHJFcTVD4ZxBty7", 507220000000000000000000), +]; + +pub const TEAM_ACCOUNTS: [(&str, Balance); 11] = [ + ("5H4H4pVXrqs6r1kwdzevPXQnLAU8518hXSi6N25jYGiPrSoD", 10000000000000000000000), + ("5DoX7xYr8kzLEdZRXzSHJvRahtntVWdAowe3P9KjjWKrRXNV", 150000000000000000000000), + ("5HBXHgGuu5kuFtiLFxa7r3ygKCDBmddnyAA7AQ5HpLuJqXQb", 200000000000000000000000), + ("5FjoBt9hjDSb81GuVK9Bqf1NHJcmeKFUnMmyXik1579dP9dW", 30000000000000000000000), + ("5EbkKKTdRJzP1j3aM3S7q178du6tW7ZVWK9Dtjx9CbTFEpGf", 100000000000000000000000), + ("5HYMCFxV9C8VGWXd5PAgD59accAsKmopEFfuKFhU2YAE6Xhu", 200000000000000000000000), + ("5DhQuvKtVi41vPL8nSTFCTY7UJvNUQwEg9wAXRTU37iHBVRj", 15000000000000000000000), + ("5FEb3bjP4KsFpet1sf81MerFqmTjTx8db2H3WctwvmB75At8", 250000000000000000000000), + ("5F7UEB6Lo141pHYS1ySPf4UDTkuBEimSZmV9uehYJvXbc4CW", 150000000000000000000000), + ("5H4RzH7KC1UZYwwNGgxmUEuahzYK21UJibS5jNkupHbLToqw", 30000000000000000000000), + ("5FH32Ro5cTpLE1FhP3skdi16UuVariyzoQfyK7vvjE2CHEtX", 28721849310000000043843584), +]; + +#[cfg(test)] +mod tests { + use super::*; + use core::str::FromStr; + use pallet_airdrop_claims::MultiAddress; + use sp_core::H160; + use sp_runtime::AccountId32; + + #[test] + fn test_decoding_accounts_into_account_id_32_bytes() { + for (address, _) in INVESTOR_ACCOUNTS { + let account_id = if address.starts_with("0x") { + MultiAddress::EVM( + H160::from_str(address).expect("should be a valid address").into(), + ) + .to_account_id_32() + } else { + let account = MultiAddress::Native( + AccountId32::from_str(address).expect("should be a valid address"), + ) + .to_account_id_32(); + + assert_eq!( + account, + AccountId32::from_str(address).expect("should be a valid address") + ); + + account + }; + + let account_id_bytes: [u8; 32] = account_id.into(); + println!("INVESTOR | {:?}", account_id_bytes); + } + + for (address, _) in TEAM_ACCOUNTS { + let account_id = MultiAddress::Native( + AccountId32::from_str(address).expect("should be a valid address"), + ) + .to_account_id_32(); + + let account_id_bytes: [u8; 32] = account_id.into(); + println!("TEAM | {:?}", account_id_bytes); + } + } +} diff --git a/pallets/multi-asset-delegation/src/lib.rs b/pallets/multi-asset-delegation/src/lib.rs index cff555d4e..b2c278ba9 100644 --- a/pallets/multi-asset-delegation/src/lib.rs +++ b/pallets/multi-asset-delegation/src/lib.rs @@ -82,10 +82,7 @@ pub mod pallet { use crate::types::{delegator::DelegatorBlueprintSelection, *}; use frame_support::{ pallet_prelude::*, - traits::{ - fungibles::Inspect, tokens::fungibles, Currency, Get, LockableCurrency, - ReservableCurrency, - }, + traits::{tokens::fungibles, Currency, Get, LockableCurrency, ReservableCurrency}, PalletId, }; use frame_system::pallet_prelude::*; diff --git a/primitives/src/services/mod.rs b/primitives/src/services/mod.rs index 115f4c262..31ba7b53b 100644 --- a/primitives/src/services/mod.rs +++ b/primitives/src/services/mod.rs @@ -19,9 +19,8 @@ use crate::Weight; use educe::Educe; use fp_evm::CallInfo; use frame_support::pallet_prelude::*; -use serde::Deserializer; #[cfg(feature = "std")] -use serde::{Deserialize, Serialize}; +use serde::{Deserialize, Deserializer, Serialize}; use sp_core::{ByteArray, RuntimeDebug, H160, U256}; use sp_runtime::Percent; diff --git a/runtime/mainnet/Cargo.toml b/runtime/mainnet/Cargo.toml index 6aadcbbcf..85b449d30 100644 --- a/runtime/mainnet/Cargo.toml +++ b/runtime/mainnet/Cargo.toml @@ -279,6 +279,28 @@ std = [ "pallet-evm-precompile-multi-asset-delegation/std", ] +try-runtime = [ + "frame-support/try-runtime", + "frame-executive/try-runtime", + "frame-system/try-runtime", + "pallet-balances/try-runtime", + "pallet-grandpa/try-runtime", + "pallet-timestamp/try-runtime", + "pallet-vesting/try-runtime", + "pallet-assets/try-runtime", + "pallet-collective/try-runtime", + "pallet-tx-pause/try-runtime", + "pallet-staking/try-runtime", + "sp-runtime/try-runtime", + + # Frontier + "pallet-ethereum/try-runtime", + "pallet-evm/try-runtime", + "pallet-hotfix-sufficients/try-runtime", + # Tangle + "pallet-services/try-runtime", +] + integration-tests = ["tangle-primitives/integration-tests"] with-rocksdb-weights = [] with-paritydb-weights = [] diff --git a/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs b/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs index b862c66cd..6727c2306 100644 --- a/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs +++ b/runtime/mainnet/src/migrations/investor_team_vesting_migration_11302024.rs @@ -1,6 +1,4 @@ use frame_support::{pallet_prelude::*, traits::OnRuntimeUpgrade}; -#[cfg(feature = "try-runtime")] -use pallet_airdrop_claims::MultiAddress; use pallet_vesting::{MaxVestingSchedulesGet, Vesting, VestingInfo}; use sp_runtime::{ traits::{Convert, EnsureDiv, Header, Zero}, @@ -130,9 +128,51 @@ pub const INVESTOR_ACCOUNTS: [[u8; 32]; 29] = [ ], ]; -pub const TEAM_ACCOUNT_TO_UPDATE: [u8; 32] = [ - 142, 28, 43, 221, 218, 185, 87, 61, 140, 176, 148, 219, 255, 186, 36, 162, 178, 194, 27, 126, - 113, 227, 245, 182, 4, 232, 96, 116, 131, 135, 36, 67, +pub const TEAM_ACCOUNTS: [[u8; 32]; 11] = [ + [ + 220, 217, 183, 10, 4, 9, 183, 98, 108, 186, 26, 64, 22, 216, 218, 25, 244, 223, 92, 233, + 252, 94, 141, 22, 183, 137, 231, 27, 177, 22, 29, 115, + ], + [ + 76, 227, 164, 218, 58, 124, 28, 230, 95, 126, 222, 255, 134, 77, 195, 221, 66, 232, 244, + 126, 236, 194, 114, 109, 153, 160, 168, 1, 36, 105, 130, 23, + ], + [ + 226, 96, 78, 172, 142, 71, 162, 218, 115, 191, 193, 196, 247, 215, 108, 71, 131, 198, 47, + 143, 92, 45, 64, 78, 106, 176, 223, 167, 103, 39, 29, 33, + ], + [ + 162, 133, 55, 193, 209, 134, 98, 231, 154, 181, 108, 72, 150, 15, 166, 174, 160, 28, 203, + 238, 113, 51, 80, 242, 197, 70, 70, 237, 33, 244, 251, 67, + ], + [ + 112, 37, 90, 147, 193, 18, 157, 49, 188, 57, 43, 67, 30, 93, 62, 212, 223, 135, 97, 116, + 54, 19, 11, 84, 98, 79, 154, 98, 77, 97, 206, 66, + ], + [ + 242, 66, 123, 184, 39, 134, 15, 110, 181, 6, 187, 139, 110, 58, 126, 105, 95, 171, 231, + 171, 87, 30, 111, 88, 107, 141, 246, 112, 113, 230, 9, 127, + ], + [ + 72, 59, 70, 104, 50, 224, 148, 240, 27, 23, 121, 167, 237, 7, 2, 93, 243, 25, 196, 146, + 218, 197, 22, 10, 202, 137, 163, 190, 17, 122, 123, 109, + ], + [ + 140, 62, 57, 135, 164, 41, 178, 70, 246, 25, 233, 31, 140, 164, 85, 53, 161, 191, 95, 135, + 14, 199, 197, 207, 246, 169, 16, 169, 148, 151, 139, 65, + ], + [ + 134, 208, 142, 123, 190, 119, 188, 116, 227, 216, 142, 226, 46, 220, 83, 54, 139, 193, 61, + 97, 158, 5, 182, 111, 230, 196, 184, 226, 213, 199, 1, 90, + ], + [ + 220, 247, 191, 133, 183, 80, 119, 15, 91, 184, 117, 45, 0, 7, 150, 96, 236, 168, 190, 205, + 63, 90, 138, 73, 172, 186, 174, 240, 173, 126, 237, 8, + ], + [ + 142, 28, 43, 221, 218, 185, 87, 61, 140, 176, 148, 219, 255, 186, 36, 162, 178, 194, 27, + 126, 113, 227, 245, 182, 4, 232, 96, 116, 131, 135, 36, 67, + ], ]; /// Migration to update team and investor vesting schedules to 4 years with 1 year cliff @@ -161,9 +201,11 @@ impl OnRuntimeUpgrade } // Update team vesting schedule - let account_id: T::AccountId = - T::AccountId::decode(&mut TEAM_ACCOUNT_TO_UPDATE.as_ref()).expect("Invalid account ID"); - update_account_vesting::(&account_id, &mut reads, &mut writes); + for account in TEAM_ACCOUNTS.iter() { + let account_id: T::AccountId = + T::AccountId::decode(&mut account.as_ref()).expect("Invalid account ID"); + update_account_vesting::(&account_id, &mut reads, &mut writes); + } T::DbWeight::get().reads_writes(reads, writes) } @@ -255,14 +297,22 @@ fn update_vesting_schedule( fn verify_updated_schedule( account_id: &T::AccountId, ) -> Result<(), &'static str> { + use sp_runtime::traits::Block; + if let Some(schedules) = Vesting::::get(account_id) { ensure!(schedules.len() >= 2, "Schedule should have at least 2 entries"); ensure!( - schedules[0].starting_block() == T::BlockNumber::from(ONE_YEAR_BLOCKS as u32), + schedules[0].starting_block() + == <<::Block as Block>::Header as Header>::Number::from( + ONE_YEAR_BLOCKS as u32 + ), "First schedule should start at 1 year" ); ensure!( - schedules[1].starting_block() == T::BlockNumber::from(ONE_YEAR_BLOCKS as u32), + schedules[1].starting_block() + == <<::Block as Block>::Header as Header>::Number::from( + ONE_YEAR_BLOCKS as u32 + ), "Second schedule should start at 1 year" ); ensure!(schedules[0].per_block().is_zero(), "First schedule should have zero per_block");