diff --git a/Cargo.lock b/Cargo.lock index 7194b5820f894..d9b477510bcef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,5 +1,7 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 3 + [[package]] name = "Inflector" version = "0.11.4" @@ -1730,6 +1732,7 @@ dependencies = [ "frame-support", "frame-system", "hex-literal", + "pallet-accounts", "pallet-balances", "pallet-indices", "pallet-transaction-payment", @@ -1840,6 +1843,7 @@ dependencies = [ "frame-support", "impl-trait-for-tuples", "log", + "pallet-accounts", "parity-scale-codec", "serde", "sp-core", @@ -4050,6 +4054,7 @@ dependencies = [ "node-primitives", "node-runtime", "node-testing", + "pallet-accounts", "pallet-balances", "pallet-contracts", "pallet-grandpa", @@ -4163,6 +4168,7 @@ dependencies = [ "hex-literal", "log", "node-primitives", + "pallet-accounts", "pallet-assets", "pallet-authority-discovery", "pallet-authorship", @@ -4273,6 +4279,7 @@ dependencies = [ "frame-system-benchmarking", "frame-system-rpc-runtime-api", "hex-literal", + "pallet-accounts", "pallet-aura", "pallet-balances", "pallet-grandpa", @@ -4494,6 +4501,20 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "pallet-accounts" +version = "3.0.0" +dependencies = [ + "frame-support", + "frame-system", + "log", + "parity-scale-codec", + "serde", + "sp-core", + "sp-io", + "sp-std", +] + [[package]] name = "pallet-assets" version = "3.0.0" @@ -4501,6 +4522,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -4516,6 +4538,7 @@ version = "3.0.0" dependencies = [ "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -4552,6 +4575,7 @@ version = "3.0.0" dependencies = [ "frame-support", "frame-system", + "pallet-accounts", "pallet-session", "parity-scale-codec", "serde", @@ -4589,6 +4613,7 @@ dependencies = [ "frame-support", "frame-system", "log", + "pallet-accounts", "pallet-authorship", "pallet-balances", "pallet-offences", @@ -4619,6 +4644,7 @@ dependencies = [ "frame-support", "frame-system", "log", + "pallet-accounts", "pallet-transaction-payment", "parity-scale-codec", "serde", @@ -4635,6 +4661,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "pallet-treasury", "parity-scale-codec", @@ -4674,6 +4701,7 @@ dependencies = [ "frame-system", "hex-literal", "log", + "pallet-accounts", "pallet-balances", "pallet-contracts-primitives", "pallet-contracts-proc-macro", @@ -4753,6 +4781,7 @@ dependencies = [ "frame-support", "frame-system", "hex-literal", + "pallet-accounts", "pallet-balances", "pallet-scheduler", "parity-scale-codec", @@ -4774,6 +4803,7 @@ dependencies = [ "frame-system", "hex-literal", "log", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "parking_lot 0.11.1", @@ -4799,6 +4829,7 @@ dependencies = [ "frame-support", "frame-system", "hex-literal", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -4817,6 +4848,7 @@ dependencies = [ "frame-system", "hex-literal", "log", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -4835,6 +4867,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -4883,6 +4916,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -4902,6 +4936,7 @@ dependencies = [ "frame-support", "frame-system", "log", + "pallet-accounts", "pallet-authorship", "pallet-balances", "pallet-offences", @@ -4931,6 +4966,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -4948,6 +4984,7 @@ dependencies = [ "frame-support", "frame-system", "log", + "pallet-accounts", "pallet-authorship", "pallet-session", "parity-scale-codec", @@ -4967,6 +5004,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -4985,6 +5023,7 @@ dependencies = [ "frame-support", "frame-support-test", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -5068,6 +5107,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -5083,6 +5123,7 @@ version = "3.0.0" dependencies = [ "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -5131,6 +5172,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-babe", "pallet-balances", "pallet-grandpa", @@ -5157,6 +5199,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "pallet-utility", "parity-scale-codec", @@ -5189,6 +5232,7 @@ dependencies = [ "enumflags2", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -5221,6 +5265,7 @@ version = "3.0.0" dependencies = [ "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -5238,6 +5283,7 @@ dependencies = [ "frame-system", "impl-trait-for-tuples", "lazy_static", + "pallet-accounts", "pallet-timestamp", "parity-scale-codec", "serde", @@ -5258,6 +5304,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "pallet-session", "pallet-staking", @@ -5281,6 +5328,7 @@ dependencies = [ "frame-support", "frame-support-test", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "rand_chacha 0.2.2", @@ -5300,6 +5348,7 @@ dependencies = [ "frame-system", "hex", "log", + "pallet-accounts", "pallet-authorship", "pallet-balances", "pallet-session", @@ -5330,6 +5379,7 @@ dependencies = [ "frame-support", "frame-system", "honggfuzz", + "pallet-accounts", "pallet-balances", "pallet-indices", "pallet-session", @@ -5411,6 +5461,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "pallet-treasury", "parity-scale-codec", @@ -5428,6 +5479,7 @@ version = "3.0.0" dependencies = [ "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -5474,6 +5526,7 @@ dependencies = [ "frame-support", "frame-system", "impl-trait-for-tuples", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -5491,6 +5544,7 @@ dependencies = [ "frame-benchmarking", "frame-support", "frame-system", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -5509,6 +5563,7 @@ dependencies = [ "frame-support", "frame-system", "hex-literal", + "pallet-accounts", "pallet-balances", "parity-scale-codec", "serde", @@ -9381,6 +9436,7 @@ dependencies = [ "frame-system-rpc-runtime-api", "log", "memory-db", + "pallet-accounts", "pallet-babe", "pallet-timestamp", "parity-scale-codec", diff --git a/Cargo.toml b/Cargo.toml index 4d8cfc3e9754d..7d187b3b8b92e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,6 +59,8 @@ members = [ "client/tracing/proc-macro", "client/transaction-pool", "client/transaction-pool/graph", + "frame/accounts", + "frame/system/rpc/runtime-api", "frame/assets", "frame/atomic-swap", "frame/aura", @@ -114,7 +116,6 @@ members = [ "frame/support/test", "frame/system", "frame/system/benchmarking", - "frame/system/rpc/runtime-api", "frame/timestamp", "frame/transaction-payment", "frame/transaction-payment/rpc", diff --git a/bin/node-template/pallets/template/src/mock.rs b/bin/node-template/pallets/template/src/mock.rs index d33670f2e9cb0..f2ab9e3492853 100644 --- a/bin/node-template/pallets/template/src/mock.rs +++ b/bin/node-template/pallets/template/src/mock.rs @@ -7,7 +7,7 @@ use sp_runtime::{ use frame_system as system; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; -type Block = frame_system::mocking::MockBlock; +type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( @@ -44,9 +44,7 @@ impl system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = SS58Prefix; } diff --git a/bin/node-template/runtime/Cargo.toml b/bin/node-template/runtime/Cargo.toml index d4e202d688c87..eb461fdb0fbc1 100644 --- a/bin/node-template/runtime/Cargo.toml +++ b/bin/node-template/runtime/Cargo.toml @@ -15,6 +15,7 @@ codec = { package = "parity-scale-codec", version = "2.0.0", default-features = pallet-aura = { version = "3.0.0", default-features = false, path = "../../../frame/aura" } pallet-balances = { version = "3.0.0", default-features = false, path = "../../../frame/balances" } +pallet-accounts = { version = "3.0.0", default-features = false, path = "../../../frame/accounts" } frame-support = { version = "3.0.0", default-features = false, path = "../../../frame/support" } pallet-grandpa = { version = "3.0.0", default-features = false, path = "../../../frame/grandpa" } pallet-randomness-collective-flip = { version = "3.0.0", default-features = false, path = "../../../frame/randomness-collective-flip" } diff --git a/bin/node-template/runtime/src/lib.rs b/bin/node-template/runtime/src/lib.rs index 0f026db5735cc..b6619b16bab0a 100644 --- a/bin/node-template/runtime/src/lib.rs +++ b/bin/node-template/runtime/src/lib.rs @@ -140,7 +140,6 @@ parameter_types! { } // Configure FRAME pallets to include in runtime. - impl frame_system::Config for Runtime { /// The basic call filter to use in dispatchable. type BaseCallFilter = (); @@ -178,16 +177,22 @@ impl frame_system::Config for Runtime { /// /// This type is being generated by `construct_runtime!`. type PalletInfo = PalletInfo; + /// Weight information for the extrinsics of this pallet. + type SystemWeightInfo = (); + /// This is used as an identifier of the chain. 42 is the generic substrate prefix. + type SS58Prefix = SS58Prefix; + /// This is where we store account information. + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Runtime { + type Event = Event; /// What to do if a new account is created. type OnNewAccount = (); /// What to do if an account is fully reaped from the system. type OnKilledAccount = (); /// The data to be stored in an account. type AccountData = pallet_balances::AccountData; - /// Weight information for the extrinsics of this pallet. - type SystemWeightInfo = (); - /// This is used as an identifier of the chain. 42 is the generic substrate prefix. - type SS58Prefix = SS58Prefix; } impl pallet_aura::Config for Runtime { @@ -238,7 +243,8 @@ impl pallet_balances::Config for Runtime { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = pallet_balances::weights::SubstrateWeight; } @@ -271,6 +277,7 @@ construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Aura: pallet_aura::{Module, Config}, @@ -427,7 +434,8 @@ impl_runtime_apis! { impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) + use frame_support::traits::BasicAccount; + Accounts::account_nonce(&account) } } diff --git a/bin/node/executor/Cargo.toml b/bin/node/executor/Cargo.toml index fb7fc9191141c..3dc784b13114e 100644 --- a/bin/node/executor/Cargo.toml +++ b/bin/node/executor/Cargo.toml @@ -29,6 +29,7 @@ criterion = "0.3.0" frame-support = { version = "3.0.0", path = "../../../frame/support" } frame-system = { version = "3.0.0", path = "../../../frame/system" } node-testing = { version = "2.0.0", path = "../testing" } +pallet-accounts = { version = "3.0.0", path = "../../../frame/accounts" } pallet-balances = { version = "3.0.0", path = "../../../frame/balances" } pallet-contracts = { version = "3.0.0", path = "../../../frame/contracts" } pallet-grandpa = { version = "3.0.0", path = "../../../frame/grandpa" } diff --git a/bin/node/executor/tests/basic.rs b/bin/node/executor/tests/basic.rs index 279b6a776031a..7a116501ab369 100644 --- a/bin/node/executor/tests/basic.rs +++ b/bin/node/executor/tests/basic.rs @@ -26,7 +26,8 @@ use sp_runtime::{ traits::Hash as HashT, transaction_validity::InvalidTransaction, }; -use frame_system::{self, EventRecord, Phase, AccountInfo}; +use frame_system::{self, EventRecord, Phase}; +use pallet_accounts::AccountInfo; use node_runtime::{ Header, Block, UncheckedExtrinsic, CheckedExtrinsic, Call, Runtime, Balances, @@ -168,7 +169,7 @@ fn block_with_size(time: u64, nonce: u32, size: usize) -> (Vec, Hash) { fn panic_execution_with_foreign_code_gives_error() { let mut t = new_test_ext(bloaty_code_unwrap(), false); t.insert( - >::hashed_key_for(alice()), + >::hashed_key_for(alice()), (69u128, 0u32, 0u128, 0u128, 0u128).encode() ); t.insert(>::hashed_key().to_vec(), 69_u128.encode()); @@ -197,7 +198,7 @@ fn panic_execution_with_foreign_code_gives_error() { fn bad_extrinsic_with_native_equivalent_code_gives_error() { let mut t = new_test_ext(compact_code_unwrap(), false); t.insert( - >::hashed_key_for(alice()), + >::hashed_key_for(alice()), (0u32, 0u32, 0u32, 69u128, 0u128, 0u128, 0u128).encode() ); t.insert(>::hashed_key().to_vec(), 69_u128.encode()); @@ -226,14 +227,14 @@ fn bad_extrinsic_with_native_equivalent_code_gives_error() { fn successful_execution_with_native_equivalent_code_gives_ok() { let mut t = new_test_ext(compact_code_unwrap(), false); t.insert( - >::hashed_key_for(alice()), + >::hashed_key_for(alice()), AccountInfo::<::Index, _> { data: (111 * DOLLARS, 0u128, 0u128, 0u128), .. Default::default() }.encode(), ); t.insert( - >::hashed_key_for(bob()), + >::hashed_key_for(bob()), AccountInfo::<::Index, _> { data: (0 * DOLLARS, 0u128, 0u128, 0u128), .. Default::default() @@ -275,14 +276,14 @@ fn successful_execution_with_native_equivalent_code_gives_ok() { fn successful_execution_with_foreign_code_gives_ok() { let mut t = new_test_ext(bloaty_code_unwrap(), false); t.insert( - >::hashed_key_for(alice()), + >::hashed_key_for(alice()), AccountInfo::<::Index, _> { data: (111 * DOLLARS, 0u128, 0u128, 0u128), .. Default::default() }.encode(), ); t.insert( - >::hashed_key_for(bob()), + >::hashed_key_for(bob()), AccountInfo::<::Index, _> { data: (0 * DOLLARS, 0u128, 0u128, 0u128), .. Default::default() @@ -715,7 +716,7 @@ fn native_big_block_import_fails_on_fallback() { fn panic_execution_gives_error() { let mut t = new_test_ext(bloaty_code_unwrap(), false); t.insert( - >::hashed_key_for(alice()), + >::hashed_key_for(alice()), AccountInfo::<::Index, _> { data: (0 * DOLLARS, 0u128, 0u128, 0u128), .. Default::default() @@ -747,14 +748,14 @@ fn panic_execution_gives_error() { fn successful_execution_gives_ok() { let mut t = new_test_ext(compact_code_unwrap(), false); t.insert( - >::hashed_key_for(alice()), + >::hashed_key_for(alice()), AccountInfo::<::Index, _> { data: (111 * DOLLARS, 0u128, 0u128, 0u128), .. Default::default() }.encode(), ); t.insert( - >::hashed_key_for(bob()), + >::hashed_key_for(bob()), AccountInfo::<::Index, _> { data: (0 * DOLLARS, 0u128, 0u128, 0u128), .. Default::default() diff --git a/bin/node/executor/tests/fees.rs b/bin/node/executor/tests/fees.rs index ad24db03f9832..e034539ec8451 100644 --- a/bin/node/executor/tests/fees.rs +++ b/bin/node/executor/tests/fees.rs @@ -125,7 +125,7 @@ fn fee_multiplier_increases_and_decreases_on_big_weight() { } fn new_account_info(free_dollars: u128) -> Vec { - frame_system::AccountInfo { + pallet_accounts::AccountInfo { nonce: 0u32, consumers: 0, providers: 0, @@ -144,8 +144,8 @@ fn transaction_fee_is_correct() { // - 1 milli-dot based on current polkadot runtime. // (this baed on assigning 0.1 CENT to the cheapest tx with `weight = 100`) let mut t = new_test_ext(compact_code_unwrap(), false); - t.insert(>::hashed_key_for(alice()), new_account_info(100)); - t.insert(>::hashed_key_for(bob()), new_account_info(10)); + t.insert(>::hashed_key_for(alice()), new_account_info(100)); + t.insert(>::hashed_key_for(bob()), new_account_info(10)); t.insert( >::hashed_key().to_vec(), (110 * DOLLARS).encode() diff --git a/bin/node/executor/tests/submit_transaction.rs b/bin/node/executor/tests/submit_transaction.rs index 3de0758d81462..fd3e5ef9be342 100644 --- a/bin/node/executor/tests/submit_transaction.rs +++ b/bin/node/executor/tests/submit_transaction.rs @@ -252,8 +252,8 @@ fn submitted_transaction_should_be_valid() { let author = extrinsic.signature.clone().unwrap().0; let address = Indices::lookup(author).unwrap(); let data = pallet_balances::AccountData { free: 5_000_000_000_000, ..Default::default() }; - let account = frame_system::AccountInfo { data, .. Default::default() }; - >::insert(&address, account); + let account = pallet_accounts::AccountInfo { data, .. Default::default() }; + >::insert(&address, account); // check validity let res = Executive::validate_transaction(source, extrinsic).unwrap(); diff --git a/bin/node/runtime/Cargo.toml b/bin/node/runtime/Cargo.toml index 43ecca7e74456..069eb965b1d21 100644 --- a/bin/node/runtime/Cargo.toml +++ b/bin/node/runtime/Cargo.toml @@ -38,6 +38,7 @@ sp-transaction-pool = { version = "3.0.0", default-features = false, path = "../ sp-version = { version = "3.0.0", default-features = false, path = "../../../primitives/version" } # frame dependencies +pallet-accounts = { version = "3.0.0", default-features = false, path = "../../../frame/accounts" } frame-executive = { version = "3.0.0", default-features = false, path = "../../../frame/executive" } frame-benchmarking = { version = "3.1.0", default-features = false, path = "../../../frame/benchmarking", optional = true } frame-support = { version = "3.0.0", default-features = false, path = "../../../frame/support" } diff --git a/bin/node/runtime/src/lib.rs b/bin/node/runtime/src/lib.rs index 2043f59eb99af..f439e4b9a8ee4 100644 --- a/bin/node/runtime/src/lib.rs +++ b/bin/node/runtime/src/lib.rs @@ -208,11 +208,16 @@ impl frame_system::Config for Runtime { type BlockHashCount = BlockHashCount; type Version = Version; type PalletInfo = PalletInfo; + type SystemWeightInfo = frame_system::weights::SubstrateWeight; + type SS58Prefix = SS58Prefix; + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Runtime { + type Event = Event; type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); - type SystemWeightInfo = frame_system::weights::SubstrateWeight; - type SS58Prefix = SS58Prefix; } impl pallet_utility::Config for Runtime { @@ -379,7 +384,8 @@ impl pallet_balances::Config for Runtime { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = pallet_balances::weights::SubstrateWeight; } @@ -443,6 +449,7 @@ impl pallet_session::Config for Runtime { type SessionHandler = ::KeyTypeIdProviders; type Keys = SessionKeys; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; + type ReferencedAccount = Accounts; type WeightInfo = pallet_session::weights::SubstrateWeight; } @@ -508,6 +515,7 @@ impl pallet_staking::Config for Runtime { // a single extrinsic. type OffchainSolutionWeightLimit = OffchainSolutionWeightLimit; type ElectionProvider = ElectionProviderMultiPhase; + type ReferencedAccount = Accounts; type WeightInfo = pallet_staking::weights::SubstrateWeight; } @@ -959,6 +967,7 @@ impl pallet_recovery::Config for Runtime { type ConfigDepositBase = ConfigDepositBase; type FriendDepositFactor = FriendDepositFactor; type MaxFriends = MaxFriends; + type ReferencedAccount = Accounts; type RecoveryDeposit = RecoveryDeposit; } @@ -1047,6 +1056,7 @@ impl pallet_assets::Config for Runtime { type AssetDeposit = AssetDeposit; type MetadataDepositBase = MetadataDepositBase; type MetadataDepositPerByte = MetadataDepositPerByte; + type ReferencedAccount = Accounts; type ApprovalDeposit = ApprovalDeposit; type StringLimit = StringLimit; type WeightInfo = pallet_assets::weights::SubstrateWeight; @@ -1087,6 +1097,7 @@ construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Utility: pallet_utility::{Module, Call, Event}, Babe: pallet_babe::{Module, Call, Storage, Config, ValidateUnsigned}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, @@ -1332,7 +1343,8 @@ impl_runtime_apis! { impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) + use frame_support::traits::BasicAccount; + Accounts::account_nonce(&account) } } diff --git a/frame/accounts/Cargo.toml b/frame/accounts/Cargo.toml new file mode 100644 index 0000000000000..582b1b28e72cd --- /dev/null +++ b/frame/accounts/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "pallet-accounts" +version = "3.0.0" +authors = ["Parity Technologies "] +edition = "2018" +license = "Apache-2.0" +homepage = "https://substrate.dev" +repository = "https://github.com/paritytech/substrate/" +description = "FRAME accounts module" +readme = "README.md" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } +sp-std = { version = "3.0.0", default-features = false, path = "../../primitives/std" } +frame-support = { version = "3.0.0", default-features = false, path = "../support" } +frame-system = { version = "3.0.0", default-features = false, path = "../system" } +log = { version = "0.4.14", default-features = false } + +[dev-dependencies] +serde = { version = "1.0.101", features = ["derive"] } +sp-core = { version = "3.0.0", path = "../../primitives/core" } +sp-io = { version = "3.0.0", path = "../../primitives/io" } + +[features] +default = ["std"] +std = [ + "codec/std", + "sp-std/std", + "frame-support/std", + "frame-system/std", + "log/std", +] +runtime-benchmarks = [ + "frame-system/runtime-benchmarks", + "frame-support/runtime-benchmarks", +] +try-runtime = ["frame-support/try-runtime"] diff --git a/frame/accounts/src/lib.rs b/frame/accounts/src/lib.rs new file mode 100644 index 0000000000000..c155b878a4394 --- /dev/null +++ b/frame/accounts/src/lib.rs @@ -0,0 +1,429 @@ +#![cfg_attr(not(feature = "std"), no_std)] + +use sp_std::{ + vec::Vec, + marker::PhantomData, +}; +use frame_support::{ + sp_runtime::{RuntimeDebug, traits::{StoredMapError, One}}, + traits::{HandleLifetime, StoredMap, OnNewAccount, OnKilledAccount, ReferencedAccount, BasicAccount}, +}; +use codec::{Encode, Decode, FullCodec}; + +#[cfg(test)] +mod mock; + +#[cfg(test)] +mod tests; + +/// Type used to encode the number of references an account has. +pub type RefCount = u32; + +/// Information of an account. +#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] +pub struct AccountInfo { + /// The number of transactions this account has sent. + pub nonce: Index, + /// The number of other modules that currently depend on this account's existence. The account + /// cannot be reaped until this is zero. + pub consumers: RefCount, + /// The number of other modules that allow this account to exist. The account may not be reaped + /// until this and `sufficients` are both zero. + pub providers: RefCount, + /// The number of modules that allow this account to exist for their own purposes only. The + /// account may not be reaped until this and `providers` are both zero. + pub sufficients: RefCount, + /// The additional data that belongs to this account. Used to store the balance(s) in a lot of + /// chains. + pub data: AccountData, +} + +/// Reference status; can be either referenced or unreferenced. +#[derive(RuntimeDebug)] +pub enum RefStatus { + Referenced, + Unreferenced, +} + +/// Some resultant status relevant to incrementing a provider/self-sufficient reference. +#[derive(Eq, PartialEq, RuntimeDebug)] +pub enum IncRefStatus { + /// Account was created. + Created, + /// Account already existed. + Existed, +} + +/// Some resultant status relevant to decrementing a provider/self-sufficient reference. +#[derive(Eq, PartialEq, RuntimeDebug)] +pub enum DecRefStatus { + /// Account was destroyed. + Reaped, + /// Account still exists. + Exists, +} + +/// Some resultant status relevant to decrementing a provider reference. +#[derive(Eq, PartialEq, RuntimeDebug)] +pub enum DecRefError { + /// Account cannot have the last provider reference removed while there is a consumer. + ConsumerRemaining, +} + +/// Some resultant status relevant to incrementing a consumer reference. +#[derive(Eq, PartialEq, RuntimeDebug)] +pub enum IncRefError { + /// Account cannot introduce a consumer while there are no providers. + NoProviders, +} + +pub use pallet::*; + +#[frame_support::pallet] +pub mod pallet { + use crate::*; + + use frame_system::pallet_prelude::*; + use frame_support::pallet_prelude::*; + + /// System configuration trait. Implemented by runtime. + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type Event: From> + IsType<::Event>; + + /// Data to be associated with an account (other than nonce/transaction counter, which this + /// pallet does regardless). + type AccountData: Member + FullCodec + Clone + Default; + + /// Handler for when a new account has just been created. + type OnNewAccount: OnNewAccount; + + /// A function that is invoked when an account has been determined to be dead. + /// + /// All resources should be cleaned up associated with the given account. + type OnKilledAccount: OnKilledAccount; + } + + /// Event for the Accounts pallet. + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + #[pallet::metadata(T::AccountId = "AccountId")] + pub enum Event { + /// A new \[account\] was created. + NewAccount(T::AccountId), + /// An \[account\] was reaped. + KilledAccount(T::AccountId), + } + + /// The full account information for a particular account ID. + #[pallet::storage] + #[pallet::getter(fn account)] + pub type Account = StorageMap< + _, + Blake2_128Concat, + T::AccountId, + AccountInfo::AccountData>, + ValueQuery, + >; + + #[pallet::pallet] + #[pallet::generate_store(pub (super) trait Store)] + pub struct Pallet(_); + + #[pallet::hooks] + impl Hooks> for Pallet {} + + #[pallet::call] + impl Pallet {} + + impl Pallet { + /// An account is being created. + pub(crate) fn on_created_account(who: T::AccountId, _a: &mut AccountInfo) { + T::OnNewAccount::on_new_account(&who); + Self::deposit_event(Event::NewAccount(who)); + } + + /// Do anything that needs to be done after an account has been killed. + pub(crate) fn on_killed_account(who: T::AccountId) { + T::OnKilledAccount::on_killed_account(&who); + Self::deposit_event(Event::KilledAccount(who)); + } + } +} + +/// Event handler which registers a provider when created. +pub struct Provider(PhantomData); +impl HandleLifetime for Provider { + fn created(t: &T::AccountId) -> Result<(), StoredMapError> { + Module::::inc_providers(t); + Ok(()) + } + fn killed(t: &T::AccountId) -> Result<(), StoredMapError> { + Module::::dec_providers(t) + .map(|_| ()) + .or_else(|e| match e { + DecRefError::ConsumerRemaining => Err(StoredMapError::ConsumerRemaining), + }) + } +} + +/// Event handler which registers a self-sufficient when created. +pub struct SelfSufficient(PhantomData); +impl HandleLifetime for SelfSufficient { + fn created(t: &T::AccountId) -> Result<(), StoredMapError> { + Module::::inc_sufficients(t); + Ok(()) + } + fn killed(t: &T::AccountId) -> Result<(), StoredMapError> { + Module::::dec_sufficients(t); + Ok(()) + } +} + +/// Event handler which registers a consumer when created. +pub struct Consumer(PhantomData); +impl HandleLifetime for Consumer { + fn created(t: &T::AccountId) -> Result<(), StoredMapError> { + Module::::inc_consumers(t) + .map_err(|e| match e { + IncRefError::NoProviders => StoredMapError::NoProviders + }) + } + fn killed(t: &T::AccountId) -> Result<(), StoredMapError> { + Module::::dec_consumers(t); + Ok(()) + } +} + +/// Implement StoredMap for a simple single-item, provide-when-not-default system. This works fine +/// for storing a single item which allows the account to continue existing as long as it's not +/// empty/default. +/// +/// Anything more complex will need more sophisticated logic. +impl StoredMap::AccountData> for Pallet { + fn get(k: &T::AccountId) -> ::AccountData { + Account::::get(k).data + } + + fn try_mutate_exists>( + k: &T::AccountId, + f: impl FnOnce(&mut Option<::AccountData>) -> Result, + ) -> Result { + let account = Account::::get(k); + let was_providing = is_providing(&account.data); + let mut some_data = if was_providing { Some(account.data) } else { None }; + let result = f(&mut some_data)?; + let is_providing = some_data.is_some(); + if !was_providing && is_providing { + Self::inc_providers(k); + } else if was_providing && !is_providing { + match Self::dec_providers(k) { + Err(DecRefError::ConsumerRemaining) => Err(StoredMapError::ConsumerRemaining)?, + Ok(DecRefStatus::Reaped) => return Ok(result), + Ok(DecRefStatus::Exists) => { + // Update value as normal... + } + } + } else if !was_providing && !is_providing { + return Ok(result) + } + Account::::mutate(k, |a| a.data = some_data.unwrap_or_default()); + Ok(result) + } +} + +fn is_providing(d: &T) -> bool { + d != &T::default() +} + +impl BasicAccount for Pallet { + type AccountInfo = AccountInfo::AccountData>; + + /// Return whether an account exists in storage. + fn account_exists(who: &T::AccountId) -> bool { + Account::::contains_key(who) + } + + /// Return the data for an account + fn get(who: &T::AccountId) -> Self::AccountInfo { + Account::::get(who) + } + + /// Retrieve the account transaction counter from storage. + fn account_nonce(who: &T::AccountId) -> T::Index { + Account::::get(who).nonce + } + + /// Increment a particular account's nonce by 1. + fn inc_account_nonce(who: &T::AccountId) { + Account::::mutate(who, |a| a.nonce += T::Index::one()); + } + + /// Return the storage key for an account. + fn hashed_key_for(who: &T::AccountId) -> Vec { + Account::::hashed_key_for(who) + } +} + +impl ReferencedAccount for Pallet { + type RefCount = RefCount; + type IncRefStatus = IncRefStatus; + type DecRefStatus = DecRefStatus; + type IncRefError = IncRefError; + type DecRefError = DecRefError; + + /// Increment the provider reference counter on an account. + fn inc_providers(who: &T::AccountId) -> IncRefStatus { + Account::::mutate(who, |a| if a.providers == 0 && a.sufficients == 0 { + // Account is being created. + a.providers = 1; + Self::on_created_account(who.clone(), a); + IncRefStatus::Created + } else { + a.providers = a.providers.saturating_add(1); + IncRefStatus::Existed + }) + } + + /// Decrement the provider reference counter on an account. + /// + /// This *MUST* only be done once for every time you called `inc_providers` on `who`. + fn dec_providers(who: &T::AccountId) -> Result { + Account::::try_mutate_exists(who, |maybe_account| { + if let Some(mut account) = maybe_account.take() { + if account.providers == 0 { + // Logic error - cannot decrement beyond zero. + log::error!( + target: "runtime::system", + "Logic error: Unexpected underflow in reducing provider", + ); + account.providers = 1; + } + match (account.providers, account.consumers, account.sufficients) { + (1, 0, 0) => { + // No providers left (and no consumers) and no sufficients. Account dead. + + Module::::on_killed_account(who.clone()); + Ok(DecRefStatus::Reaped) + } + (1, c, _) if c > 0 => { + // Cannot remove last provider if there are consumers. + Err(DecRefError::ConsumerRemaining) + } + (x, _, _) => { + // Account will continue to exist as there is either > 1 provider or + // > 0 sufficients. + account.providers = x - 1; + *maybe_account = Some(account); + Ok(DecRefStatus::Exists) + } + } + } else { + log::error!( + target: "runtime::system", + "Logic error: Account already dead when reducing provider", + ); + Ok(DecRefStatus::Reaped) + } + }) + } + + /// Increment the self-sufficient reference counter on an account. + fn inc_sufficients(who: &T::AccountId) -> IncRefStatus { + Account::::mutate(who, |a| if a.providers + a.sufficients == 0 { + // Account is being created. + a.sufficients = 1; + Self::on_created_account(who.clone(), a); + IncRefStatus::Created + } else { + a.sufficients = a.sufficients.saturating_add(1); + IncRefStatus::Existed + }) + } + + /// Decrement the self-sufficient reference counter on an account. + /// + /// This *MUST* only be done once for every time you called `inc_sufficients` on `who`. + fn dec_sufficients(who: &T::AccountId) -> DecRefStatus { + Account::::mutate_exists(who, |maybe_account| { + if let Some(mut account) = maybe_account.take() { + if account.sufficients == 0 { + // Logic error - cannot decrement beyond zero. + log::error!( + target: "runtime::system", + "Logic error: Unexpected underflow in reducing sufficients", + ); + } + match (account.sufficients, account.providers) { + (0, 0) | (1, 0) => { + Module::::on_killed_account(who.clone()); + DecRefStatus::Reaped + } + (x, _) => { + account.sufficients = x - 1; + *maybe_account = Some(account); + DecRefStatus::Exists + } + } + } else { + log::error!( + target: "runtime::system", + "Logic error: Account already dead when reducing provider", + ); + DecRefStatus::Reaped + } + }) + } + + /// The number of outstanding provider references for the account `who`. + fn providers(who: &T::AccountId) -> RefCount { + Account::::get(who).providers + } + + /// The number of outstanding sufficient references for the account `who`. + fn sufficients(who: &T::AccountId) -> RefCount { + Account::::get(who).sufficients + } + + /// The number of outstanding provider and sufficient references for the account `who`. + fn reference_count(who: &T::AccountId) -> RefCount { + let a = Account::::get(who); + a.providers + a.sufficients + } + + /// Increment the reference counter on an account. + /// + /// The account `who`'s `providers` must be non-zero or this will return an error. + fn inc_consumers(who: &T::AccountId) -> Result<(), IncRefError> { + Account::::try_mutate(who, |a| if a.providers > 0 { + a.consumers = a.consumers.saturating_add(1); + Ok(()) + } else { + Err(IncRefError::NoProviders) + }) + } + + /// Decrement the reference counter on an account. This *MUST* only be done once for every time + /// you called `inc_consumers` on `who`. + fn dec_consumers(who: &T::AccountId) { + Account::::mutate(who, |a| if a.consumers > 0 { + a.consumers -= 1; + } else { + log::error!( + target: "runtime::system", + "Logic error: Unexpected underflow in reducing consumer", + ); + }) + } + + /// The number of outstanding references for the account `who`. + fn consumers(who: &T::AccountId) -> RefCount { + Account::::get(who).consumers + } + + /// True if the account has some outstanding references. + fn is_provider_required(who: &T::AccountId) -> bool { + Account::::get(who).consumers != 0 + } +} diff --git a/frame/accounts/src/mock.rs b/frame/accounts/src/mock.rs new file mode 100644 index 0000000000000..b0e36bad1ff6d --- /dev/null +++ b/frame/accounts/src/mock.rs @@ -0,0 +1,84 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{self as pallet_accounts, *}; +use sp_std::cell::RefCell; +use sp_core::H256; +use frame_support::{ + sp_runtime::{ + traits::{BlakeTwo256, IdentityLookup}, + testing::Header, + }, +}; + +type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +type Block = frame_system::mocking::MockBlock; + +frame_support::construct_runtime!( + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, + } +); + +thread_local!{ + pub static KILLED: RefCell> = RefCell::new(vec![]); +} + +pub struct RecordKilled; +impl OnKilledAccount for RecordKilled { + fn on_killed_account(who: &u64) { KILLED.with(|r| r.borrow_mut().push(*who)) } +} + +impl frame_system::Config for Test { + type BaseCallFilter = (); + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type Origin = Origin; + type Index = u64; + type Call = Call; + type BlockNumber = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; + type Header = Header; + type Event = Event; + type BlockHashCount = (); + type Version = (); + type PalletInfo = PalletInfo; + type SystemWeightInfo = (); + type SS58Prefix = (); + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Test { + type Event = Event; + type AccountData = u32; + type OnNewAccount = (); + type OnKilledAccount = RecordKilled; +} + +/// Create new externalities for `System` module tests. +pub fn new_test_ext() -> sp_io::TestExternalities { + frame_system::GenesisConfig::default().build_storage::().unwrap().into() +} diff --git a/frame/accounts/src/tests.rs b/frame/accounts/src/tests.rs new file mode 100644 index 0000000000000..2a14cb836d3ef --- /dev/null +++ b/frame/accounts/src/tests.rs @@ -0,0 +1,141 @@ +// This file is part of Substrate. + +// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::*; +use mock::*; +use frame_support::assert_noop; + +#[test] +fn stored_map_works() { + new_test_ext().execute_with(|| { + assert!(Accounts::insert(&0, 42).is_ok()); + assert!(!Accounts::is_provider_required(&0)); + + assert_eq!(Account::::get(0), AccountInfo { + nonce: 0, + providers: 1, + consumers: 0, + sufficients: 0, + data: 42, + }); + + assert!(Accounts::inc_consumers(&0).is_ok()); + assert!(Accounts::is_provider_required(&0)); + + assert!(Accounts::insert(&0, 69).is_ok()); + assert!(Accounts::is_provider_required(&0)); + + Accounts::dec_consumers(&0); + assert!(!Accounts::is_provider_required(&0)); + + assert!(KILLED.with(|r| r.borrow().is_empty())); + assert!(Accounts::remove(&0).is_ok()); + assert_eq!(KILLED.with(|r| r.borrow().clone()), vec![0u64]); + }); +} + +#[test] +fn provider_ref_handover_to_self_sufficient_ref_works() { + new_test_ext().execute_with(|| { + assert_eq!(Accounts::inc_providers(&0), IncRefStatus::Created); + Accounts::inc_account_nonce(&0); + assert_eq!(Accounts::account_nonce(&0), 1); + + // a second reference coming and going doesn't change anything. + assert_eq!(Accounts::inc_sufficients(&0), IncRefStatus::Existed); + assert_eq!(Accounts::dec_sufficients(&0), DecRefStatus::Exists); + assert_eq!(Accounts::account_nonce(&0), 1); + + // a provider reference coming and going doesn't change anything. + assert_eq!(Accounts::inc_providers(&0), IncRefStatus::Existed); + assert_eq!(Accounts::dec_providers(&0).unwrap(), DecRefStatus::Exists); + assert_eq!(Accounts::account_nonce(&0), 1); + + // decreasing the providers with a self-sufficient present should not delete the account + assert_eq!(Accounts::inc_sufficients(&0), IncRefStatus::Existed); + assert_eq!(Accounts::dec_providers(&0).unwrap(), DecRefStatus::Exists); + assert_eq!(Accounts::account_nonce(&0), 1); + + // decreasing the sufficients should delete the account + assert_eq!(Accounts::dec_sufficients(&0), DecRefStatus::Reaped); + assert_eq!(Accounts::account_nonce(&0), 0); + }); +} + +#[test] +fn self_sufficient_ref_handover_to_provider_ref_works() { + new_test_ext().execute_with(|| { + assert_eq!(Accounts::inc_sufficients(&0), IncRefStatus::Created); + Accounts::inc_account_nonce(&0); + assert_eq!(Accounts::account_nonce(&0), 1); + + // a second reference coming and going doesn't change anything. + assert_eq!(Accounts::inc_providers(&0), IncRefStatus::Existed); + assert_eq!(Accounts::dec_providers(&0).unwrap(), DecRefStatus::Exists); + assert_eq!(Accounts::account_nonce(&0), 1); + + // a sufficient reference coming and going doesn't change anything. + assert_eq!(Accounts::inc_sufficients(&0), IncRefStatus::Existed); + assert_eq!(Accounts::dec_sufficients(&0), DecRefStatus::Exists); + assert_eq!(Accounts::account_nonce(&0), 1); + + // decreasing the sufficients with a provider present should not delete the account + assert_eq!(Accounts::inc_providers(&0), IncRefStatus::Existed); + assert_eq!(Accounts::dec_sufficients(&0), DecRefStatus::Exists); + assert_eq!(Accounts::account_nonce(&0), 1); + + // decreasing the providers should delete the account + assert_eq!(Accounts::dec_providers(&0).unwrap(), DecRefStatus::Reaped); + assert_eq!(Accounts::account_nonce(&0), 0); + }); +} + +#[test] +fn sufficient_cannot_support_consumer() { + new_test_ext().execute_with(|| { + assert_eq!(Accounts::inc_sufficients(&0), IncRefStatus::Created); + Accounts::inc_account_nonce(&0); + assert_eq!(Accounts::account_nonce(&0), 1); + assert_noop!(Accounts::inc_consumers(&0), IncRefError::NoProviders); + + assert_eq!(Accounts::inc_providers(&0), IncRefStatus::Existed); + assert!(Accounts::inc_consumers(&0).is_ok()); + assert_noop!(Accounts::dec_providers(&0), DecRefError::ConsumerRemaining); + }); +} + +#[test] +fn provider_required_to_support_consumer() { + new_test_ext().execute_with(|| { + assert_noop!(Accounts::inc_consumers(&0), IncRefError::NoProviders); + + assert_eq!(Accounts::inc_providers(&0), IncRefStatus::Created); + Accounts::inc_account_nonce(&0); + assert_eq!(Accounts::account_nonce(&0), 1); + + assert_eq!(Accounts::inc_providers(&0), IncRefStatus::Existed); + assert_eq!(Accounts::dec_providers(&0).unwrap(), DecRefStatus::Exists); + assert_eq!(Accounts::account_nonce(&0), 1); + + assert!(Accounts::inc_consumers(&0).is_ok()); + assert_noop!(Accounts::dec_providers(&0), DecRefError::ConsumerRemaining); + + Accounts::dec_consumers(&0); + assert_eq!(Accounts::dec_providers(&0).unwrap(), DecRefStatus::Reaped); + assert_eq!(Accounts::account_nonce(&0), 0); + }); +} diff --git a/frame/assets/Cargo.toml b/frame/assets/Cargo.toml index b62e8bac8ccc6..055976198f884 100644 --- a/frame/assets/Cargo.toml +++ b/frame/assets/Cargo.toml @@ -22,6 +22,7 @@ sp-runtime = { version = "3.0.0", default-features = false, path = "../../primit frame-support = { version = "3.0.0", default-features = false, path = "../support" } # `system` module provides us with all sorts of useful stuff and macros depend on it being around. frame-system = { version = "3.0.0", default-features = false, path = "../system" } +pallet-accounts = { version = "3.0.0", default-features = false, path = "../accounts" } frame-benchmarking = { version = "3.1.0", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] @@ -29,6 +30,7 @@ sp-core = { version = "3.0.0", path = "../../primitives/core" } sp-std = { version = "3.0.0", path = "../../primitives/std" } sp-io = { version = "3.0.0", path = "../../primitives/io" } pallet-balances = { version = "3.0.0", path = "../balances" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } [features] default = ["std"] diff --git a/frame/assets/src/benchmarking.rs b/frame/assets/src/benchmarking.rs index 42f876ff7f3de..13bd185813e76 100644 --- a/frame/assets/src/benchmarking.rs +++ b/frame/assets/src/benchmarking.rs @@ -26,8 +26,12 @@ use frame_system::RawOrigin as SystemOrigin; use frame_benchmarking::{ benchmarks, account, whitelisted_caller, whitelist_account, impl_benchmark_test_suite }; -use frame_support::traits::Get; -use frame_support::{traits::EnsureOrigin, dispatch::UnfilteredDispatchable}; +use frame_support::{ + traits::{ + Get, EnsureOrigin, BasicAccount, + }, + dispatch::UnfilteredDispatchable, +}; use crate::Module as Assets; @@ -193,7 +197,7 @@ benchmarks! { let target_lookup = T::Lookup::unlookup(target.clone()); }: _(SystemOrigin::Signed(caller.clone()), Default::default(), target_lookup, amount) verify { - assert!(frame_system::Module::::account_exists(&caller)); + assert!(T::ReferencedAccount::account_exists(&caller)); assert_last_event::(Event::Transferred(Default::default(), caller, target, amount).into()); } diff --git a/frame/assets/src/lib.rs b/frame/assets/src/lib.rs index e5cb39db2b8e5..bc3a2addfc5fb 100644 --- a/frame/assets/src/lib.rs +++ b/frame/assets/src/lib.rs @@ -140,7 +140,7 @@ use sp_runtime::{ use codec::{Encode, Decode, HasCompact}; use frame_support::{ ensure, - traits::{Currency, ReservableCurrency, BalanceStatus::Reserved}, + traits::{Currency, ReservableCurrency, BalanceStatus::Reserved, ReferencedAccount}, dispatch::{DispatchError, DispatchResult}, }; pub use weights::WeightInfo; @@ -301,6 +301,9 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; + + /// A way to place reference counters on accounts. + type ReferencedAccount: ReferencedAccount; } #[pallet::storage] @@ -1375,11 +1378,11 @@ impl Pallet { ) -> Result { let accounts = d.accounts.checked_add(1).ok_or(Error::::Overflow)?; let is_sufficient = if d.is_sufficient { - frame_system::Module::::inc_sufficients(who); + T::ReferencedAccount::inc_sufficients(who); d.sufficients += 1; true } else { - frame_system::Module::::inc_consumers(who).map_err(|_| Error::::NoProvider)?; + T::ReferencedAccount::inc_consumers(who).map_err(|_| Error::::NoProvider)?; false }; d.accounts = accounts; @@ -1393,9 +1396,9 @@ impl Pallet { ) { if sufficient { d.sufficients = d.sufficients.saturating_sub(1); - frame_system::Module::::dec_sufficients(who); + T::ReferencedAccount::dec_sufficients(who); } else { - frame_system::Module::::dec_consumers(who); + T::ReferencedAccount::dec_consumers(who); } d.accounts = d.accounts.saturating_sub(1); } diff --git a/frame/assets/src/mock.rs b/frame/assets/src/mock.rs index 434a7ccce0757..9f4f4edab3884 100644 --- a/frame/assets/src/mock.rs +++ b/frame/assets/src/mock.rs @@ -34,6 +34,7 @@ construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Assets: pallet_assets::{Module, Call, Storage, Event}, } @@ -60,11 +61,16 @@ impl frame_system::Config for Test { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { @@ -76,7 +82,8 @@ impl pallet_balances::Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); type MaxLocks = (); } @@ -100,6 +107,7 @@ impl Config for Test { type MetadataDepositPerByte = MetadataDepositPerByte; type ApprovalDeposit = ApprovalDeposit; type StringLimit = StringLimit; + type ReferencedAccount = Accounts; type WeightInfo = (); } diff --git a/frame/atomic-swap/Cargo.toml b/frame/atomic-swap/Cargo.toml index a3b62d65e56a3..bb9921b2956e2 100644 --- a/frame/atomic-swap/Cargo.toml +++ b/frame/atomic-swap/Cargo.toml @@ -24,6 +24,7 @@ sp-core = { version = "3.0.0", default-features = false, path = "../../primitive [dev-dependencies] pallet-balances = { version = "3.0.0", path = "../balances" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } [features] default = ["std"] diff --git a/frame/atomic-swap/src/tests.rs b/frame/atomic-swap/src/tests.rs index 977b17f8710e3..0a3fcb4c87860 100644 --- a/frame/atomic-swap/src/tests.rs +++ b/frame/atomic-swap/src/tests.rs @@ -20,6 +20,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, AtomicSwap: pallet_atomic_swap::{Module, Call, Event}, } @@ -48,12 +49,18 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } + +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; +} + parameter_types! { pub const ExistentialDeposit: u64 = 1; } @@ -63,7 +70,8 @@ impl pallet_balances::Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } parameter_types! { diff --git a/frame/aura/src/mock.rs b/frame/aura/src/mock.rs index a5ef12f5935f1..3e15844a18fdb 100644 --- a/frame/aura/src/mock.rs +++ b/frame/aura/src/mock.rs @@ -65,9 +65,7 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/authority-discovery/Cargo.toml b/frame/authority-discovery/Cargo.toml index 85844cf716f03..0d0b24c43b838 100644 --- a/frame/authority-discovery/Cargo.toml +++ b/frame/authority-discovery/Cargo.toml @@ -24,6 +24,7 @@ frame-support = { version = "3.0.0", default-features = false, path = "../suppor frame-system = { version = "3.0.0", default-features = false, path = "../system" } [dev-dependencies] +pallet-accounts = { version = "3.0.0", path = "../accounts" } sp-core = { version = "3.0.0", path = "../../primitives/core" } sp-io = { version = "3.0.0", path = "../../primitives/io" } sp-staking = { version = "3.0.0", default-features = false, path = "../../primitives/staking" } diff --git a/frame/authority-discovery/src/lib.rs b/frame/authority-discovery/src/lib.rs index cc3f41f59ed89..99300bc57c374 100644 --- a/frame/authority-discovery/src/lib.rs +++ b/frame/authority-discovery/src/lib.rs @@ -137,6 +137,7 @@ mod tests { UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Session: pallet_session::{Module, Call, Storage, Event, Config}, AuthorityDiscovery: pallet_authority_discovery::{Module, Call, Config}, } @@ -144,6 +145,13 @@ mod tests { impl Config for Test {} + impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = (); + } + parameter_types! { pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(33); } @@ -158,6 +166,7 @@ mod tests { type ValidatorIdOf = ConvertInto; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type NextSessionRotation = pallet_session::PeriodicSessions; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -195,9 +204,7 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/authorship/src/lib.rs b/frame/authorship/src/lib.rs index 3d89ab24d01cf..cabe5475ed162 100644 --- a/frame/authorship/src/lib.rs +++ b/frame/authorship/src/lib.rs @@ -442,9 +442,7 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/babe/Cargo.toml b/frame/babe/Cargo.toml index 2d7467d82e5b7..73780663a6b04 100644 --- a/frame/babe/Cargo.toml +++ b/frame/babe/Cargo.toml @@ -33,6 +33,7 @@ sp-timestamp = { version = "3.0.0", default-features = false, path = "../../prim log = { version = "0.4.14", default-features = false } [dev-dependencies] +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } pallet-offences = { version = "3.0.0", path = "../offences" } pallet-staking = { version = "3.0.0", path = "../staking" } diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index 412f13f6a2df8..76b483bea5d87 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -52,6 +52,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Historical: pallet_session_historical::{Module}, Offences: pallet_offences::{Module, Call, Storage, Event}, @@ -87,13 +88,18 @@ impl frame_system::Config for Test { type Event = Event; type BlockHashCount = BlockHashCount; type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; +} + impl frame_system::offchain::SendTransactionTypes for Test where Call: From, @@ -118,6 +124,7 @@ impl pallet_session::Config for Test { type SessionHandler = ::KeyTypeIdProviders; type Keys = MockSessionKeys; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -158,7 +165,8 @@ impl pallet_balances::Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -214,6 +222,7 @@ impl pallet_staking::Config for Test { type MinSolutionScoreBump = (); type OffchainSolutionWeightLimit = (); type ElectionProvider = onchain::OnChainSequentialPhragmen; + type ReferencedAccount = Accounts; type WeightInfo = (); } diff --git a/frame/balances/Cargo.toml b/frame/balances/Cargo.toml index 22c4ef0976f5f..4cabf26123fd4 100644 --- a/frame/balances/Cargo.toml +++ b/frame/balances/Cargo.toml @@ -20,12 +20,14 @@ sp-runtime = { version = "3.0.0", default-features = false, path = "../../primit frame-benchmarking = { version = "3.1.0", default-features = false, path = "../benchmarking", optional = true } frame-support = { version = "3.0.0", default-features = false, path = "../support" } frame-system = { version = "3.0.0", default-features = false, path = "../system" } +pallet-accounts = { version = "3.0.0", default-features = false, path = "../accounts" } log = { version = "0.4.14", default-features = false } [dev-dependencies] sp-io = { version = "3.0.0", path = "../../primitives/io" } sp-core = { version = "3.0.0", path = "../../primitives/core" } pallet-transaction-payment = { version = "3.0.0", path = "../transaction-payment" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } [features] default = ["std"] @@ -37,6 +39,7 @@ std = [ "frame-benchmarking/std", "frame-support/std", "frame-system/std", + "pallet-accounts/std", "log/std", ] runtime-benchmarks = ["frame-benchmarking"] diff --git a/frame/balances/src/lib.rs b/frame/balances/src/lib.rs index cc7b6351c2584..308a3fdc17ab4 100644 --- a/frame/balances/src/lib.rs +++ b/frame/balances/src/lib.rs @@ -164,7 +164,7 @@ use frame_support::{ Currency, OnUnbalanced, TryDrop, StoredMap, WithdrawReasons, LockIdentifier, LockableCurrency, ExistenceRequirement, Imbalance, SignedImbalance, ReservableCurrency, Get, ExistenceRequirement::KeepAlive, - ExistenceRequirement::AllowDeath, BalanceStatus as Status, + ExistenceRequirement::AllowDeath, BalanceStatus as Status, ReferencedAccount, } }; #[cfg(feature = "std")] @@ -176,7 +176,6 @@ use sp_runtime::{ MaybeSerializeDeserialize, Saturating, Bounded, StoredMapError, }, }; -use frame_system as system; pub use self::imbalances::{PositiveImbalance, NegativeImbalance}; pub use weights::WeightInfo; @@ -213,6 +212,9 @@ pub mod pallet { /// The maximum number of locks that should exist on an account. /// Not strictly enforced, but used for weight estimation. type MaxLocks: Get; + + /// A way to place reference counters on an account. + type ReferencedAccount: ReferencedAccount; } #[pallet::pallet] @@ -782,12 +784,12 @@ impl, I: 'static> Pallet { if existed { // TODO: use Locks::::hashed_key // https://github.com/paritytech/substrate/issues/4969 - system::Pallet::::dec_consumers(who); + T::ReferencedAccount::dec_consumers(who); } } else { Locks::::insert(who, locks); if !existed { - if system::Pallet::::inc_consumers(who).is_err() { + if T::ReferencedAccount::inc_consumers(who).is_err() { // No providers for the locks. This is impossible under normal circumstances // since the funds that are under the lock will themselves be stored in the // account and therefore will need a reference. @@ -1070,7 +1072,7 @@ impl, I: 'static> Currency for Pallet where // TODO: This is over-conservative. There may now be other providers, and this pallet // may not even be a provider. let allow_death = existence_requirement == ExistenceRequirement::AllowDeath; - let allow_death = allow_death && !system::Pallet::::is_provider_required(transactor); + let allow_death = allow_death && !T::ReferencedAccount::is_provider_required(transactor); ensure!(allow_death || from_account.total() >= ed, Error::::KeepAlive); Ok(()) diff --git a/frame/balances/src/tests.rs b/frame/balances/src/tests.rs index 776cda140efb8..ab19e71e5e3bc 100644 --- a/frame/balances/src/tests.rs +++ b/frame/balances/src/tests.rs @@ -29,7 +29,8 @@ macro_rules! decl_tests { assert_noop, assert_storage_noop, assert_ok, assert_err, StorageValue, traits::{ LockableCurrency, LockIdentifier, WithdrawReasons, - Currency, ReservableCurrency, ExistenceRequirement::AllowDeath + Currency, ReservableCurrency, ExistenceRequirement::AllowDeath, + BasicAccount, ReferencedAccount, } }; use pallet_transaction_payment::{ChargeTransactionPayment, Multiplier}; @@ -55,7 +56,7 @@ macro_rules! decl_tests { } fn last_event() -> Event { - system::Module::::events().pop().expect("Event expected").event + frame_system::Module::::events().pop().expect("Event expected").event } #[test] @@ -264,13 +265,13 @@ macro_rules! decl_tests { .monied(true) .build() .execute_with(|| { - System::inc_account_nonce(&2); + Accounts::inc_account_nonce(&2); assert_eq!(Balances::total_balance(&2), 256 * 20); assert_ok!(Balances::reserve(&2, 256 * 19 + 1)); // account 2 becomes mostly reserved assert_eq!(Balances::free_balance(2), 255); // "free" account deleted." assert_eq!(Balances::total_balance(&2), 256 * 20); // reserve still exists. - assert_eq!(System::account_nonce(&2), 1); + assert_eq!(Accounts::account_nonce(&2), 1); // account 4 tries to take index 1 for account 5. assert_ok!(Balances::transfer(Some(4).into(), 5, 256 * 1 + 0x69)); @@ -279,7 +280,7 @@ macro_rules! decl_tests { assert!(Balances::slash(&2, 256 * 19 + 2).1.is_zero()); // account 2 gets slashed // "reserve" account reduced to 255 (below ED) so account deleted assert_eq!(Balances::total_balance(&2), 0); - assert_eq!(System::account_nonce(&2), 0); // nonce zero + assert_eq!(Accounts::account_nonce(&2), 0); // nonce zero // account 4 tries to take index 1 again for account 6. assert_ok!(Balances::transfer(Some(4).into(), 6, 256 * 1 + 0x69)); @@ -304,14 +305,14 @@ macro_rules! decl_tests { .monied(true) .build() .execute_with(|| { - System::inc_account_nonce(&2); - assert_eq!(System::account_nonce(&2), 1); + Accounts::inc_account_nonce(&2); + assert_eq!(Accounts::account_nonce(&2), 1); assert_eq!(Balances::total_balance(&2), 2000); // index 1 (account 2) becomes zombie assert_ok!(Balances::transfer(Some(2).into(), 5, 1901)); assert_eq!(Balances::total_balance(&2), 0); assert_eq!(Balances::total_balance(&5), 1901); - assert_eq!(System::account_nonce(&2), 0); + assert_eq!(Accounts::account_nonce(&2), 0); }); } @@ -721,7 +722,7 @@ macro_rules! decl_tests { assert_eq!( events(), [ - Event::frame_system(system::Event::NewAccount(1)), + Event::pallet_accounts(pallet_accounts::Event::NewAccount(1)), Event::pallet_balances(crate::Event::Endowed(1, 100)), Event::pallet_balances(crate::Event::BalanceSet(1, 100, 0)), ] @@ -732,7 +733,7 @@ macro_rules! decl_tests { assert_eq!( events(), [ - Event::frame_system(system::Event::KilledAccount(1)), + Event::pallet_accounts(pallet_accounts::Event::KilledAccount(1)), Event::pallet_balances(crate::Event::DustLost(1, 99)), ] ); @@ -750,7 +751,7 @@ macro_rules! decl_tests { assert_eq!( events(), [ - Event::frame_system(system::Event::NewAccount(1)), + Event::pallet_accounts(pallet_accounts::Event::NewAccount(1)), Event::pallet_balances(crate::Event::Endowed(1, 100)), Event::pallet_balances(crate::Event::BalanceSet(1, 100, 0)), ] @@ -761,7 +762,7 @@ macro_rules! decl_tests { assert_eq!( events(), [ - Event::frame_system(system::Event::KilledAccount(1)) + Event::pallet_accounts(pallet_accounts::Event::KilledAccount(1)) ] ); }); @@ -780,87 +781,87 @@ macro_rules! decl_tests { // Slashed completed in full assert_eq!(Balances::slash(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Slash will kill account because not enough balance left. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); // Slashed completed in full assert_eq!(Balances::slash(&1, 950), (NegativeImbalance::new(950), 0)); // Account is killed - assert!(!System::account_exists(&1)); + assert!(!Accounts::account_exists(&1)); // SCENARIO: Over-slash will kill account, and report missing slash amount. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); // Slashed full free_balance, and reports 300 not slashed assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1000), 300)); // Account is dead - assert!(!System::account_exists(&1)); + assert!(!Accounts::account_exists(&1)); // SCENARIO: Over-slash can take from reserved, but keep alive. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 400)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1300), 0)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Over-slash can take from reserved, and kill. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 350)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1300), 0)); // Account is dead because 50 reserved balance is not enough to keep alive - assert!(!System::account_exists(&1)); + assert!(!Accounts::account_exists(&1)); // SCENARIO: Over-slash can take as much as possible from reserved, kill, and report missing amount. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 250)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1250), 50)); // Account is super dead - assert!(!System::account_exists(&1)); + assert!(!Accounts::account_exists(&1)); /* User will now have a reference counter on them, keeping them alive in these scenarios */ // SCENARIO: Slash would not kill account. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); - assert_ok!(System::inc_consumers(&1)); // <-- Reference counter added here is enough for all tests + assert_ok!(Accounts::inc_consumers(&1)); // <-- Reference counter added here is enough for all tests // Slashed completed in full assert_eq!(Balances::slash(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Slash will take as much as possible without killing account. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); // Slashed completed in full assert_eq!(Balances::slash(&1, 950), (NegativeImbalance::new(900), 50)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Over-slash will not kill account, and report missing slash amount. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 0)); // Slashed full free_balance minus ED, and reports 400 not slashed assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(900), 400)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Over-slash can take from reserved, but keep alive. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 400)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1300), 0)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Over-slash can take from reserved, but keep alive. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 350)); // Slashed full free_balance and 250 of reserved balance to leave ED assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1250), 50)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Over-slash can take as much as possible from reserved and report missing amount. assert_ok!(Balances::set_balance(Origin::root(), 1, 1_000, 250)); // Slashed full free_balance and 300 of reserved balance assert_eq!(Balances::slash(&1, 1_300), (NegativeImbalance::new(1150), 150)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // Slash on non-existent account is okay. assert_eq!(Balances::slash(&12345, 1_300), (NegativeImbalance::new(0), 1300)); @@ -880,59 +881,59 @@ macro_rules! decl_tests { // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Slash would kill account. assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 1_000), (NegativeImbalance::new(1_000), 0)); // Account is dead - assert!(!System::account_exists(&1)); + assert!(!Accounts::account_exists(&1)); // SCENARIO: Over-slash would kill account, and reports left over slash. assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 1_300), (NegativeImbalance::new(1_000), 300)); // Account is dead - assert!(!System::account_exists(&1)); + assert!(!Accounts::account_exists(&1)); // SCENARIO: Over-slash does not take from free balance. assert_ok!(Balances::set_balance(Origin::root(), 1, 300, 1_000)); // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 1_300), (NegativeImbalance::new(1_000), 300)); // Account is alive because of free balance - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); /* User has a reference counter, so they cannot die */ // SCENARIO: Slash would not kill account. assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); - assert_ok!(System::inc_consumers(&1)); // <-- Reference counter added here is enough for all tests + assert_ok!(Accounts::inc_consumers(&1)); // <-- Reference counter added here is enough for all tests // Slashed completed in full assert_eq!(Balances::slash_reserved(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Slash as much as possible without killing. assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); // Slashed as much as possible assert_eq!(Balances::slash_reserved(&1, 1_000), (NegativeImbalance::new(950), 50)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Over-slash reports correctly, where reserved is needed to keep alive. assert_ok!(Balances::set_balance(Origin::root(), 1, 50, 1_000)); // Slashed as much as possible assert_eq!(Balances::slash_reserved(&1, 1_300), (NegativeImbalance::new(950), 350)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // SCENARIO: Over-slash reports correctly, where full reserved is removed. assert_ok!(Balances::set_balance(Origin::root(), 1, 200, 1_000)); // Slashed as much as possible assert_eq!(Balances::slash_reserved(&1, 1_300), (NegativeImbalance::new(1_000), 300)); // Account is still alive - assert!(System::account_exists(&1)); + assert!(Accounts::account_exists(&1)); // Slash on non-existent account is okay. assert_eq!(Balances::slash_reserved(&12345, 1_300), (NegativeImbalance::new(0), 1300)); diff --git a/frame/balances/src/tests_composite.rs b/frame/balances/src/tests_composite.rs index 14dfd0c4b33d6..fbec4ae126ef9 100644 --- a/frame/balances/src/tests_composite.rs +++ b/frame/balances/src/tests_composite.rs @@ -42,6 +42,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, } ); @@ -70,11 +71,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = super::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = super::AccountData; } parameter_types! { pub const TransactionByteFee: u64 = 1; @@ -91,7 +96,8 @@ impl Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Pallet; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type MaxLocks = (); type WeightInfo = (); } diff --git a/frame/balances/src/tests_local.rs b/frame/balances/src/tests_local.rs index 02088e88b98ec..2367482b65917 100644 --- a/frame/balances/src/tests_local.rs +++ b/frame/balances/src/tests_local.rs @@ -44,6 +44,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, } ); @@ -72,12 +73,16 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = (); +} parameter_types! { pub const TransactionByteFee: u64 = 1; } @@ -97,11 +102,12 @@ impl Config for Test { type ExistentialDeposit = ExistentialDeposit; type AccountStore = StorageMapShim< super::Account, - system::Provider, + pallet_accounts::Provider, u64, super::AccountData, >; type MaxLocks = MaxLocks; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -168,7 +174,7 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { assert_eq!( events(), [ - Event::frame_system(system::Event::NewAccount(1)), + Event::pallet_accounts(pallet_accounts::Event::NewAccount(1)), Event::pallet_balances(crate::Event::Endowed(1, 100)), Event::pallet_balances(crate::Event::BalanceSet(1, 100, 0)), ] @@ -184,7 +190,7 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { assert_eq!( events(), [ - Event::frame_system(system::Event::KilledAccount(1)), + Event::pallet_accounts(pallet_accounts::Event::KilledAccount(1)), Event::pallet_balances(crate::Event::DustLost(1, 1)), ] ); diff --git a/frame/balances/src/tests_reentrancy.rs b/frame/balances/src/tests_reentrancy.rs index 020c514b6317c..5044447d8edc0 100644 --- a/frame/balances/src/tests_reentrancy.rs +++ b/frame/balances/src/tests_reentrancy.rs @@ -47,7 +47,7 @@ type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; fn last_event() -> Event { - system::Module::::events().pop().expect("Event expected").event + frame_system::Module::::events().pop().expect("Event expected").event } frame_support::construct_runtime!( @@ -57,6 +57,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, } ); @@ -85,12 +86,16 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; +} parameter_types! { pub const TransactionByteFee: u64 = 1; } @@ -117,12 +122,13 @@ impl Config for Test { type ExistentialDeposit = ExistentialDeposit; type AccountStore = StorageMapShim< super::Account, - system::Provider, + pallet_accounts::Provider, u64, super::AccountData, >; type MaxLocks = MaxLocks; type WeightInfo = (); + type ReferencedAccount = Accounts; } pub struct ExtBuilder { diff --git a/frame/benchmarking/src/lib.rs b/frame/benchmarking/src/lib.rs index c2f60a5e13c41..ff52b461cab38 100644 --- a/frame/benchmarking/src/lib.rs +++ b/frame/benchmarking/src/lib.rs @@ -712,8 +712,11 @@ macro_rules! impl_benchmark { // Add whitelist to DB including whitelisted caller let mut whitelist = whitelist.to_vec(); let whitelisted_caller_key = - as $crate::frame_support::storage::StorageMap<_,_>>::hashed_key_for( - $crate::whitelisted_caller::() + < + ::AccountStorage as + $crate::frame_support::traits::BasicAccount + >::hashed_key_for( + &$crate::whitelisted_caller::() ); whitelist.push(whitelisted_caller_key.into()); $crate::benchmarking::set_whitelist(whitelist); diff --git a/frame/benchmarking/src/tests.rs b/frame/benchmarking/src/tests.rs index 8431f3e46c277..e0497e40a75b1 100644 --- a/frame/benchmarking/src/tests.rs +++ b/frame/benchmarking/src/tests.rs @@ -99,9 +99,7 @@ impl frame_system::Config for Test { type BlockHashCount = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/benchmarking/src/utils.rs b/frame/benchmarking/src/utils.rs index 1574e47454b59..100886dc339ae 100644 --- a/frame/benchmarking/src/utils.rs +++ b/frame/benchmarking/src/utils.rs @@ -225,7 +225,12 @@ pub fn whitelisted_caller() -> AccountId { macro_rules! whitelist_account { ($acc:ident) => { frame_benchmarking::benchmarking::add_to_whitelist( - frame_system::Account::::hashed_key_for(&$acc).into() + < + ::AccountStorage as + $crate::frame_support::traits::BasicAccount + >::hashed_key_for( + &$crate::whitelisted_caller::() + ).into() ); } } diff --git a/frame/bounties/Cargo.toml b/frame/bounties/Cargo.toml index ff1a3a6807098..f96e30db2658c 100644 --- a/frame/bounties/Cargo.toml +++ b/frame/bounties/Cargo.toml @@ -28,6 +28,7 @@ sp-io ={ version = "3.0.0", path = "../../primitives/io" } sp-core = { version = "3.0.0", path = "../../primitives/core" } sp-storage = { version = "3.0.0", path = "../../primitives/storage" } pallet-balances = { version = "3.0.0", path = "../balances" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } [features] default = ["std"] diff --git a/frame/bounties/src/tests.rs b/frame/bounties/src/tests.rs index cbff502daa65e..a3cfb8cd0e55c 100644 --- a/frame/bounties/src/tests.rs +++ b/frame/bounties/src/tests.rs @@ -44,6 +44,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Bounties: pallet_bounties::{Module, Call, Storage, Event}, Treasury: pallet_treasury::{Module, Call, Storage, Config, Event}, @@ -75,11 +76,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub const ExistentialDeposit: u64 = 1; @@ -90,7 +95,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } thread_local! { diff --git a/frame/collective/src/lib.rs b/frame/collective/src/lib.rs index 6d9066bca241c..818da8b87aab9 100644 --- a/frame/collective/src/lib.rs +++ b/frame/collective/src/lib.rs @@ -999,9 +999,7 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/contracts/Cargo.toml b/frame/contracts/Cargo.toml index 018a8a5df672e..f21ec2d4c512c 100644 --- a/frame/contracts/Cargo.toml +++ b/frame/contracts/Cargo.toml @@ -37,6 +37,7 @@ rand_pcg = { version = "0.2.1", optional = true } [dev-dependencies] assert_matches = "1.3.0" hex-literal = "0.3.1" +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } pallet-timestamp = { version = "3.0.0", path = "../timestamp" } pallet-randomness-collective-flip = { version = "3.0.0", path = "../randomness-collective-flip" } diff --git a/frame/contracts/src/tests.rs b/frame/contracts/src/tests.rs index c17434300d454..37df766c636f1 100644 --- a/frame/contracts/src/tests.rs +++ b/frame/contracts/src/tests.rs @@ -58,6 +58,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Randomness: pallet_randomness_collective_flip::{Module, Call, Storage}, @@ -216,11 +217,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } impl pallet_balances::Config for Test { type MaxLocks = (); @@ -228,7 +233,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } parameter_types! { @@ -473,7 +479,7 @@ fn instantiate_and_call_and_deposit_event() { assert_eq!(System::events(), vec![ EventRecord { phase: Phase::Initialization, - event: Event::frame_system(frame_system::Event::NewAccount(ALICE.clone())), + event: Event::pallet_accounts(pallet_accounts::Event::NewAccount(ALICE.clone())), topics: vec![], }, EventRecord { @@ -485,7 +491,7 @@ fn instantiate_and_call_and_deposit_event() { }, EventRecord { phase: Phase::Initialization, - event: Event::frame_system(frame_system::Event::NewAccount(addr.clone())), + event: Event::pallet_accounts(pallet_accounts::Event::NewAccount(addr.clone())), topics: vec![], }, EventRecord { @@ -1202,7 +1208,7 @@ fn restoration( let mut events = vec![ EventRecord { phase: Phase::Initialization, - event: Event::frame_system(frame_system::Event::NewAccount(ALICE)), + event: Event::pallet_accounts(pallet_accounts::Event::NewAccount(ALICE)), topics: vec![], }, EventRecord { @@ -1214,7 +1220,7 @@ fn restoration( }, EventRecord { phase: Phase::Initialization, - event: Event::frame_system(frame_system::Event::NewAccount(addr_bob.clone())), + event: Event::pallet_accounts(pallet_accounts::Event::NewAccount(addr_bob.clone())), topics: vec![], }, EventRecord { @@ -1263,7 +1269,7 @@ fn restoration( events.extend([ EventRecord { phase: Phase::Initialization, - event: Event::frame_system(frame_system::Event::NewAccount(addr_dummy.clone())), + event: Event::pallet_accounts(pallet_accounts::Event::NewAccount(addr_dummy.clone())), topics: vec![], }, EventRecord { @@ -1415,7 +1421,7 @@ fn restoration( }, EventRecord { phase: Phase::Initialization, - event: Event::frame_system(frame_system::Event::NewAccount(CHARLIE)), + event: Event::pallet_accounts(pallet_accounts::Event::NewAccount(CHARLIE)), topics: vec![], }, EventRecord { @@ -1425,7 +1431,7 @@ fn restoration( }, EventRecord { phase: Phase::Initialization, - event: Event::frame_system(frame_system::Event::NewAccount(addr_django.clone())), + event: Event::pallet_accounts(pallet_accounts::Event::NewAccount(addr_django.clone())), topics: vec![], }, EventRecord { @@ -1488,7 +1494,7 @@ fn restoration( }, EventRecord { phase: Phase::Initialization, - event: Event::frame_system(system::Event::KilledAccount(addr_django.clone())), + event: Event::pallet_accounts(pallet_accounts::Event::KilledAccount(addr_django.clone())), topics: vec![], }, EventRecord { @@ -1721,8 +1727,8 @@ fn self_destruct_works() { pretty_assertions::assert_eq!(System::events(), vec![ EventRecord { phase: Phase::Initialization, - event: Event::frame_system( - frame_system::Event::KilledAccount(addr.clone()) + event: Event::pallet_accounts( + pallet_accounts::Event::KilledAccount(addr.clone()) ), topics: vec![], }, diff --git a/frame/democracy/Cargo.toml b/frame/democracy/Cargo.toml index f9b0d035b089d..ceb6b695301cc 100644 --- a/frame/democracy/Cargo.toml +++ b/frame/democracy/Cargo.toml @@ -24,6 +24,7 @@ frame-system = { version = "3.0.0", default-features = false, path = "../system" [dev-dependencies] sp-core = { version = "3.0.0", path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } pallet-scheduler = { version = "3.0.0", path = "../scheduler" } sp-storage = { version = "3.0.0", path = "../../primitives/storage" } diff --git a/frame/democracy/src/tests.rs b/frame/democracy/src/tests.rs index 291cfa33b5224..6fc928700b52c 100644 --- a/frame/democracy/src/tests.rs +++ b/frame/democracy/src/tests.rs @@ -61,6 +61,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Scheduler: pallet_scheduler::{Module, Call, Storage, Config, Event}, Democracy: pallet_democracy::{Module, Call, Storage, Config, Event}, @@ -98,11 +99,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block; @@ -126,7 +131,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } parameter_types! { diff --git a/frame/election-provider-multi-phase/Cargo.toml b/frame/election-provider-multi-phase/Cargo.toml index 1d63f9df40a25..4e9b3a0efc903 100644 --- a/frame/election-provider-multi-phase/Cargo.toml +++ b/frame/election-provider-multi-phase/Cargo.toml @@ -44,6 +44,7 @@ sp-tracing = { version = "3.0.0", path = "../../primitives/tracing" } sp-election-providers = { version = "3.0.0", features = ["runtime-benchmarks"], path = "../../primitives/election-providers" } pallet-balances = { version = "3.0.0", path = "../balances" } frame-benchmarking = { path = "../benchmarking" , version = "3.1.0"} +pallet-accounts = { path = "../accounts" , version = "3.0.0"} [features] default = ["std"] diff --git a/frame/election-provider-multi-phase/src/mock.rs b/frame/election-provider-multi-phase/src/mock.rs index e7a2924fd2aa6..636f27f294902 100644 --- a/frame/election-provider-multi-phase/src/mock.rs +++ b/frame/election-provider-multi-phase/src/mock.rs @@ -55,6 +55,7 @@ frame_support::construct_runtime!( System: frame_system::{Module, Call, Event, Config}, Balances: pallet_balances::{Module, Call, Event, Config}, MultiPhase: multi_phase::{Module, Call, Event}, + Accounts: pallet_accounts::{Module, Call, Event,}, } ); @@ -155,12 +156,15 @@ impl frame_system::Config for Runtime { type BlockWeights = BlockWeights; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Runtime { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } - const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); parameter_types! { pub const ExistentialDeposit: u64 = 1; @@ -173,7 +177,8 @@ impl pallet_balances::Config for Runtime { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type MaxLocks = (); type WeightInfo = (); } diff --git a/frame/elections-phragmen/Cargo.toml b/frame/elections-phragmen/Cargo.toml index 89723cb85fbe1..1a28850b16a7d 100644 --- a/frame/elections-phragmen/Cargo.toml +++ b/frame/elections-phragmen/Cargo.toml @@ -26,6 +26,7 @@ log = { version = "0.4.14", default-features = false } [dev-dependencies] sp-io = { version = "3.0.0", path = "../../primitives/io" } hex-literal = "0.3.1" +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } sp-core = { version = "3.0.0", path = "../../primitives/core" } substrate-test-utils = { version = "3.0.0", path = "../../test-utils" } diff --git a/frame/elections-phragmen/src/lib.rs b/frame/elections-phragmen/src/lib.rs index 779570ca633ee..69a46dd3bb76a 100644 --- a/frame/elections-phragmen/src/lib.rs +++ b/frame/elections-phragmen/src/lib.rs @@ -1080,11 +1080,16 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); - type SS58Prefix = (); + type SS58Prefix = (); + type AccountStorage = Accounts; + } + + impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { @@ -1096,7 +1101,8 @@ mod tests { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = frame_system::Module; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type MaxLocks = (); type WeightInfo = (); } @@ -1188,6 +1194,7 @@ mod tests { UncheckedExtrinsic = UncheckedExtrinsic { System: frame_system::{Module, Call, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Event, Config}, Elections: elections_phragmen::{Module, Call, Event, Config}, } diff --git a/frame/elections/Cargo.toml b/frame/elections/Cargo.toml index ac3c709300f51..596ef730811be 100644 --- a/frame/elections/Cargo.toml +++ b/frame/elections/Cargo.toml @@ -24,6 +24,7 @@ frame-system = { version = "3.0.0", default-features = false, path = "../system" [dev-dependencies] hex-literal = "0.3.1" +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/elections/src/mock.rs b/frame/elections/src/mock.rs index 31d3f5a1c28a5..2a30bbee9f1bd 100644 --- a/frame/elections/src/mock.rs +++ b/frame/elections/src/mock.rs @@ -53,11 +53,16 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { @@ -69,7 +74,8 @@ impl pallet_balances::Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -136,6 +142,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic { System: system::{Module, Call, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Event, Config}, Elections: elections::{Module, Call, Event, Config}, } diff --git a/frame/example-offchain-worker/src/tests.rs b/frame/example-offchain-worker/src/tests.rs index 7707e7d61e629..084b2796382bc 100644 --- a/frame/example-offchain-worker/src/tests.rs +++ b/frame/example-offchain-worker/src/tests.rs @@ -77,9 +77,7 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/example-parallel/src/tests.rs b/frame/example-parallel/src/tests.rs index da2892c67d42a..08fa6bb7883ba 100644 --- a/frame/example-parallel/src/tests.rs +++ b/frame/example-parallel/src/tests.rs @@ -61,9 +61,7 @@ impl frame_system::Config for Test { type BlockWeights = (); type BlockLength = (); type Version = (); - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/example/Cargo.toml b/frame/example/Cargo.toml index de741294b9c16..298ac3a967ef6 100644 --- a/frame/example/Cargo.toml +++ b/frame/example/Cargo.toml @@ -25,7 +25,8 @@ sp-io = { version = "3.0.0", default-features = false, path = "../../primitives/ frame-benchmarking = { version = "3.1.0", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] -sp-core = { version = "3.0.0", path = "../../primitives/core", default-features = false } +sp-core = { version = "3.0.0", default-features = false, path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", default-features = false, path = "../accounts" } [features] default = ["std"] diff --git a/frame/example/src/lib.rs b/frame/example/src/lib.rs index 7a537f4522abf..1b12d028023ce 100644 --- a/frame/example/src/lib.rs +++ b/frame/example/src/lib.rs @@ -759,6 +759,7 @@ mod tests { UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Example: pallet_example::{Module, Call, Storage, Config, Event}, } @@ -787,12 +788,18 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } + + impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; + } + parameter_types! { pub const ExistentialDeposit: u64 = 1; } @@ -802,7 +809,8 @@ mod tests { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } impl Config for Test { diff --git a/frame/executive/Cargo.toml b/frame/executive/Cargo.toml index 6a0042308736e..737c8ebcc907f 100644 --- a/frame/executive/Cargo.toml +++ b/frame/executive/Cargo.toml @@ -27,8 +27,9 @@ sp-core = { version = "3.0.0", default-features = false, path = "../../primitive hex-literal = "0.3.1" sp-core = { version = "3.0.0", path = "../../primitives/core" } sp-io ={ version = "3.0.0", path = "../../primitives/io" } -pallet-indices = { version = "3.0.0", path = "../indices" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } +pallet-indices = { version = "3.0.0", path = "../indices" } pallet-transaction-payment = { version = "3.0.0", path = "../transaction-payment" } sp-version = { version = "3.0.0", path = "../../primitives/version" } diff --git a/frame/executive/src/lib.rs b/frame/executive/src/lib.rs index 9485e75bbdecf..68b2d324556f6 100644 --- a/frame/executive/src/lib.rs +++ b/frame/executive/src/lib.rs @@ -598,6 +598,7 @@ mod tests { UncheckedExtrinsic = TestUncheckedExtrinsic { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Custom: custom::{Module, Call, ValidateUnsigned}, } @@ -634,13 +635,18 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = RuntimeVersion; type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } + impl pallet_accounts::Config for Runtime { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; + } + type Balance = u64; parameter_types! { pub const ExistentialDeposit: Balance = 1; @@ -650,7 +656,8 @@ mod tests { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type MaxLocks = (); type WeightInfo = (); } @@ -769,7 +776,7 @@ mod tests { header: Header { parent_hash: [69u8; 32].into(), number: 1, - state_root: hex!("2c01e6f33d595793119823478b45b36978a8f65a731b5ae3fdfb6330b4cd4b11").into(), + state_root: hex!("b7d31cf177f0cc54bbc5c437d63123829643b2ac63895df9edc151b6ef446874").into(), extrinsics_root: hex!("03170a2e7597b7b7e3d84c05391d139a62b157e78786d8c082f29dcf4c111314").into(), digest: Digest { logs: vec![], }, }, diff --git a/frame/gilt/Cargo.toml b/frame/gilt/Cargo.toml index 4df0dc49aaf93..42f5b1c12fbbb 100644 --- a/frame/gilt/Cargo.toml +++ b/frame/gilt/Cargo.toml @@ -25,6 +25,7 @@ frame-system = { version = "3.0.0", default-features = false, path = "../system" [dev-dependencies] sp-io = { version = "3.0.0", path = "../../primitives/io" } sp-core = { version = "3.0.0", path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/gilt/src/mock.rs b/frame/gilt/src/mock.rs index ca4ccaff73c58..99f0021dac293 100644 --- a/frame/gilt/src/mock.rs +++ b/frame/gilt/src/mock.rs @@ -37,6 +37,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Config, Storage, Event}, Gilt: pallet_gilt::{Module, Call, Config, Storage, Event}, } @@ -65,11 +66,16 @@ impl frame_system::Config for Test { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = SS58Prefix; + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { @@ -81,7 +87,8 @@ impl pallet_balances::Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); type MaxLocks = (); } diff --git a/frame/grandpa/Cargo.toml b/frame/grandpa/Cargo.toml index 2bf7306f58e15..d3c593d49f062 100644 --- a/frame/grandpa/Cargo.toml +++ b/frame/grandpa/Cargo.toml @@ -34,6 +34,7 @@ frame-benchmarking = { version = "3.1.0", path = "../benchmarking" } grandpa = { package = "finality-grandpa", version = "0.14.0", features = ["derive-codec"] } sp-io = { version = "3.0.0", path = "../../primitives/io" } sp-keyring = { version = "3.0.0", path = "../../primitives/keyring" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } pallet-offences = { version = "3.0.0", path = "../offences" } pallet-staking = { version = "3.0.0", path = "../staking" } diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index 0a24a2344547e..1f74e9efb7a95 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -52,6 +52,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Staking: pallet_staking::{Module, Call, Config, Storage, Event, ValidateUnsigned}, @@ -92,11 +93,16 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } impl frame_system::offchain::SendTransactionTypes for Test @@ -125,6 +131,7 @@ impl pallet_session::Config for Test { type Keys = TestSessionKeys; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type WeightInfo = (); + type ReferencedAccount = Accounts; } impl pallet_session::historical::Config for Test { @@ -153,7 +160,8 @@ impl pallet_balances::Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -221,6 +229,7 @@ impl pallet_staking::Config for Test { type OffchainSolutionWeightLimit = (); type ElectionProvider = onchain::OnChainSequentialPhragmen; type WeightInfo = (); + type ReferencedAccount = Accounts; } parameter_types! { diff --git a/frame/identity/Cargo.toml b/frame/identity/Cargo.toml index 08109fda2584c..a3a215db5830f 100644 --- a/frame/identity/Cargo.toml +++ b/frame/identity/Cargo.toml @@ -25,6 +25,7 @@ frame-system = { version = "3.0.0", default-features = false, path = "../system" [dev-dependencies] sp-core = { version = "3.0.0", path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/identity/src/tests.rs b/frame/identity/src/tests.rs index 230079a21ea0d..5f0afc18781e7 100644 --- a/frame/identity/src/tests.rs +++ b/frame/identity/src/tests.rs @@ -38,6 +38,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Identity: pallet_identity::{Module, Call, Storage, Event}, } @@ -66,11 +67,15 @@ impl frame_system::Config for Test { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub const ExistentialDeposit: u64 = 1; @@ -80,7 +85,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type MaxLocks = (); type WeightInfo = (); } diff --git a/frame/im-online/Cargo.toml b/frame/im-online/Cargo.toml index 4c5b4a8863bcd..5a5bf27aba966 100644 --- a/frame/im-online/Cargo.toml +++ b/frame/im-online/Cargo.toml @@ -29,6 +29,7 @@ log = { version = "0.4.14", default-features = false } frame-benchmarking = { version = "3.1.0", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-session = { version = "3.0.0", path = "../session" } [features] diff --git a/frame/im-online/src/mock.rs b/frame/im-online/src/mock.rs index 1b80f5b12dedb..07b06352094dc 100644 --- a/frame/im-online/src/mock.rs +++ b/frame/im-online/src/mock.rs @@ -41,6 +41,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Session: pallet_session::{Module, Call, Storage, Event, Config}, ImOnline: imonline::{Module, Call, Storage, Config, Event}, Historical: pallet_session_historical::{Module}, @@ -131,13 +132,18 @@ impl frame_system::Config for Runtime { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } +impl pallet_accounts::Config for Runtime { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = (); +} + parameter_types! { pub const Period: u64 = 1; pub const Offset: u64 = 0; @@ -158,6 +164,7 @@ impl pallet_session::Config for Runtime { type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type NextSessionRotation = pallet_session::PeriodicSessions; type WeightInfo = (); + type ReferencedAccount = Accounts; } impl pallet_session::historical::Config for Runtime { diff --git a/frame/indices/Cargo.toml b/frame/indices/Cargo.toml index ce9b2053ff184..b82f4c3b5f169 100644 --- a/frame/indices/Cargo.toml +++ b/frame/indices/Cargo.toml @@ -26,6 +26,7 @@ frame-system = { version = "3.0.0", default-features = false, path = "../system" frame-benchmarking = { version = "3.1.0", default-features = false, path = "../benchmarking", optional = true } [dev-dependencies] +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/indices/src/mock.rs b/frame/indices/src/mock.rs index 06c73b1a9bc27..4cd742f3d1041 100644 --- a/frame/indices/src/mock.rs +++ b/frame/indices/src/mock.rs @@ -34,6 +34,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Indices: pallet_indices::{Module, Call, Storage, Config, Event}, } @@ -63,11 +64,16 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { @@ -80,7 +86,8 @@ impl pallet_balances::Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } diff --git a/frame/lottery/Cargo.toml b/frame/lottery/Cargo.toml index 73de239a4d801..aa7695ff42cbe 100644 --- a/frame/lottery/Cargo.toml +++ b/frame/lottery/Cargo.toml @@ -23,6 +23,7 @@ frame-benchmarking = { version = "3.1.0", default-features = false, path = "../b [dev-dependencies] frame-support-test = { version = "3.0.0", path = "../support/test" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } sp-core = { version = "3.0.0", path = "../../primitives/core" } sp-io = { version = "3.0.0", path = "../../primitives/io" } diff --git a/frame/lottery/src/mock.rs b/frame/lottery/src/mock.rs index 44691427c8e59..4aaef97b93f63 100644 --- a/frame/lottery/src/mock.rs +++ b/frame/lottery/src/mock.rs @@ -43,6 +43,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Lottery: pallet_lottery::{Module, Call, Storage, Event}, } @@ -73,13 +74,18 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; +} + parameter_types! { pub const ExistentialDeposit: u64 = 1; } @@ -90,7 +96,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } diff --git a/frame/membership/src/lib.rs b/frame/membership/src/lib.rs index f080938095445..043c2a1e7739a 100644 --- a/frame/membership/src/lib.rs +++ b/frame/membership/src/lib.rs @@ -323,9 +323,7 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/merkle-mountain-range/src/mock.rs b/frame/merkle-mountain-range/src/mock.rs index 0adb0294d5080..1ff4e122a74c9 100644 --- a/frame/merkle-mountain-range/src/mock.rs +++ b/frame/merkle-mountain-range/src/mock.rs @@ -66,9 +66,7 @@ impl frame_system::Config for Test { type BlockLength = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/multisig/Cargo.toml b/frame/multisig/Cargo.toml index e48f80567f67a..2d5a4f643719d 100644 --- a/frame/multisig/Cargo.toml +++ b/frame/multisig/Cargo.toml @@ -26,6 +26,7 @@ frame-benchmarking = { version = "3.1.0", default-features = false, path = "../b [dev-dependencies] sp-core = { version = "3.0.0", path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/multisig/src/tests.rs b/frame/multisig/src/tests.rs index a3f47a26e6422..ea7eb4180aab3 100644 --- a/frame/multisig/src/tests.rs +++ b/frame/multisig/src/tests.rs @@ -38,6 +38,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Multisig: pallet_multisig::{Module, Call, Storage, Event}, } @@ -66,11 +67,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub const ExistentialDeposit: u64 = 1; @@ -81,7 +86,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } parameter_types! { diff --git a/frame/nicks/Cargo.toml b/frame/nicks/Cargo.toml index 6c8b609b401ca..88c99119f0781 100644 --- a/frame/nicks/Cargo.toml +++ b/frame/nicks/Cargo.toml @@ -23,6 +23,7 @@ frame-system = { version = "3.0.0", default-features = false, path = "../system" [dev-dependencies] sp-core = { version = "3.0.0", path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/nicks/src/lib.rs b/frame/nicks/src/lib.rs index 681a45626fbca..63334a8f13760 100644 --- a/frame/nicks/src/lib.rs +++ b/frame/nicks/src/lib.rs @@ -258,6 +258,7 @@ mod tests { UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Nicks: pallet_nicks::{Module, Call, Storage, Event}, } @@ -286,12 +287,16 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } + impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; + } parameter_types! { pub const ExistentialDeposit: u64 = 1; } @@ -301,7 +306,8 @@ mod tests { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } parameter_types! { diff --git a/frame/node-authorization/src/lib.rs b/frame/node-authorization/src/lib.rs index 090be28492630..4f4bd5c69eef5 100644 --- a/frame/node-authorization/src/lib.rs +++ b/frame/node-authorization/src/lib.rs @@ -481,9 +481,7 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/offences/benchmarking/Cargo.toml b/frame/offences/benchmarking/Cargo.toml index 6be2787734a4f..2e8a00f533492 100644 --- a/frame/offences/benchmarking/Cargo.toml +++ b/frame/offences/benchmarking/Cargo.toml @@ -18,6 +18,7 @@ frame-benchmarking = { version = "3.1.0", default-features = false, path = "../. frame-support = { version = "3.0.0", default-features = false, path = "../../support" } frame-system = { version = "3.0.0", default-features = false, path = "../../system" } pallet-babe = { version = "3.0.0", default-features = false, path = "../../babe" } +pallet-accounts = { version = "3.0.0", default-features = false, path = "../../accounts" } pallet-balances = { version = "3.0.0", default-features = false, path = "../../balances" } pallet-grandpa = { version = "3.0.0", default-features = false, path = "../../grandpa" } pallet-im-online = { version = "3.0.0", default-features = false, path = "../../im-online" } diff --git a/frame/offences/benchmarking/src/lib.rs b/frame/offences/benchmarking/src/lib.rs index 0ceebaecd91ae..99d81c5c4161d 100644 --- a/frame/offences/benchmarking/src/lib.rs +++ b/frame/offences/benchmarking/src/lib.rs @@ -281,13 +281,20 @@ benchmarks! { StakingEvent::::Slash(stash, BalanceOf::::from(slash_amount)) )) .collect::>(); + let reward_events = reporters.into_iter() - .flat_map(|reporter| vec![ - frame_system::Event::::NewAccount(reporter.clone()).into(), - ::Event::from( - pallet_balances::Event::::Endowed(reporter, (reward_amount / r).into()) - ).into() - ]); + .flat_map(|reporter| { + let accounts_event: ::Event + = pallet_accounts::Event::NewAccount(reporter.clone()).into(); + let new_account_event: ::Event = accounts_event.into(); + + vec![ + new_account_event, + ::Event::from( + pallet_balances::Event::::Endowed(reporter, (reward_amount / r).into()) + ).into() + ] + }); // rewards are applied after first offender and it's nominators let slash_rest = slash_events.split_off(1 + n as usize); diff --git a/frame/offences/benchmarking/src/mock.rs b/frame/offences/benchmarking/src/mock.rs index 124e6b13b77ac..17cb1c45c13a1 100644 --- a/frame/offences/benchmarking/src/mock.rs +++ b/frame/offences/benchmarking/src/mock.rs @@ -60,11 +60,15 @@ impl frame_system::Config for Test { type BlockHashCount = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub const ExistentialDeposit: Balance = 10; @@ -75,7 +79,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -130,6 +135,7 @@ impl pallet_session::Config for Test { type ValidatorIdOf = pallet_staking::StashOf; type DisabledValidatorsThreshold = (); type WeightInfo = (); + type ReferencedAccount = Accounts; } pallet_staking_reward_curve::build! { @@ -180,6 +186,7 @@ impl pallet_staking::Config for Test { type OffchainSolutionWeightLimit = (); type ElectionProvider = onchain::OnChainSequentialPhragmen; type WeightInfo = (); + type ReferencedAccount = Accounts; } impl pallet_im_online::Config for Test { @@ -220,6 +227,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic { System: system::{Module, Call, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Staking: pallet_staking::{Module, Call, Config, Storage, Event, ValidateUnsigned}, Session: pallet_session::{Module, Call, Storage, Event, Config}, diff --git a/frame/offences/src/mock.rs b/frame/offences/src/mock.rs index c47a9cf943c18..fd96e4f05bb45 100644 --- a/frame/offences/src/mock.rs +++ b/frame/offences/src/mock.rs @@ -119,9 +119,7 @@ impl frame_system::Config for Runtime { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/proxy/Cargo.toml b/frame/proxy/Cargo.toml index 2934b9953b316..108febdc5cb54 100644 --- a/frame/proxy/Cargo.toml +++ b/frame/proxy/Cargo.toml @@ -26,6 +26,7 @@ frame-benchmarking = { version = "3.1.0", default-features = false, path = "../b [dev-dependencies] sp-core = { version = "3.0.0", path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } pallet-utility = { version = "3.0.0", path = "../utility" } diff --git a/frame/proxy/src/tests.rs b/frame/proxy/src/tests.rs index b31ef1dfdb2fe..18ea17c368fb4 100644 --- a/frame/proxy/src/tests.rs +++ b/frame/proxy/src/tests.rs @@ -39,6 +39,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Proxy: proxy::{Module, Call, Storage, Event}, Utility: pallet_utility::{Module, Call, Event}, @@ -68,11 +69,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub const ExistentialDeposit: u64 = 1; @@ -83,7 +88,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } impl pallet_utility::Config for Test { diff --git a/frame/randomness-collective-flip/src/lib.rs b/frame/randomness-collective-flip/src/lib.rs index 57e95ccb141df..0418865531f88 100644 --- a/frame/randomness-collective-flip/src/lib.rs +++ b/frame/randomness-collective-flip/src/lib.rs @@ -188,9 +188,7 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/recovery/Cargo.toml b/frame/recovery/Cargo.toml index 1f8003bd4d056..0cb7c4c708e91 100644 --- a/frame/recovery/Cargo.toml +++ b/frame/recovery/Cargo.toml @@ -24,6 +24,7 @@ frame-system = { version = "3.0.0", default-features = false, path = "../system" [dev-dependencies] sp-core = { version = "3.0.0", path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/recovery/src/lib.rs b/frame/recovery/src/lib.rs index 00cd6ff2a7f79..04563cbe21695 100644 --- a/frame/recovery/src/lib.rs +++ b/frame/recovery/src/lib.rs @@ -161,7 +161,7 @@ use codec::{Encode, Decode}; use frame_support::{ decl_module, decl_event, decl_storage, decl_error, ensure, Parameter, RuntimeDebug, weights::GetDispatchInfo, - traits::{Currency, ReservableCurrency, Get, BalanceStatus}, + traits::{Currency, ReservableCurrency, Get, BalanceStatus, ReferencedAccount}, dispatch::PostDispatchInfo, }; use frame_system::{self as system, ensure_signed, ensure_root}; @@ -207,6 +207,9 @@ pub trait Config: frame_system::Config { /// `sizeof(BlockNumber, Balance + T * AccountId)` bytes. Where T is a configurable /// threshold. type RecoveryDeposit: Get>; + + /// A way to place reference counters on accounts. + type ReferencedAccount: ReferencedAccount; } /// An active recovery process. @@ -588,7 +591,7 @@ decl_module! { recovery_config.threshold as usize <= active_recovery.friends.len(), Error::::Threshold ); - system::Module::::inc_consumers(&who).map_err(|_| Error::::BadState)?; + T::ReferencedAccount::inc_consumers(&who).map_err(|_| Error::::BadState)?; // Create the recovery storage item Proxy::::insert(&who, &account); Self::deposit_event(RawEvent::AccountRecovered(account, who)); @@ -677,7 +680,7 @@ decl_module! { // Check `who` is allowed to make a call on behalf of `account` ensure!(Self::proxy(&who) == Some(account), Error::::NotAllowed); Proxy::::remove(&who); - system::Module::::dec_consumers(&who); + T::ReferencedAccount::dec_consumers(&who); } } } diff --git a/frame/recovery/src/mock.rs b/frame/recovery/src/mock.rs index ee38b0e24cc60..9630c765159d7 100644 --- a/frame/recovery/src/mock.rs +++ b/frame/recovery/src/mock.rs @@ -36,6 +36,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Recovery: recovery::{Module, Call, Storage, Event}, } @@ -65,11 +66,16 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { @@ -82,7 +88,8 @@ impl pallet_balances::Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -101,6 +108,7 @@ impl Config for Test { type FriendDepositFactor = FriendDepositFactor; type MaxFriends = MaxFriends; type RecoveryDeposit = RecoveryDeposit; + type ReferencedAccount = Accounts; } pub type BalancesCall = pallet_balances::Call; diff --git a/frame/scheduler/src/lib.rs b/frame/scheduler/src/lib.rs index 5cab10b0aff38..d1e0f464b8874 100644 --- a/frame/scheduler/src/lib.rs +++ b/frame/scheduler/src/lib.rs @@ -830,9 +830,7 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/scored-pool/Cargo.toml b/frame/scored-pool/Cargo.toml index 97e3a954d7e25..c60d2a821acf6 100644 --- a/frame/scored-pool/Cargo.toml +++ b/frame/scored-pool/Cargo.toml @@ -22,6 +22,7 @@ frame-support = { version = "3.0.0", default-features = false, path = "../suppor frame-system = { version = "3.0.0", default-features = false, path = "../system" } [dev-dependencies] +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } sp-core = { version = "3.0.0", path = "../../primitives/core" } diff --git a/frame/scored-pool/src/mock.rs b/frame/scored-pool/src/mock.rs index 3c4263b813e41..8ce5387ffad27 100644 --- a/frame/scored-pool/src/mock.rs +++ b/frame/scored-pool/src/mock.rs @@ -38,6 +38,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, ScoredPool: pallet_scored_pool::{Module, Call, Storage, Config, Event}, } @@ -74,11 +75,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } impl pallet_balances::Config for Test { @@ -87,7 +92,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } diff --git a/frame/session/Cargo.toml b/frame/session/Cargo.toml index 52b8ebbdf4780..8eaf64374bf8c 100644 --- a/frame/session/Cargo.toml +++ b/frame/session/Cargo.toml @@ -29,6 +29,7 @@ impl-trait-for-tuples = "0.2.1" [dev-dependencies] sp-application-crypto = { version = "3.0.0", path = "../../primitives/application-crypto" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } lazy_static = "1.4.0" [features] @@ -40,6 +41,7 @@ std = [ "sp-std/std", "sp-io/std", "frame-support/std", + "frame-system/std", "sp-core/std", "sp-runtime/std", "sp-session/std", diff --git a/frame/session/benchmarking/Cargo.toml b/frame/session/benchmarking/Cargo.toml index 47265ed5ef7a8..508dc87ceb98b 100644 --- a/frame/session/benchmarking/Cargo.toml +++ b/frame/session/benchmarking/Cargo.toml @@ -30,6 +30,7 @@ sp-core = { version = "3.0.0", path = "../../../primitives/core" } pallet-staking-reward-curve = { version = "3.0.0", path = "../../staking/reward-curve" } sp-io ={ version = "3.0.0", path = "../../../primitives/io" } pallet-timestamp = { version = "3.0.0", path = "../../timestamp" } +pallet-accounts = { version = "3.0.0", path = "../../accounts" } pallet-balances = { version = "3.0.0", path = "../../balances" } sp-election-providers = { version = "3.0.0", path = "../../../primitives/election-providers" } diff --git a/frame/session/benchmarking/src/lib.rs b/frame/session/benchmarking/src/lib.rs index 8546800ee4fdc..40f73ec6f22c1 100644 --- a/frame/session/benchmarking/src/lib.rs +++ b/frame/session/benchmarking/src/lib.rs @@ -25,7 +25,7 @@ mod mock; use sp_std::prelude::*; use sp_std::vec; -use frame_benchmarking::{benchmarks, impl_benchmark_test_suite}; +use frame_benchmarking::{benchmarks, impl_benchmark_test_suite, whitelist_account}; use frame_support::{ codec::Decode, storage::StorageValue, @@ -63,8 +63,7 @@ benchmarks! { let keys = T::Keys::default(); let proof: Vec = vec![0,1,2,3]; // Whitelist controller account from further DB operations. - let v_controller_key = frame_system::Account::::hashed_key_for(&v_controller); - frame_benchmarking::benchmarking::add_to_whitelist(v_controller_key.into()); + whitelist_account!(v_controller); }: _(RawOrigin::Signed(v_controller), keys, proof) purge_keys { @@ -80,8 +79,7 @@ benchmarks! { let proof: Vec = vec![0,1,2,3]; Session::::set_keys(RawOrigin::Signed(v_controller.clone()).into(), keys, proof)?; // Whitelist controller account from further DB operations. - let v_controller_key = frame_system::Account::::hashed_key_for(&v_controller); - frame_benchmarking::benchmarking::add_to_whitelist(v_controller_key.into()); + whitelist_account!(v_controller); }: _(RawOrigin::Signed(v_controller)) #[extra] diff --git a/frame/session/benchmarking/src/mock.rs b/frame/session/benchmarking/src/mock.rs index 0eba5452b28d0..1c45c6f6194a5 100644 --- a/frame/session/benchmarking/src/mock.rs +++ b/frame/session/benchmarking/src/mock.rs @@ -38,6 +38,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Staking: pallet_staking::{Module, Call, Config, Storage, Event, ValidateUnsigned}, Session: pallet_session::{Module, Call, Storage, Event, Config}, @@ -62,11 +63,15 @@ impl frame_system::Config for Test { type BlockHashCount = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub const ExistentialDeposit: Balance = 10; @@ -77,7 +82,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -126,6 +132,7 @@ impl pallet_session::Config for Test { type ValidatorId = AccountId; type ValidatorIdOf = pallet_staking::StashOf; type DisabledValidatorsThreshold = (); + type ReferencedAccount = Accounts; type WeightInfo = (); } pallet_staking_reward_curve::build! { @@ -184,6 +191,7 @@ impl pallet_staking::Config for Test { type MinSolutionScoreBump = (); type OffchainSolutionWeightLimit = (); type ElectionProvider = onchain::OnChainSequentialPhragmen; + type ReferencedAccount = Accounts; type WeightInfo = (); } diff --git a/frame/session/src/historical/mod.rs b/frame/session/src/historical/mod.rs index 9b4d2704cf456..8a9ff8dc2b5cc 100644 --- a/frame/session/src/historical/mod.rs +++ b/frame/session/src/historical/mod.rs @@ -344,9 +344,9 @@ pub(crate) mod tests { use sp_runtime::testing::UintAuthorityId; use crate::mock::{ NEXT_VALIDATORS, force_new_session, - set_next_validators, Test, System, Session, + set_next_validators, Test, System, Session, Accounts, }; - use frame_support::traits::{KeyOwnerProofSystem, OnInitialize}; + use frame_support::traits::{KeyOwnerProofSystem, OnInitialize, ReferencedAccount}; use frame_support::BasicExternalities; type Historical = Module; @@ -358,7 +358,7 @@ pub(crate) mod tests { ); BasicExternalities::execute_with_storage(&mut t, || { for (ref k, ..) in &keys { - frame_system::Module::::inc_providers(k); + Accounts::inc_providers(k); } }); crate::GenesisConfig:: { keys }.assimilate_storage(&mut t).unwrap(); diff --git a/frame/session/src/historical/offchain.rs b/frame/session/src/historical/offchain.rs index f095be9e44e24..198bddb9edc14 100644 --- a/frame/session/src/historical/offchain.rs +++ b/frame/session/src/historical/offchain.rs @@ -140,10 +140,10 @@ mod tests { use super::super::{onchain, Module}; use super::*; use crate::mock::{ - force_new_session, set_next_validators, Session, System, Test, NEXT_VALIDATORS, + force_new_session, set_next_validators, Session, System, Test, NEXT_VALIDATORS, Accounts, }; use codec::Encode; - use frame_support::traits::{KeyOwnerProofSystem, OnInitialize}; + use frame_support::traits::{KeyOwnerProofSystem, OnInitialize, ReferencedAccount}; use sp_core::crypto::key_types::DUMMY; use sp_core::offchain::{ testing::TestOffchainExt, @@ -167,7 +167,7 @@ mod tests { ); BasicExternalities::execute_with_storage(&mut t, || { for (ref k, ..) in &keys { - frame_system::Module::::inc_providers(k); + Accounts::inc_providers(k); } }); diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index d95d99389f732..0dc04d6233560 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -123,7 +123,7 @@ use frame_support::{ ensure, decl_module, decl_event, decl_storage, decl_error, ConsensusEngineId, Parameter, traits::{ Get, FindAuthor, ValidatorRegistration, EstimateNextSessionRotation, EstimateNextNewSession, - OneSessionHandler, ValidatorSet, + OneSessionHandler, ValidatorSet, ReferencedAccount, }, dispatch::{self, DispatchResult, DispatchError}, weights::Weight, @@ -366,6 +366,9 @@ pub trait Config: frame_system::Config { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; + + /// A way to add reference counters to accounts; + type ReferencedAccount: ReferencedAccount; } decl_storage! { @@ -415,7 +418,7 @@ decl_storage! { for (account, val, keys) in config.keys.iter().cloned() { >::inner_set_keys(&val, keys) .expect("genesis config must not contain duplicates; qed"); - assert!(frame_system::Module::::inc_consumers(&account).is_ok()); + assert!(T::ReferencedAccount::inc_consumers(&account).is_ok()); } let initial_validators_0 = T::SessionManager::new_session(0) @@ -719,10 +722,10 @@ impl Module { let who = T::ValidatorIdOf::convert(account.clone()) .ok_or(Error::::NoAssociatedValidatorId)?; - frame_system::Module::::inc_consumers(&account).map_err(|_| Error::::NoAccount)?; + T::ReferencedAccount::inc_consumers(&account).map_err(|_| Error::::NoAccount)?; let old_keys = Self::inner_set_keys(&who, keys)?; if old_keys.is_some() { - let _ = frame_system::Module::::dec_consumers(&account); + let _ = T::ReferencedAccount::dec_consumers(&account); // ^^^ Defensive only; Consumers were incremented just before, so should never fail. } @@ -771,7 +774,7 @@ impl Module { let key_data = old_keys.get_raw(*id); Self::clear_key_owner(*id, key_data); } - frame_system::Module::::dec_consumers(&account); + T::ReferencedAccount::dec_consumers(&account); Ok(()) } diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index 73499bf739b87..86b13a4c45ea8 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -79,6 +79,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Session: pallet_session::{Module, Call, Storage, Event, Config}, Historical: pallet_session_historical::{Module}, } @@ -92,6 +93,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Session: pallet_session::{Module, Call, Storage, Event, Config}, } ); @@ -210,11 +212,11 @@ pub fn new_test_ext() -> sp_io::TestExternalities { ); BasicExternalities::execute_with_storage(&mut t, || { for (ref k, ..) in &keys { - frame_system::Module::::inc_providers(k); + Accounts::inc_providers(k); } - frame_system::Module::::inc_providers(&4); + Accounts::inc_providers(&4); // An additional identity that we use. - frame_system::Module::::inc_providers(&69); + Accounts::inc_providers(&69); }); pallet_session::GenesisConfig:: { keys }.assimilate_storage(&mut t).unwrap(); sp_io::TestExternalities::new(t) @@ -245,13 +247,18 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = (); +} + impl pallet_timestamp::Config for Test { type Moment = u64; type OnTimestampSet = (); @@ -277,6 +284,7 @@ impl Config for Test { type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type NextSessionRotation = (); type WeightInfo = (); + type ReferencedAccount = Accounts; } #[cfg(feature = "historical")] diff --git a/frame/session/src/tests.rs b/frame/session/src/tests.rs index b2e086aed90c5..6f209f45e9bc0 100644 --- a/frame/session/src/tests.rs +++ b/frame/session/src/tests.rs @@ -26,7 +26,7 @@ use mock::{ SESSION_CHANGED, TEST_SESSION_CHANGED, authorities, force_new_session, set_next_validators, set_session_length, session_changed, Origin, System, Session, reset_before_session_end_called, before_session_end_called, new_test_ext, - PreUpgradeMockSessionKeys, + PreUpgradeMockSessionKeys, Accounts, }; fn initialize_block(block: u64) { @@ -61,9 +61,9 @@ fn keys_cleared_on_kill() { let id = DUMMY; assert_eq!(Session::key_owner(id, UintAuthorityId(1).get_raw(id)), Some(1)); - assert!(System::is_provider_required(&1)); + assert!(Accounts::is_provider_required(&1)); assert_ok!(Session::purge_keys(Origin::signed(1))); - assert!(!System::is_provider_required(&1)); + assert!(!Accounts::is_provider_required(&1)); assert_eq!(Session::load_keys(&1), None); assert_eq!(Session::key_owner(id, UintAuthorityId(1).get_raw(id)), None); diff --git a/frame/society/Cargo.toml b/frame/society/Cargo.toml index a3c6dcadab86d..7c40301ffd55c 100644 --- a/frame/society/Cargo.toml +++ b/frame/society/Cargo.toml @@ -25,6 +25,7 @@ rand_chacha = { version = "0.2", default-features = false } sp-core = { version = "3.0.0", path = "../../primitives/core" } sp-io ={ version = "3.0.0", path = "../../primitives/io" } frame-support-test = { version = "3.0.0", path = "../support/test" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/society/src/mock.rs b/frame/society/src/mock.rs index 0a684b2a8dc89..2de62f84c9f7b 100644 --- a/frame/society/src/mock.rs +++ b/frame/society/src/mock.rs @@ -42,6 +42,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Society: pallet_society::{Module, Call, Storage, Event, Config}, } @@ -85,20 +86,26 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type OnNewAccount = (); - type OnKilledAccount = (); - type AccountData = pallet_balances::AccountData; + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; +} + impl pallet_balances::Config for Test { type MaxLocks = (); type Balance = u64; type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } diff --git a/frame/staking/Cargo.toml b/frame/staking/Cargo.toml index 1f9f29570a223..b85b1171c4666 100644 --- a/frame/staking/Cargo.toml +++ b/frame/staking/Cargo.toml @@ -24,6 +24,7 @@ sp-runtime = { version = "3.0.0", default-features = false, path = "../../primit sp-staking = { version = "3.0.0", default-features = false, path = "../../primitives/staking" } frame-support = { version = "3.0.0", default-features = false, path = "../support" } frame-system = { version = "3.0.0", default-features = false, path = "../system" } +pallet-accounts = { version = "3.0.0", default-features = false, path = "../accounts" } pallet-session = { version = "3.0.0", default-features = false, features = ["historical"], path = "../session" } pallet-authorship = { version = "3.0.0", default-features = false, path = "../authorship" } sp-application-crypto = { version = "3.0.0", default-features = false, path = "../../primitives/application-crypto" } @@ -61,6 +62,7 @@ std = [ "sp-staking/std", "pallet-session/std", "frame-system/std", + "pallet-accounts/std", "pallet-authorship/std", "sp-application-crypto/std", "log/std", diff --git a/frame/staking/fuzzer/Cargo.toml b/frame/staking/fuzzer/Cargo.toml index 84758c6bf65ce..014e042deed05 100644 --- a/frame/staking/fuzzer/Cargo.toml +++ b/frame/staking/fuzzer/Cargo.toml @@ -22,6 +22,7 @@ pallet-indices = { version = "3.0.0", path = "../../indices" } pallet-balances = { version = "3.0.0", path = "../../balances" } pallet-timestamp = { version = "3.0.0", path = "../../timestamp" } frame-system = { version = "3.0.0", path = "../../system" } +pallet-accounts = { version = "3.0.0", path = "../../accounts" } frame-support = { version = "3.0.0", path = "../../support" } sp-std = { version = "3.0.0", path = "../../../primitives/std" } sp-io ={ version = "3.0.0", path = "../../../primitives/io" } diff --git a/frame/staking/fuzzer/src/mock.rs b/frame/staking/fuzzer/src/mock.rs index 05d001d23858e..83463b96febd4 100644 --- a/frame/staking/fuzzer/src/mock.rs +++ b/frame/staking/fuzzer/src/mock.rs @@ -34,6 +34,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Staking: pallet_staking::{Module, Call, Config, Storage, Event, ValidateUnsigned}, Indices: pallet_indices::{Module, Call, Storage, Config, Event}, @@ -59,12 +60,18 @@ impl frame_system::Config for Test { type BlockHashCount = (); type Version = (); type PalletInfo = PalletInfo; + type SystemWeightInfo = (); + type SS58Prefix = (); + type AccountStorage = Accounts; +} + +impl pallet_accounts::Config for Test { + type Event = Event; type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = (); } + parameter_types! { pub const ExistentialDeposit: Balance = 10; } @@ -74,7 +81,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } impl pallet_indices::Config for Test { @@ -129,6 +137,7 @@ impl pallet_session::Config for Test { type ValidatorId = AccountId; type ValidatorIdOf = pallet_staking::StashOf; type DisabledValidatorsThreshold = (); + type ReferencedAccount = Accounts; type WeightInfo = (); } pallet_staking_reward_curve::build! { @@ -191,4 +200,5 @@ impl pallet_staking::Config for Test { type OffchainSolutionWeightLimit = (); type WeightInfo = (); type ElectionProvider = MockElectionProvider; + type ReferencedAccount = Accounts; } diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index ed8a2efbd45a4..6b2962c6d4556 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -300,7 +300,7 @@ use frame_support::{ }, traits::{ Currency, LockIdentifier, LockableCurrency, WithdrawReasons, OnUnbalanced, Imbalance, Get, - UnixTime, EstimateNextNewSession, EnsureOrigin, CurrencyToVote, IsSubType, + UnixTime, EstimateNextNewSession, EnsureOrigin, CurrencyToVote, IsSubType, ReferencedAccount, } }; use pallet_session::historical; @@ -323,7 +323,7 @@ use sp_staking::{ #[cfg(feature = "std")] use sp_runtime::{Serialize, Deserialize}; use frame_system::{ - self as system, ensure_signed, ensure_root, ensure_none, + ensure_signed, ensure_root, ensure_none, offchain::SendTransactionTypes, }; use sp_npos_elections::{ @@ -780,7 +780,7 @@ impl SessionInterface<::AccountId> for T w } } -pub trait Config: frame_system::Config + SendTransactionTypes> { +pub trait Config: frame_system::Config + pallet_accounts::Config + SendTransactionTypes> { /// The staking balance. type Currency: LockableCurrency; @@ -884,6 +884,9 @@ pub trait Config: frame_system::Config + SendTransactionTypes> { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; + + /// A way to place reference counters on an account. + type ReferencedAccount: ReferencedAccount; } /// Mode of era-forcing. @@ -1500,7 +1503,7 @@ decl_module! { Err(Error::::InsufficientValue)? } - system::Module::::inc_consumers(&stash).map_err(|_| Error::::BadState)?; + T::ReferencedAccount::inc_consumers(&stash).map_err(|_| Error::::BadState)?; // You're auto-bonded forever, here. We might improve this by only bonding when // you actually validate/nominate and remove once you unbond __everything__. @@ -3202,7 +3205,7 @@ impl Module { >::remove(stash); >::remove(stash); - system::Module::::dec_consumers(stash); + T::ReferencedAccount::dec_consumers(stash); Ok(()) } diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 0d6701c48b894..142d673b3a12f 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -99,6 +99,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Staking: staking::{Module, Call, Config, Storage, Event, ValidateUnsigned}, @@ -150,19 +151,24 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; +} impl pallet_balances::Config for Test { type MaxLocks = MaxLocks; type Balance = Balance; type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } parameter_types! { @@ -184,6 +190,7 @@ impl pallet_session::Config for Test { type ValidatorIdOf = crate::StashOf; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type NextSessionRotation = pallet_session::PeriodicSessions; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -269,6 +276,7 @@ impl Config for Test { type UnsignedPriority = UnsignedPriority; type OffchainSolutionWeightLimit = OffchainSolutionWeightLimit; type ElectionProvider = onchain::OnChainSequentialPhragmen; + type ReferencedAccount = Accounts; type WeightInfo = (); } diff --git a/frame/sudo/src/mock.rs b/frame/sudo/src/mock.rs index 91cd03ac4756a..ce3d425b32286 100644 --- a/frame/sudo/src/mock.rs +++ b/frame/sudo/src/mock.rs @@ -118,9 +118,7 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/support/src/traits.rs b/frame/support/src/traits.rs index 1427a727a15d8..a2289d7c817b4 100644 --- a/frame/support/src/traits.rs +++ b/frame/support/src/traits.rs @@ -2247,6 +2247,76 @@ pub trait ExecuteBlock { fn execute_block(block: Block); } +/// A minimal API for creating an account system compatible with FRAME System. +pub trait BasicAccount { + type AccountInfo; + + /// Return whether an account exists in storage. + fn account_exists(who: &AccountId) -> bool; + + /// Return the data for an account. + fn get(who: &AccountId) -> Self::AccountInfo; + + /// Retrieve the account transaction counter from storage. + fn account_nonce(who: &AccountId) -> Index; + + /// Increment a particular account's nonce by 1. + fn inc_account_nonce(who: &AccountId); + + /// Return the storage key for an account. + fn hashed_key_for(who: &AccountId) -> Vec; +} + +/// An API on top of `BasicAccount` which provides the ability for users to place +/// reference counters on an account, preventing account deletion. +pub trait ReferencedAccount: BasicAccount { + type RefCount; + type IncRefStatus; + type DecRefStatus; + type IncRefError; + type DecRefError; + + /// Increment the provider reference counter on an account. + fn inc_providers(who: &AccountId) -> Self::IncRefStatus; + + /// Decrement the provider reference counter on an account. + /// + /// This *MUST* only be done once for every time you called `inc_providers` on `who`. + fn dec_providers(who: &AccountId) -> Result; + + /// Increment the self-sufficient reference counter on an account. + fn inc_sufficients(who: &AccountId) -> Self::IncRefStatus; + + /// Decrement the sufficients reference counter on an account. + /// + /// This *MUST* only be done once for every time you called `inc_sufficients` on `who`. + fn dec_sufficients(who: &AccountId) -> Self::DecRefStatus; + + /// The number of outstanding provider references for the account `who`. + fn providers(who: &AccountId) -> Self::RefCount; + + /// The number of outstanding sufficient references for the account `who`. + fn sufficients(who: &AccountId) -> Self::RefCount; + + /// The number of outstanding provider and sufficient references for the account `who`. + fn reference_count(who: &AccountId) -> Self::RefCount; + + /// Increment the reference counter on an account. + /// + /// The account `who`'s `providers` must be non-zero or this will return an error. + fn inc_consumers(who: &AccountId) -> Result<(), Self::IncRefError>; + + /// Decrement the reference counter on an account. This *MUST* only be done once for every time + /// you called `inc_consumers` on `who`. + fn dec_consumers(who: &AccountId); + + /// The number of outstanding references for the account `who`. + fn consumers(who: &AccountId) -> Self::RefCount; + + /// True if the account has some outstanding references. + fn is_provider_required(who: &AccountId) -> bool; +} + #[cfg(test)] mod tests { use super::*; diff --git a/frame/support/test/tests/pallet.rs b/frame/support/test/tests/pallet.rs index a31ce9d91ae2d..bf5fc1a46f57e 100644 --- a/frame/support/test/tests/pallet.rs +++ b/frame/support/test/tests/pallet.rs @@ -368,9 +368,7 @@ impl frame_system::Config for Runtime { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/support/test/tests/pallet_compatibility.rs b/frame/support/test/tests/pallet_compatibility.rs index 5b9001e0475fe..c3b6aa0759750 100644 --- a/frame/support/test/tests/pallet_compatibility.rs +++ b/frame/support/test/tests/pallet_compatibility.rs @@ -220,9 +220,7 @@ impl frame_system::Config for Runtime { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/support/test/tests/pallet_compatibility_instance.rs b/frame/support/test/tests/pallet_compatibility_instance.rs index d7de03ea46cfd..2c1400eccf718 100644 --- a/frame/support/test/tests/pallet_compatibility_instance.rs +++ b/frame/support/test/tests/pallet_compatibility_instance.rs @@ -212,9 +212,7 @@ impl frame_system::Config for Runtime { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/support/test/tests/pallet_instance.rs b/frame/support/test/tests/pallet_instance.rs index 62654d53e19d7..b1f6577c0cc86 100644 --- a/frame/support/test/tests/pallet_instance.rs +++ b/frame/support/test/tests/pallet_instance.rs @@ -255,9 +255,7 @@ impl frame_system::Config for Runtime { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/support/test/tests/pallet_version.rs b/frame/support/test/tests/pallet_version.rs index 4cc93d395db2a..b28b2ed948d86 100644 --- a/frame/support/test/tests/pallet_version.rs +++ b/frame/support/test/tests/pallet_version.rs @@ -161,9 +161,7 @@ impl frame_system::Config for Runtime { type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/support/test/tests/pallet_with_name_trait_is_valid.rs b/frame/support/test/tests/pallet_with_name_trait_is_valid.rs index b09beb04cd17c..2f8ad42358bbf 100644 --- a/frame/support/test/tests/pallet_with_name_trait_is_valid.rs +++ b/frame/support/test/tests/pallet_with_name_trait_is_valid.rs @@ -136,9 +136,7 @@ mod tests { type BlockLength = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/system/Cargo.toml b/frame/system/Cargo.toml index 4306dbd644815..8c256a38ce6ef 100644 --- a/frame/system/Cargo.toml +++ b/frame/system/Cargo.toml @@ -28,6 +28,7 @@ log = { version = "0.4.14", default-features = false } criterion = "0.3.3" sp-externalities = { version = "0.9.0", path = "../../primitives/externalities" } substrate-test-runtime-client = { version = "2.0.0", path = "../../test-utils/runtime/client" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } [features] default = ["std"] diff --git a/frame/system/benches/bench.rs b/frame/system/benches/bench.rs index 6ed3d456826c2..d8de464f33aaa 100644 --- a/frame/system/benches/bench.rs +++ b/frame/system/benches/bench.rs @@ -84,9 +84,7 @@ impl system::Config for Runtime { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/system/benchmarking/src/mock.rs b/frame/system/benchmarking/src/mock.rs index edc5dfebbd106..447dde72d165f 100644 --- a/frame/system/benchmarking/src/mock.rs +++ b/frame/system/benchmarking/src/mock.rs @@ -56,9 +56,7 @@ impl frame_system::Config for Test { type BlockHashCount = (); type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/system/rpc/runtime-api/Cargo.toml b/frame/system/rpc/runtime-api/Cargo.toml index 56619d59ddcad..6c2a8565a627d 100644 --- a/frame/system/rpc/runtime-api/Cargo.toml +++ b/frame/system/rpc/runtime-api/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" license = "Apache-2.0" homepage = "https://substrate.dev" repository = "https://github.com/paritytech/substrate/" -description = "Runtime API definition required by System RPC extensions." +description = "Runtime API definition required by Accounts RPC extensions." readme = "README.md" [package.metadata.docs.rs] diff --git a/frame/system/rpc/runtime-api/README.md b/frame/system/rpc/runtime-api/README.md index ab46c22a8be33..4adfb89c0cdbc 100644 --- a/frame/system/rpc/runtime-api/README.md +++ b/frame/system/rpc/runtime-api/README.md @@ -1,7 +1,7 @@ -Runtime API definition required by System RPC extensions. +Runtime API definition required by Accounts RPC extensions. This API should be imported and implemented by the runtime, of a node that wants to use the custom RPC extension -adding System access methods. +adding Accounts access methods. -License: Apache-2.0 \ No newline at end of file +License: Apache-2.0 diff --git a/frame/system/rpc/runtime-api/src/lib.rs b/frame/system/rpc/runtime-api/src/lib.rs index 319883c36d748..e04c6cea03b10 100644 --- a/frame/system/rpc/runtime-api/src/lib.rs +++ b/frame/system/rpc/runtime-api/src/lib.rs @@ -15,11 +15,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Runtime API definition required by System RPC extensions. +//! Runtime API definition required by Accounts RPC extensions. //! //! This API should be imported and implemented by the runtime, //! of a node that wants to use the custom RPC extension -//! adding System access methods. +//! adding Accounts access methods. #![cfg_attr(not(feature = "std"), no_std)] diff --git a/frame/system/src/extensions/check_nonce.rs b/frame/system/src/extensions/check_nonce.rs index 3cb74a7ed918d..299c5eca7b243 100644 --- a/frame/system/src/extensions/check_nonce.rs +++ b/frame/system/src/extensions/check_nonce.rs @@ -17,7 +17,10 @@ use codec::{Encode, Decode}; use crate::Config; -use frame_support::weights::DispatchInfo; +use frame_support::{ + traits::BasicAccount, + weights::DispatchInfo, +}; use sp_runtime::{ traits::{SignedExtension, DispatchInfoOf, Dispatchable, One}, transaction_validity::{ @@ -71,18 +74,17 @@ impl SignedExtension for CheckNonce where _info: &DispatchInfoOf, _len: usize, ) -> Result<(), TransactionValidityError> { - let mut account = crate::Account::::get(who); - if self.0 != account.nonce { + let account_nonce = T::AccountStorage::account_nonce(who); + if self.0 != account_nonce { return Err( - if self.0 < account.nonce { + if self.0 < account_nonce { InvalidTransaction::Stale } else { InvalidTransaction::Future }.into() ) } - account.nonce += T::Index::one(); - crate::Account::::insert(who, account); + T::AccountStorage::inc_account_nonce(who); Ok(()) } @@ -94,13 +96,13 @@ impl SignedExtension for CheckNonce where _len: usize, ) -> TransactionValidity { // check index - let account = crate::Account::::get(who); - if self.0 < account.nonce { + let account_nonce = T::AccountStorage::account_nonce(who); + if self.0 < account_nonce { return InvalidTransaction::Stale.into() } let provides = vec![Encode::encode(&(who, self.0))]; - let requires = if account.nonce < self.0 { + let requires = if account_nonce < self.0 { vec![Encode::encode(&(who, self.0 - One::one()))] } else { vec![] @@ -124,13 +126,7 @@ mod tests { #[test] fn signed_ext_check_nonce_works() { new_test_ext().execute_with(|| { - crate::Account::::insert(1, crate::AccountInfo { - nonce: 1, - consumers: 0, - providers: 0, - sufficients: 0, - data: 0, - }); + crate::Account::::insert(1, 1); let info = DispatchInfo::default(); let len = 0_usize; // stale diff --git a/frame/system/src/lib.rs b/frame/system/src/lib.rs index ce9ab0dddc105..f6623fac8a25b 100644 --- a/frame/system/src/lib.rs +++ b/frame/system/src/lib.rs @@ -78,7 +78,7 @@ use sp_runtime::{ self, CheckEqual, AtLeast32Bit, Zero, Lookup, LookupError, SimpleBitOps, Hash, Member, MaybeDisplay, BadOrigin, MaybeSerializeDeserialize, MaybeMallocSizeOf, StaticLookup, One, Bounded, - Dispatchable, AtLeast32BitUnsigned, Saturating, StoredMapError, + Dispatchable, AtLeast32BitUnsigned, Saturating, }, offchain::storage_lock::BlockNumberProvider, }; @@ -87,8 +87,8 @@ use sp_core::{ChangesTrieConfiguration, storage::well_known_keys}; use frame_support::{ Parameter, storage, traits::{ - Contains, Get, PalletInfo, OnNewAccount, OnKilledAccount, HandleLifetime, - StoredMap, EnsureOrigin, OriginTrait, Filter, + Contains, Get, PalletInfo, + EnsureOrigin, OriginTrait, Filter, BasicAccount, }, weights::{ Weight, RuntimeDbWeight, DispatchInfo, DispatchClass, @@ -96,7 +96,7 @@ use frame_support::{ }, dispatch::DispatchResultWithPostInfo, }; -use codec::{Encode, Decode, FullCodec, EncodeLike}; +use codec::{Encode, Decode}; #[cfg(feature = "std")] use frame_support::traits::GenesisBuild; @@ -232,18 +232,6 @@ pub mod pallet { /// For tests it is okay to use `()` as type, however it will provide "useless" data. type PalletInfo: PalletInfo; - /// Data to be associated with an account (other than nonce/transaction counter, which this - /// pallet does regardless). - type AccountData: Member + FullCodec + Clone + Default; - - /// Handler for when a new account has just been created. - type OnNewAccount: OnNewAccount; - - /// A function that is invoked when an account has been determined to be dead. - /// - /// All resources should be cleaned up associated with the given account. - type OnKilledAccount: OnKilledAccount; - type SystemWeightInfo: WeightInfo; /// The designated SS85 prefix of this chain. @@ -253,6 +241,8 @@ pub mod pallet { /// an identifier of the chain. #[pallet::constant] type SS58Prefix: Get; + + type AccountStorage: BasicAccount; } #[pallet::pallet] @@ -262,12 +252,7 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { fn on_runtime_upgrade() -> frame_support::weights::Weight { - if !UpgradedToTripleRefCount::::get() { - UpgradedToTripleRefCount::::put(true); - migrations::migrate_to_triple_ref_count::() - } else { - 0 - } + 0 } fn integrity_test() { @@ -509,14 +494,14 @@ pub mod pallet { #[pallet::origin] pub type Origin = RawOrigin<::AccountId>; - /// The full account information for a particular account ID. + /// Basic account information for a particular account ID. #[pallet::storage] #[pallet::getter(fn account)] pub type Account = StorageMap< _, Blake2_128Concat, T::AccountId, - AccountInfo, + T::Index, ValueQuery, >; @@ -638,38 +623,6 @@ pub mod pallet { } } -mod migrations { - use super::*; - - #[allow(dead_code)] - /// Migrate from unique `u8` reference counting to triple `u32` reference counting. - pub fn migrate_all() -> frame_support::weights::Weight { - Account::::translate::<(T::Index, u8, T::AccountData), _>(|_key, (nonce, rc, data)| - Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, sufficients: 0, data }) - ); - T::BlockWeights::get().max_block - } - - #[allow(dead_code)] - /// Migrate from unique `u32` reference counting to triple `u32` reference counting. - pub fn migrate_to_dual_ref_count() -> frame_support::weights::Weight { - Account::::translate::<(T::Index, RefCount, T::AccountData), _>(|_key, (nonce, consumers, data)| - Some(AccountInfo { nonce, consumers, providers: 1, sufficients: 0, data }) - ); - T::BlockWeights::get().max_block - } - - /// Migrate from dual `u32` reference counting to triple `u32` reference counting. - pub fn migrate_to_triple_ref_count() -> frame_support::weights::Weight { - Account::::translate::<(T::Index, RefCount, RefCount, T::AccountData), _>( - |_key, (nonce, consumers, providers, data)| { - Some(AccountInfo { nonce, consumers, providers, sufficients: 0, data }) - } - ); - T::BlockWeights::get().max_block - } -} - #[cfg(feature = "std")] impl GenesisConfig { /// Direct implementation of `GenesisBuild::build_storage`. @@ -766,25 +719,6 @@ type EventIndex = u32; /// Type used to encode the number of references an account has. pub type RefCount = u32; -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Index, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} - /// Stores the `spec_version` and `spec_name` of when the last runtime upgrade /// happened. #[derive(sp_runtime::RuntimeDebug, Encode, Decode)] @@ -1023,188 +957,6 @@ pub enum IncRefError { } impl Module { - pub fn account_exists(who: &T::AccountId) -> bool { - Account::::contains_key(who) - } - - /// Increment the reference counter on an account. - #[deprecated = "Use `inc_consumers` instead"] - pub fn inc_ref(who: &T::AccountId) { - let _ = Self::inc_consumers(who); - } - - /// Decrement the reference counter on an account. This *MUST* only be done once for every time - /// you called `inc_consumers` on `who`. - #[deprecated = "Use `dec_consumers` instead"] - pub fn dec_ref(who: &T::AccountId) { - let _ = Self::dec_consumers(who); - } - - /// The number of outstanding references for the account `who`. - #[deprecated = "Use `consumers` instead"] - pub fn refs(who: &T::AccountId) -> RefCount { - Self::consumers(who) - } - - /// True if the account has no outstanding references. - #[deprecated = "Use `!is_provider_required` instead"] - pub fn allow_death(who: &T::AccountId) -> bool { - !Self::is_provider_required(who) - } - - /// Increment the provider reference counter on an account. - pub fn inc_providers(who: &T::AccountId) -> IncRefStatus { - Account::::mutate(who, |a| if a.providers == 0 && a.sufficients == 0 { - // Account is being created. - a.providers = 1; - Self::on_created_account(who.clone(), a); - IncRefStatus::Created - } else { - a.providers = a.providers.saturating_add(1); - IncRefStatus::Existed - }) - } - - /// Decrement the provider reference counter on an account. - /// - /// This *MUST* only be done once for every time you called `inc_providers` on `who`. - pub fn dec_providers(who: &T::AccountId) -> Result { - Account::::try_mutate_exists(who, |maybe_account| { - if let Some(mut account) = maybe_account.take() { - if account.providers == 0 { - // Logic error - cannot decrement beyond zero. - log::error!( - target: "runtime::system", - "Logic error: Unexpected underflow in reducing provider", - ); - account.providers = 1; - } - match (account.providers, account.consumers, account.sufficients) { - (1, 0, 0) => { - // No providers left (and no consumers) and no sufficients. Account dead. - - Module::::on_killed_account(who.clone()); - Ok(DecRefStatus::Reaped) - } - (1, c, _) if c > 0 => { - // Cannot remove last provider if there are consumers. - Err(DecRefError::ConsumerRemaining) - } - (x, _, _) => { - // Account will continue to exist as there is either > 1 provider or - // > 0 sufficients. - account.providers = x - 1; - *maybe_account = Some(account); - Ok(DecRefStatus::Exists) - } - } - } else { - log::error!( - target: "runtime::system", - "Logic error: Account already dead when reducing provider", - ); - Ok(DecRefStatus::Reaped) - } - }) - } - - /// Increment the self-sufficient reference counter on an account. - pub fn inc_sufficients(who: &T::AccountId) -> IncRefStatus { - Account::::mutate(who, |a| if a.providers + a.sufficients == 0 { - // Account is being created. - a.sufficients = 1; - Self::on_created_account(who.clone(), a); - IncRefStatus::Created - } else { - a.sufficients = a.sufficients.saturating_add(1); - IncRefStatus::Existed - }) - } - - /// Decrement the sufficients reference counter on an account. - /// - /// This *MUST* only be done once for every time you called `inc_sufficients` on `who`. - pub fn dec_sufficients(who: &T::AccountId) -> DecRefStatus { - Account::::mutate_exists(who, |maybe_account| { - if let Some(mut account) = maybe_account.take() { - if account.sufficients == 0 { - // Logic error - cannot decrement beyond zero. - log::error!( - target: "runtime::system", - "Logic error: Unexpected underflow in reducing sufficients", - ); - } - match (account.sufficients, account.providers) { - (0, 0) | (1, 0) => { - Module::::on_killed_account(who.clone()); - DecRefStatus::Reaped - } - (x, _) => { - account.sufficients = x - 1; - *maybe_account = Some(account); - DecRefStatus::Exists - } - } - } else { - log::error!( - target: "runtime::system", - "Logic error: Account already dead when reducing provider", - ); - DecRefStatus::Reaped - } - }) - } - - /// The number of outstanding provider references for the account `who`. - pub fn providers(who: &T::AccountId) -> RefCount { - Account::::get(who).providers - } - - /// The number of outstanding sufficient references for the account `who`. - pub fn sufficients(who: &T::AccountId) -> RefCount { - Account::::get(who).sufficients - } - - /// The number of outstanding provider and sufficient references for the account `who`. - pub fn reference_count(who: &T::AccountId) -> RefCount { - let a = Account::::get(who); - a.providers + a.sufficients - } - - /// Increment the reference counter on an account. - /// - /// The account `who`'s `providers` must be non-zero or this will return an error. - pub fn inc_consumers(who: &T::AccountId) -> Result<(), IncRefError> { - Account::::try_mutate(who, |a| if a.providers > 0 { - a.consumers = a.consumers.saturating_add(1); - Ok(()) - } else { - Err(IncRefError::NoProviders) - }) - } - - /// Decrement the reference counter on an account. This *MUST* only be done once for every time - /// you called `inc_consumers` on `who`. - pub fn dec_consumers(who: &T::AccountId) { - Account::::mutate(who, |a| if a.consumers > 0 { - a.consumers -= 1; - } else { - log::error!( - target: "runtime::system", - "Logic error: Unexpected underflow in reducing consumer", - ); - }) - } - - /// The number of outstanding references for the account `who`. - pub fn consumers(who: &T::AccountId) -> RefCount { - Account::::get(who).consumers - } - - /// True if the account has some outstanding references. - pub fn is_provider_required(who: &T::AccountId) -> bool { - Account::::get(who).consumers != 0 - } /// Deposits an event into this block's event record. pub fn deposit_event(event: impl Into) { @@ -1424,16 +1176,6 @@ impl Module { /// Return the chain's current runtime version. pub fn runtime_version() -> RuntimeVersion { T::Version::get() } - /// Retrieve the account transaction counter from storage. - pub fn account_nonce(who: impl EncodeLike) -> T::Index { - Account::::get(who).nonce - } - - /// Increment a particular account's nonce by 1. - pub fn inc_account_nonce(who: impl EncodeLike) { - Account::::mutate(who, |a| a.nonce += T::Index::one()); - } - /// Note what the extrinsic data of the current extrinsic index is. /// /// This is required to be called before applying an extrinsic. The data will used @@ -1476,18 +1218,6 @@ impl Module { ExecutionPhase::::put(Phase::ApplyExtrinsic(0)) } - /// An account is being created. - pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo) { - T::OnNewAccount::on_new_account(&who); - Self::deposit_event(Event::NewAccount(who)); - } - - /// Do anything that needs to be done after an account has been killed. - fn on_killed_account(who: T::AccountId) { - T::OnKilledAccount::on_killed_account(&who); - Self::deposit_event(Event::KilledAccount(who)); - } - /// Determine whether or not it is possible to update the code. /// /// Checks the given code if it is a valid runtime wasm blob by instantianting @@ -1511,50 +1241,6 @@ impl Module { } } -/// Event handler which registers a provider when created. -pub struct Provider(PhantomData); -impl HandleLifetime for Provider { - fn created(t: &T::AccountId) -> Result<(), StoredMapError> { - Module::::inc_providers(t); - Ok(()) - } - fn killed(t: &T::AccountId) -> Result<(), StoredMapError> { - Module::::dec_providers(t) - .map(|_| ()) - .or_else(|e| match e { - DecRefError::ConsumerRemaining => Err(StoredMapError::ConsumerRemaining), - }) - } -} - -/// Event handler which registers a self-sufficient when created. -pub struct SelfSufficient(PhantomData); -impl HandleLifetime for SelfSufficient { - fn created(t: &T::AccountId) -> Result<(), StoredMapError> { - Module::::inc_sufficients(t); - Ok(()) - } - fn killed(t: &T::AccountId) -> Result<(), StoredMapError> { - Module::::dec_sufficients(t); - Ok(()) - } -} - -/// Event handler which registers a consumer when created. -pub struct Consumer(PhantomData); -impl HandleLifetime for Consumer { - fn created(t: &T::AccountId) -> Result<(), StoredMapError> { - Module::::inc_consumers(t) - .map_err(|e| match e { - IncRefError::NoProviders => StoredMapError::NoProviders - }) - } - fn killed(t: &T::AccountId) -> Result<(), StoredMapError> { - Module::::dec_consumers(t); - Ok(()) - } -} - impl BlockNumberProvider for Pallet { type BlockNumber = ::BlockNumber; @@ -1564,47 +1250,6 @@ impl BlockNumberProvider for Pallet } } -fn is_providing(d: &T) -> bool { - d != &T::default() -} - -/// Implement StoredMap for a simple single-item, provide-when-not-default system. This works fine -/// for storing a single item which allows the account to continue existing as long as it's not -/// empty/default. -/// -/// Anything more complex will need more sophisticated logic. -impl StoredMap for Pallet { - fn get(k: &T::AccountId) -> T::AccountData { - Account::::get(k).data - } - - fn try_mutate_exists>( - k: &T::AccountId, - f: impl FnOnce(&mut Option) -> Result, - ) -> Result { - let account = Account::::get(k); - let was_providing = is_providing(&account.data); - let mut some_data = if was_providing { Some(account.data) } else { None }; - let result = f(&mut some_data)?; - let is_providing = some_data.is_some(); - if !was_providing && is_providing { - Self::inc_providers(k); - } else if was_providing && !is_providing { - match Self::dec_providers(k) { - Err(DecRefError::ConsumerRemaining) => Err(StoredMapError::ConsumerRemaining)?, - Ok(DecRefStatus::Reaped) => return Ok(result), - Ok(DecRefStatus::Exists) => { - // Update value as normal... - } - } - } else if !was_providing && !is_providing { - return Ok(result) - } - Account::::mutate(k, |a| a.data = some_data.unwrap_or_default()); - Ok(result) - } -} - /// Split an `option` into two constituent options, as defined by a `splitter` function. pub fn split_inner(option: Option, splitter: impl FnOnce(T) -> (R, S)) -> (Option, Option) @@ -1634,6 +1279,35 @@ impl Lookup for ChainContext { } } +impl BasicAccount for Pallet { + type AccountInfo = T::Index; + + /// Return whether an account exists in storage. + fn account_exists(who: &T::AccountId) -> bool { + Account::::contains_key(who) + } + + /// Return the data for an account + fn get(who: &T::AccountId) -> Self::AccountInfo { + Account::::get(who) + } + + /// Retrieve the account transaction counter from storage. + fn account_nonce(who: &T::AccountId) -> T::Index { + Account::::get(who) + } + + /// Increment a particular account's nonce by 1. + fn inc_account_nonce(who: &T::AccountId) { + Account::::mutate(who, |a| *a += T::Index::one()); + } + + /// Return the storage key for an account. + fn hashed_key_for(who: &T::AccountId) -> Vec { + Account::::hashed_key_for(who) + } +} + /// Prelude to be used alongside pallet macro, for ease of use. pub mod pallet_prelude { pub use crate::{ensure_signed, ensure_none, ensure_root}; diff --git a/frame/system/src/mock.rs b/frame/system/src/mock.rs index 2b31929b5da81..00201c4ce599a 100644 --- a/frame/system/src/mock.rs +++ b/frame/system/src/mock.rs @@ -16,7 +16,6 @@ // limitations under the License. use crate::{self as frame_system, *}; -use sp_std::cell::RefCell; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -75,15 +74,6 @@ parameter_types! { limits::BlockLength::max_with_normal_ratio(1024, NORMAL_DISPATCH_RATIO); } -thread_local!{ - pub static KILLED: RefCell> = RefCell::new(vec![]); -} - -pub struct RecordKilled; -impl OnKilledAccount for RecordKilled { - fn on_killed_account(who: &u64) { KILLED.with(|r| r.borrow_mut().push(*who)) } -} - impl Config for Test { type BaseCallFilter = (); type BlockWeights = RuntimeBlockWeights; @@ -102,11 +92,9 @@ impl Config for Test { type DbWeight = DbWeight; type Version = Version; type PalletInfo = PalletInfo; - type AccountData = u32; - type OnNewAccount = (); - type OnKilledAccount = RecordKilled; type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = System; } pub type SysEvent = frame_system::Event; diff --git a/frame/system/src/offchain.rs b/frame/system/src/offchain.rs index aa8bce966192e..abf57d30727fd 100644 --- a/frame/system/src/offchain.rs +++ b/frame/system/src/offchain.rs @@ -62,8 +62,8 @@ use sp_std::collections::btree_set::BTreeSet; use sp_std::convert::{TryInto, TryFrom}; use sp_std::prelude::{Box, Vec}; use sp_runtime::app_crypto::RuntimeAppPublic; -use sp_runtime::traits::{Extrinsic as ExtrinsicT, IdentifyAccount, One}; -use frame_support::RuntimeDebug; +use sp_runtime::traits::{Extrinsic as ExtrinsicT, IdentifyAccount}; +use frame_support::{RuntimeDebug, traits::BasicAccount}; /// Marker struct used to flag using all supported keys to sign a payload. pub struct ForAll {} @@ -549,18 +549,18 @@ pub trait SendSignedTransaction< account: &Account, call: LocalCall, ) -> Option> { - let mut account_data = crate::Account::::get(&account.id); + let account_nonce = T::AccountStorage::account_nonce(&account.id); log::debug!( target: "runtime::offchain", "Creating signed transaction from account: {:?} (nonce: {:?})", account.id, - account_data.nonce, + account_nonce, ); let (call, signature) = T::create_transaction::( call.into(), account.public.clone(), account.id.clone(), - account_data.nonce + account_nonce, )?; let res = SubmitTransaction:: ::submit_transaction(call, Some(signature)); @@ -568,8 +568,7 @@ pub trait SendSignedTransaction< if res.is_ok() { // increment the nonce. This is fine, since the code should always // be running in off-chain context, so we NEVER persists data. - account_data.nonce += One::one(); - crate::Account::::insert(&account.id, account_data); + T::AccountStorage::inc_account_nonce(&account.id); } Some(res) diff --git a/frame/system/src/tests.rs b/frame/system/src/tests.rs index 9f500e5a3b050..190dd080ca688 100644 --- a/frame/system/src/tests.rs +++ b/frame/system/src/tests.rs @@ -19,7 +19,7 @@ use crate::*; use mock::{*, Origin}; use sp_core::H256; use sp_runtime::{DispatchError, DispatchErrorWithPostInfo, traits::{Header, BlakeTwo256}}; -use frame_support::{assert_noop, weights::WithPostDispatchInfo, dispatch::PostDispatchInfo}; +use frame_support::{assert_ok, weights::WithPostDispatchInfo, dispatch::PostDispatchInfo}; #[test] fn origin_works() { @@ -28,127 +28,6 @@ fn origin_works() { assert_eq!(x.unwrap(), RawOrigin::::Signed(1u64)); } -#[test] -fn stored_map_works() { - new_test_ext().execute_with(|| { - assert!(System::insert(&0, 42).is_ok()); - assert!(!System::is_provider_required(&0)); - - assert_eq!(Account::::get(0), AccountInfo { - nonce: 0, - providers: 1, - consumers: 0, - sufficients: 0, - data: 42, - }); - - assert!(System::inc_consumers(&0).is_ok()); - assert!(System::is_provider_required(&0)); - - assert!(System::insert(&0, 69).is_ok()); - assert!(System::is_provider_required(&0)); - - System::dec_consumers(&0); - assert!(!System::is_provider_required(&0)); - - assert!(KILLED.with(|r| r.borrow().is_empty())); - assert!(System::remove(&0).is_ok()); - assert_eq!(KILLED.with(|r| r.borrow().clone()), vec![0u64]); - }); -} - -#[test] -fn provider_ref_handover_to_self_sufficient_ref_works() { - new_test_ext().execute_with(|| { - assert_eq!(System::inc_providers(&0), IncRefStatus::Created); - System::inc_account_nonce(&0); - assert_eq!(System::account_nonce(&0), 1); - - // a second reference coming and going doesn't change anything. - assert_eq!(System::inc_sufficients(&0), IncRefStatus::Existed); - assert_eq!(System::dec_sufficients(&0), DecRefStatus::Exists); - assert_eq!(System::account_nonce(&0), 1); - - // a provider reference coming and going doesn't change anything. - assert_eq!(System::inc_providers(&0), IncRefStatus::Existed); - assert_eq!(System::dec_providers(&0).unwrap(), DecRefStatus::Exists); - assert_eq!(System::account_nonce(&0), 1); - - // decreasing the providers with a self-sufficient present should not delete the account - assert_eq!(System::inc_sufficients(&0), IncRefStatus::Existed); - assert_eq!(System::dec_providers(&0).unwrap(), DecRefStatus::Exists); - assert_eq!(System::account_nonce(&0), 1); - - // decreasing the sufficients should delete the account - assert_eq!(System::dec_sufficients(&0), DecRefStatus::Reaped); - assert_eq!(System::account_nonce(&0), 0); - }); -} - -#[test] -fn self_sufficient_ref_handover_to_provider_ref_works() { - new_test_ext().execute_with(|| { - assert_eq!(System::inc_sufficients(&0), IncRefStatus::Created); - System::inc_account_nonce(&0); - assert_eq!(System::account_nonce(&0), 1); - - // a second reference coming and going doesn't change anything. - assert_eq!(System::inc_providers(&0), IncRefStatus::Existed); - assert_eq!(System::dec_providers(&0).unwrap(), DecRefStatus::Exists); - assert_eq!(System::account_nonce(&0), 1); - - // a sufficient reference coming and going doesn't change anything. - assert_eq!(System::inc_sufficients(&0), IncRefStatus::Existed); - assert_eq!(System::dec_sufficients(&0), DecRefStatus::Exists); - assert_eq!(System::account_nonce(&0), 1); - - // decreasing the sufficients with a provider present should not delete the account - assert_eq!(System::inc_providers(&0), IncRefStatus::Existed); - assert_eq!(System::dec_sufficients(&0), DecRefStatus::Exists); - assert_eq!(System::account_nonce(&0), 1); - - // decreasing the providers should delete the account - assert_eq!(System::dec_providers(&0).unwrap(), DecRefStatus::Reaped); - assert_eq!(System::account_nonce(&0), 0); - }); -} - -#[test] -fn sufficient_cannot_support_consumer() { - new_test_ext().execute_with(|| { - assert_eq!(System::inc_sufficients(&0), IncRefStatus::Created); - System::inc_account_nonce(&0); - assert_eq!(System::account_nonce(&0), 1); - assert_noop!(System::inc_consumers(&0), IncRefError::NoProviders); - - assert_eq!(System::inc_providers(&0), IncRefStatus::Existed); - assert!(System::inc_consumers(&0).is_ok()); - assert_noop!(System::dec_providers(&0), DecRefError::ConsumerRemaining); - }); -} - -#[test] -fn provider_required_to_support_consumer() { - new_test_ext().execute_with(|| { - assert_noop!(System::inc_consumers(&0), IncRefError::NoProviders); - - assert_eq!(System::inc_providers(&0), IncRefStatus::Created); - System::inc_account_nonce(&0); - assert_eq!(System::account_nonce(&0), 1); - - assert_eq!(System::inc_providers(&0), IncRefStatus::Existed); - assert_eq!(System::dec_providers(&0).unwrap(), DecRefStatus::Exists); - assert_eq!(System::account_nonce(&0), 1); - - assert!(System::inc_consumers(&0).is_ok()); - assert_noop!(System::dec_providers(&0), DecRefError::ConsumerRemaining); - - System::dec_consumers(&0); - assert_eq!(System::dec_providers(&0).unwrap(), DecRefStatus::Reaped); - assert_eq!(System::account_nonce(&0), 0); - }); -} - #[test] fn deposit_event_should_work() { new_test_ext().execute_with(|| { @@ -498,12 +377,11 @@ fn events_not_emitted_during_genesis() { new_test_ext().execute_with(|| { // Block Number is zero at genesis assert!(System::block_number().is_zero()); - let mut account_data = AccountInfo::default(); - System::on_created_account(Default::default(), &mut account_data); + assert_ok!(System::remark_with_event(Origin::signed(1), vec![1,2,3])); assert!(System::events().is_empty()); // Events will be emitted starting on block 1 System::set_block_number(1); - System::on_created_account(Default::default(), &mut account_data); + assert_ok!(System::remark_with_event(Origin::signed(1), vec![1,2,3])); assert!(System::events().len() == 1); }); } diff --git a/frame/timestamp/src/lib.rs b/frame/timestamp/src/lib.rs index 0deef258ed5bd..568d4298eeebf 100644 --- a/frame/timestamp/src/lib.rs +++ b/frame/timestamp/src/lib.rs @@ -347,9 +347,7 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = System; type SystemWeightInfo = (); type SS58Prefix = (); } diff --git a/frame/tips/Cargo.toml b/frame/tips/Cargo.toml index a16c9b91327ec..942b949412000 100644 --- a/frame/tips/Cargo.toml +++ b/frame/tips/Cargo.toml @@ -27,6 +27,7 @@ frame-benchmarking = { version = "3.1.0", default-features = false, path = "../b sp-io ={ version = "3.0.0", path = "../../primitives/io" } sp-core = { version = "3.0.0", path = "../../primitives/core" } sp-storage = { version = "3.0.0", path = "../../primitives/storage" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/tips/src/tests.rs b/frame/tips/src/tests.rs index 413e2dd9437e2..930f39ac3f817 100644 --- a/frame/tips/src/tests.rs +++ b/frame/tips/src/tests.rs @@ -41,6 +41,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Treasury: pallet_treasury::{Module, Call, Storage, Config, Event}, TipsModTestInst: tips::{Module, Call, Storage, Event}, @@ -71,11 +72,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub const ExistentialDeposit: u64 = 1; @@ -86,7 +91,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } thread_local! { diff --git a/frame/transaction-payment/Cargo.toml b/frame/transaction-payment/Cargo.toml index 2a7fbe503efaf..e2b9b9f11e444 100644 --- a/frame/transaction-payment/Cargo.toml +++ b/frame/transaction-payment/Cargo.toml @@ -25,6 +25,7 @@ sp-core = { version = "3.0.0", path = "../../primitives/core", default-features [dev-dependencies] serde_json = "1.0.41" +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } sp-storage = { version = "3.0.0", path = "../../primitives/storage" } diff --git a/frame/transaction-payment/src/lib.rs b/frame/transaction-payment/src/lib.rs index 709a8f69a487d..f04b28cfdc056 100644 --- a/frame/transaction-payment/src/lib.rs +++ b/frame/transaction-payment/src/lib.rs @@ -631,6 +631,7 @@ mod tests { UncheckedExtrinsic = UncheckedExtrinsic, { System: system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, TransactionPayment: pallet_transaction_payment::{Module, Storage}, } @@ -682,24 +683,30 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } + impl pallet_accounts::Config for Runtime { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; + } + parameter_types! { pub const ExistentialDeposit: u64 = 1; } impl pallet_balances::Config for Runtime { + type MaxLocks = (); type Balance = u64; type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type MaxLocks = (); + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } @@ -1160,7 +1167,7 @@ mod tests { })); // Killed Event assert!(System::events().iter().any(|event| { - event.event == Event::system(system::Event::KilledAccount(2)) + event.event == Event::pallet_accounts(pallet_accounts::Event::KilledAccount(2)) })); }); } diff --git a/frame/treasury/Cargo.toml b/frame/treasury/Cargo.toml index da0ffcb725c9b..7bacb771da266 100644 --- a/frame/treasury/Cargo.toml +++ b/frame/treasury/Cargo.toml @@ -19,7 +19,6 @@ sp-std = { version = "3.0.0", default-features = false, path = "../../primitives sp-runtime = { version = "3.0.0", default-features = false, path = "../../primitives/runtime" } frame-support = { version = "3.0.0", default-features = false, path = "../support" } frame-system = { version = "3.0.0", default-features = false, path = "../system" } -pallet-balances = { version = "3.0.0", default-features = false, path = "../balances" } impl-trait-for-tuples = "0.2.1" frame-benchmarking = { version = "3.1.0", default-features = false, path = "../benchmarking", optional = true } @@ -28,6 +27,8 @@ frame-benchmarking = { version = "3.1.0", default-features = false, path = "../b sp-io ={ version = "3.0.0", path = "../../primitives/io" } sp-core = { version = "3.0.0", path = "../../primitives/core" } sp-storage = { version = "3.0.0", path = "../../primitives/storage" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } +pallet-balances = { version = "3.0.0", path = "../balances" } [features] default = ["std"] @@ -38,7 +39,6 @@ std = [ "sp-runtime/std", "frame-support/std", "frame-system/std", - "pallet-balances/std", ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/frame/treasury/src/tests.rs b/frame/treasury/src/tests.rs index 3c70099843ea8..956cd2a56517b 100644 --- a/frame/treasury/src/tests.rs +++ b/frame/treasury/src/tests.rs @@ -44,6 +44,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Treasury: treasury::{Module, Call, Storage, Config, Event}, } @@ -72,11 +73,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub const ExistentialDeposit: u64 = 1; @@ -87,7 +92,8 @@ impl pallet_balances::Config for Test { type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } thread_local! { diff --git a/frame/utility/Cargo.toml b/frame/utility/Cargo.toml index f55cff4d653c5..20875f8437de1 100644 --- a/frame/utility/Cargo.toml +++ b/frame/utility/Cargo.toml @@ -26,6 +26,7 @@ frame-benchmarking = { version = "3.1.0", default-features = false, path = "../b [dev-dependencies] sp-core = { version = "3.0.0", path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } [features] diff --git a/frame/utility/src/tests.rs b/frame/utility/src/tests.rs index af31bbe96cbc4..451fca7e0d6f6 100644 --- a/frame/utility/src/tests.rs +++ b/frame/utility/src/tests.rs @@ -76,6 +76,7 @@ frame_support::construct_runtime!( UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Utility: utility::{Module, Call, Event}, Example: example::{Module, Call}, @@ -105,11 +106,15 @@ impl frame_system::Config for Test { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = Accounts; +} +impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; } parameter_types! { pub const ExistentialDeposit: u64 = 1; @@ -120,7 +125,8 @@ impl pallet_balances::Config for Test { type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } parameter_types! { diff --git a/frame/vesting/Cargo.toml b/frame/vesting/Cargo.toml index e1335237eb508..2d4d968ac5433 100644 --- a/frame/vesting/Cargo.toml +++ b/frame/vesting/Cargo.toml @@ -25,6 +25,7 @@ frame-benchmarking = { version = "3.1.0", default-features = false, path = "../b [dev-dependencies] sp-io = { version = "3.0.0", path = "../../primitives/io" } sp-core = { version = "3.0.0", path = "../../primitives/core" } +pallet-accounts = { version = "3.0.0", path = "../accounts" } pallet-balances = { version = "3.0.0", path = "../balances" } sp-storage = { version = "3.0.0", path = "../../primitives/storage" } hex-literal = "0.3.1" diff --git a/frame/vesting/src/lib.rs b/frame/vesting/src/lib.rs index 9cf9166b37c0c..6c49ac8fb800a 100644 --- a/frame/vesting/src/lib.rs +++ b/frame/vesting/src/lib.rs @@ -409,6 +409,7 @@ mod tests { UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event}, + Accounts: pallet_accounts::{Module, Call, Storage, Event}, Balances: pallet_balances::{Module, Call, Storage, Config, Event}, Vesting: pallet_vesting::{Module, Call, Storage, Event, Config}, } @@ -437,22 +438,27 @@ mod tests { type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); + type AccountStorage = Accounts; type SystemWeightInfo = (); type SS58Prefix = (); } + impl pallet_accounts::Config for Test { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = pallet_balances::AccountData; + } parameter_types! { pub const MaxLocks: u32 = 10; } impl pallet_balances::Config for Test { + type MaxLocks = MaxLocks; type Balance = u64; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type MaxLocks = MaxLocks; + type AccountStore = Accounts; + type ReferencedAccount = Accounts; type WeightInfo = (); } parameter_types! { diff --git a/test-utils/runtime/Cargo.toml b/test-utils/runtime/Cargo.toml index 89da7929e64b8..56cec2156990e 100644 --- a/test-utils/runtime/Cargo.toml +++ b/test-utils/runtime/Cargo.toml @@ -32,6 +32,7 @@ sp-session = { version = "3.0.0", default-features = false, path = "../../primit sp-api = { version = "3.0.0", default-features = false, path = "../../primitives/api" } sp-runtime = { version = "3.0.0", default-features = false, path = "../../primitives/runtime" } pallet-babe = { version = "3.0.0", default-features = false, path = "../../frame/babe" } +pallet-accounts = { version = "3.0.0", default-features = false, path = "../../frame/accounts" } frame-system = { version = "3.0.0", default-features = false, path = "../../frame/system" } frame-system-rpc-runtime-api = { version = "3.0.0", default-features = false, path = "../../frame/system/rpc/runtime-api" } pallet-timestamp = { version = "3.0.0", default-features = false, path = "../../frame/timestamp" } @@ -88,6 +89,7 @@ std = [ "pallet-babe/std", "frame-system-rpc-runtime-api/std", "frame-system/std", + "pallet-accounts/std", "pallet-timestamp/std", "sc-service", "sp-finality-grandpa/std", diff --git a/test-utils/runtime/src/lib.rs b/test-utils/runtime/src/lib.rs index 5f80dc93a95f2..0aad99b3d0275 100644 --- a/test-utils/runtime/src/lib.rs +++ b/test-utils/runtime/src/lib.rs @@ -448,6 +448,12 @@ impl From> for Event { } } +impl From> for Event { + fn from(_evt: pallet_accounts::Event) -> Self { + unimplemented!("Not required in tests!") + } +} + impl frame_support::traits::PalletInfo for Runtime { fn index() -> Option { let type_id = sp_std::any::TypeId::of::

(); @@ -492,6 +498,13 @@ parameter_types! { BlockWeights::with_sensible_defaults(4 * 1024 * 1024, Perbill::from_percent(75)); } +impl pallet_accounts::Config for Runtime { + type Event = Event; + type OnKilledAccount = (); + type OnNewAccount = (); + type AccountData = (); +} + impl frame_system::Config for Runtime { type BaseCallFilter = (); type BlockWeights = RuntimeBlockWeights; @@ -510,11 +523,9 @@ impl frame_system::Config for Runtime { type DbWeight = (); type Version = (); type PalletInfo = Self; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); + type AccountStorage = pallet_accounts::Pallet::; } impl pallet_timestamp::Config for Runtime {