Skip to content

Commit

Permalink
derive_dev_account helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
runcomet committed Nov 22, 2024
1 parent beb8056 commit e647bca
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 68 deletions.
64 changes: 42 additions & 22 deletions substrate/frame/balances/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -516,11 +516,11 @@ pub mod pallet {

impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
fn default() -> Self {
Self {
Self {
balances: Default::default(),

#[cfg(feature = "runtime-benchmarks")]
dev_accounts: (Default::default(), Default::default(), None),
dev_accounts: (One::one(), <T as Config<I>>::ExistentialDeposit::get(), None),
}
}
}
Expand Down Expand Up @@ -556,28 +556,15 @@ pub mod pallet {
#[cfg(feature = "runtime-benchmarks")]
{
let (num_accounts, balance, ref derivation) = self.dev_accounts;

// Check if `derivation` is `Some` and generate key pair
if let Some(derivation_string) = &derivation {
for index in 0..num_accounts {
// Replace "{}" in the derivation string with the index
let derivation_string = derivation_string.replace("{}", &index.to_string());

// Attempt to create the key pair from the derivation string with error handling
let pair: SrPair = Pair::from_string(&derivation_string, None)
.expect(&format!("Failed to parse derivation string: {}", derivation_string));

// Convert the public key to AccountId
let who = T::AccountId::decode(&mut &pair.public().encode()[..])
.expect(&format!("Failed to decode public key from pair: {}", pair.public()));

frame_system::Pallet::<T>::inc_providers(&who);
// Insert the account into the store and ensure it succeeds
assert!(T::AccountStore::insert(&who, AccountData { free: balance, ..Default::default() })
.is_ok())
}
Pallet::<T, I>::derive_dev_account(num_accounts, balance, derivation_string);
} else {
// `derivation` is None, handle as needed.
log::error!(target: LOG_TARGET, "Derivation string is missing for runtime benchmarks.");
// Derivation string is missing, using default..
let default_derivation = "//Sender/{}".to_string();

Pallet::<T, I>::derive_dev_account(num_accounts, balance, &default_derivation);
}
}

Expand Down Expand Up @@ -1289,5 +1276,38 @@ pub mod pallet {
});
Ok(actual)
}

/// Generate dev account from derivation string.
#[cfg(feature = "runtime-benchmarks")]
pub fn derive_dev_account(num_accounts: u32, balance: T::Balance, derivation: &String) {
// Ensure that the number of accounts is not zero
assert!(num_accounts > 0, "num_accounts must be greater than zero");

assert!(
balance >= <T as Config<I>>::ExistentialDeposit::get(),
"the balance of any account should always be at least the existential deposit.",
);

for index in 0..num_accounts {
// Replace "{}" in the derivation string with the index.
let derivation_string = derivation.replace("{}", &index.to_string());

// Attempt to create the key pair from the derivation string with error handling.
let pair: SrPair = Pair::from_string(&derivation_string, None)
.expect(&format!("Failed to parse derivation string: {}", derivation_string));

// Convert the public key to AccountId.
let who = T::AccountId::decode(&mut &pair.public().encode()[..])
.expect(&format!("Failed to decode public key from pair: {}", pair.public()));

frame_system::Pallet::<T>::inc_providers(&who);
// Insert the account into the store and ensure it succeeds.
assert!(T::AccountStore::insert(
&who,
AccountData { free: balance, ..Default::default() }
)
.is_ok());
}
}
}
}
11 changes: 4 additions & 7 deletions substrate/frame/balances/src/tests/currency_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -721,10 +721,7 @@ fn burn_must_work() {
fn cannot_set_genesis_value_below_ed() {
EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = 11);
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
let _ = crate::GenesisConfig::<Test> {
balances: vec![(1, 10)],
..Default::default()
}
let _ = crate::GenesisConfig::<Test> { balances: vec![(1, 10)], ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();
}
Expand All @@ -733,12 +730,12 @@ fn cannot_set_genesis_value_below_ed() {
#[should_panic = "duplicate balances in genesis."]
fn cannot_set_genesis_value_twice() {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
let _ = crate::GenesisConfig::<Test> {
let _ = crate::GenesisConfig::<Test> {
balances: vec![(1, 10), (2, 20), (1, 15)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
.assimilate_storage(&mut t)
.unwrap();
}

#[test]
Expand Down
82 changes: 43 additions & 39 deletions substrate/frame/balances/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ impl ExtBuilder {
vec![]
},
#[cfg(feature = "runtime-benchmarks")]
dev_accounts: (1000, self.existential_deposit, Some("//Sender/{}".to_string()))
dev_accounts: (1000, self.existential_deposit, Some("//Sender/{}".to_string())),
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down Expand Up @@ -284,45 +284,49 @@ pub fn info_from_weight(w: Weight) -> DispatchInfo {

/// Check that the total-issuance matches the sum of all accounts' total balances.
pub fn ensure_ti_valid() {
let mut sum = 0;

// Fetch the dev accounts from Account Storage.
#[cfg(feature = "runtime-benchmarks")]
let dev_accounts = (1000, EXISTENTIAL_DEPOSIT, "//Sender/{}".to_string()); // You can customize this as needed
#[cfg(feature = "runtime-benchmarks")]
let (num_accounts, _balance, ref derivation) = dev_accounts;

// Generate the dev account public keys.
#[cfg(feature = "runtime-benchmarks")]
let dev_account_ids: Vec<_> = (0..num_accounts)
.map(|index| {
let derivation_string = derivation.replace("{}", &index.to_string());
let pair: SrPair = Pair::from_string(&derivation_string, None).expect("Invalid derivation string");
<crate::tests::Test as frame_system::Config>::AccountId::decode(&mut &pair.public().encode()[..]).unwrap()
})
.collect();

// Iterate over all account keys (i.e., the account IDs).
for acc in frame_system::Account::<Test>::iter_keys() {
// Skip dev accounts by checking if the account is in the dev_account_ids list.
let mut sum = 0;

// Fetch the dev accounts from Account Storage.
#[cfg(feature = "runtime-benchmarks")]
let dev_accounts = (1000, EXISTENTIAL_DEPOSIT, "//Sender/{}".to_string()); // You can customize this as needed
#[cfg(feature = "runtime-benchmarks")]
let (num_accounts, _balance, ref derivation) = dev_accounts;

// Generate the dev account public keys.
#[cfg(feature = "runtime-benchmarks")]
let dev_account_ids: Vec<_> = (0..num_accounts)
.map(|index| {
let derivation_string = derivation.replace("{}", &index.to_string());
let pair: SrPair =
Pair::from_string(&derivation_string, None).expect("Invalid derivation string");
<crate::tests::Test as frame_system::Config>::AccountId::decode(
&mut &pair.public().encode()[..],
)
.unwrap()
})
.collect();

// Iterate over all account keys (i.e., the account IDs).
for acc in frame_system::Account::<Test>::iter_keys() {
// Skip dev accounts by checking if the account is in the dev_account_ids list.
// This also proves dev_accounts exists in storage.
#[cfg(feature = "runtime-benchmarks")]
if dev_account_ids.contains(&acc) {
continue;
}

// Check if we are using the system pallet or some other custom storage for accounts.
if UseSystem::get() {
let data = frame_system::Pallet::<Test>::account(acc);
sum += data.data.total();
} else {
let data = crate::Account::<Test>::get(acc);
sum += data.total();
}
}

// Ensure the total issuance matches the sum of the account balances
assert_eq!(TotalIssuance::<Test>::get(), sum, "Total Issuance is incorrect");
#[cfg(feature = "runtime-benchmarks")]
if dev_account_ids.contains(&acc) {
continue;
}

// Check if we are using the system pallet or some other custom storage for accounts.
if UseSystem::get() {
let data = frame_system::Pallet::<Test>::account(acc);
sum += data.data.total();
} else {
let data = crate::Account::<Test>::get(acc);
sum += data.total();
}
}

// Ensure the total issuance matches the sum of the account balances
assert_eq!(TotalIssuance::<Test>::get(), sum, "Total Issuance is incorrect");
}

#[test]
Expand Down

0 comments on commit e647bca

Please sign in to comment.