Skip to content

Commit b2a5167

Browse files
committed
fix mock so consistent with implementation using u128 for Balance type. add full rewards test that passes
1 parent 2b90f58 commit b2a5167

File tree

4 files changed

+208
-31
lines changed

4 files changed

+208
-31
lines changed

CONTRIBUTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ cargo +nightly-2021-08-31-aarch64-apple-darwin fmt --all -- --check
349349
* Ans: Because there is a type mismatch, perhaps the first variable requires a `Balance` instead of `u32` in custom_types.json or similar.
350350

351351
* Question: How to debug when running tests?
352-
* Ans: Run tests with this `SKIP_WASM_BUILD=1 RUST_LOG=runtime=debug` in front, i.e. `SKIP_WASM_BUILD=1 RUST_LOG=runtime=debug cargo +nightly-2021-08-31 test -p datahighway-runtime`, and use `println!` where you want to log the output (i.e. `println!("claim duration {:#?}", claim_duration);`), as `debug::info!` not work in tests. Try using `info!` (have not tried yet)
352+
* Ans: Run tests with this `SKIP_WASM_BUILD=1 RUST_LOG=runtime=debug` in front and `-- --nocapture` at the end, i.e. `SKIP_WASM_BUILD=1 RUST_LOG=runtime=debug cargo +nightly-2021-08-31 test -p datahighway-runtime -- --nocapture`, and use `println!` in the implementation where you want to log the output (i.e. `println!("claim duration {:#?}", claim_duration);`), as `debug::info!` not work in tests. It is important that you do a find/replace to comment out all those `println!` statements before you build your code with `cargo build`, otherwise it will give an error message `duplicate lang item in crate`.
353353

354354
* Question: Why can't I connect my node to telemetry?
355355
* Ans: Try use these flags when running your node `--telemetry-url 'wss://telemetry.polkadot.io/submit/ 0' --unsafe-ws-external --unsafe-rpc-external --rpc-cors=all --rpc-methods=Unsafe`

pallets/mining/rewards-allowance/src/lib.rs

Lines changed: 91 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,19 @@ pub mod pallet {
266266
)]
267267
#[pallet::generate_deposit(pub(super) fn deposit_event)]
268268
pub enum Event<T: Config> {
269+
/// Storage of a sending account as a registered DHX miner
270+
/// \[sender]
271+
SetRegisteredDHXMiner(T::AccountId),
272+
273+
/// Storage of the default minimum DHX that must be bonded by each registered DHX miner each day
274+
/// to be eligible for rewards
275+
/// \[amount_dhx, sender\]
276+
SetMinBondedDHXDailyStored(u128, T::AccountId),
277+
278+
/// Storage of the default cooling off period in days
279+
/// \[cooling_off_period_days\]
280+
SetCoolingOffPeriodDaysStored(u32),
281+
269282
/// Storage of the bonded DHX of an account on a specific date by a requesting origin account.
270283
/// \[date, amount_dhx_bonded, account_dhx_bonded, sender\]
271284
SetBondedDHXOfAccountForDateStored(Date, BondedData<T>, T::AccountId, T::AccountId),
@@ -445,7 +458,8 @@ pub mod pallet {
445458
//
446459
// Test with 2x registered miners each with values like `25133000000000000000000u128`, which is over
447460
// half of 5000 DHX daily allowance (of 2500 DHX), but in that case we split the rewards
448-
let mut locks_first_amount_as_u128 = 25133000000000000000000u128;
461+
// (i.e. 25,133 DHX locked at 10:1 gives 2513 DHX reward)
462+
let mut locks_first_amount_as_u128 = 25_133_000_000_000_000_000_000u128;
449463

450464
let locked_vec = <pallet_balances::Pallet<T>>::locks(miner.clone()).into_inner();
451465
if locked_vec.len() != 0 {
@@ -563,6 +577,7 @@ pub mod pallet {
563577
cooling_off_period_days_remaining.1 > 0u32 &&
564578
is_bonding_min_dhx == true
565579
{
580+
// println!("[reducing_days] block: {:#?}, miner: {:#?}, date_start: {:#?} remain_days: {:#?}", _n, miner_count, start_of_requested_date_millis, cooling_off_period_days_remaining);
566581
let old_cooling_off_period_days_remaining = cooling_off_period_days_remaining.1.clone();
567582

568583
// we cannot do this because of error: cannot use the `?` operator in a method that returns `()`
@@ -606,6 +621,18 @@ pub mod pallet {
606621
cooling_off_period_days_remaining.2 == 1u32 &&
607622
is_bonding_min_dhx == true
608623
{
624+
// println!("[eligible] block: {:#?}, miner: {:#?}, date_start: {:#?} remain_days: {:#?}", _n, miner_count, start_of_requested_date_millis, cooling_off_period_days_remaining);
625+
626+
// we need to add that they are eligible for rewards on the current date too
627+
<CoolingOffPeriodDaysRemaining<T>>::insert(
628+
miner.clone(),
629+
(
630+
start_of_requested_date_millis.clone(),
631+
0u32,
632+
1u32,
633+
),
634+
);
635+
609636
// only accumulate the DHX reward for each registered miner once per day
610637
// https://substrate.dev/rustdocs/latest/frame_support/storage/trait.StorageMap.html
611638
if <RewardsAccumulatedDHXForMinerForDate<T>>::contains_key(
@@ -636,7 +663,8 @@ pub mod pallet {
636663
// Divide, handling overflow
637664
let mut daily_reward_for_miner_as_u128 = 0u128;
638665
// note: this rounds down to the nearest integer
639-
let _daily_reward_for_miner_as_u128 = locks_first_amount_as_u128.clone().checked_div(min_bonded_dhx_daily_u128.clone());
666+
let _daily_reward_for_miner_as_u128 = 25_133_000_000_000_000_000_000u128.checked_div(10u128);
667+
// let _daily_reward_for_miner_as_u128 = locks_first_amount_as_u128.clone().checked_div(min_bonded_dhx_daily_u128.clone());
640668
match _daily_reward_for_miner_as_u128 {
641669
None => {
642670
log::error!("Unable to divide min_bonded_dhx_daily from locks_first_amount_as_u128 due to StorageOverflow");
@@ -647,6 +675,7 @@ pub mod pallet {
647675
}
648676
}
649677
log::info!("daily_reward_for_miner_as_u128: {:?}", daily_reward_for_miner_as_u128.clone());
678+
// println!("[eligible] block: {:#?}, miner: {:#?}, date_start: {:#?} daily_reward_for_miner_as_u128: {:#?}", _n, miner_count, start_of_requested_date_millis, daily_reward_for_miner_as_u128);
650679

651680
let daily_reward_for_miner;
652681
let _daily_reward_for_miner = Self::convert_u128_to_balance(daily_reward_for_miner_as_u128.clone());
@@ -669,6 +698,7 @@ pub mod pallet {
669698
log::error!("Unable to retrieve balance for rewards_aggregated_dhx_daily");
670699
}
671700

701+
672702
let rewards_aggregated_dhx_daily_as_u128;
673703
let _rewards_aggregated_dhx_daily_as_u128 = Self::convert_balance_to_u128(rewards_aggregated_dhx_daily.clone());
674704
match _rewards_aggregated_dhx_daily_as_u128.clone() {
@@ -680,7 +710,6 @@ pub mod pallet {
680710
rewards_aggregated_dhx_daily_as_u128 = x;
681711
}
682712
}
683-
log::info!("rewards_aggregated_dhx_daily_as_u128: {:?}", rewards_aggregated_dhx_daily_as_u128.clone());
684713

685714
// Add, handling overflow
686715
let new_rewards_aggregated_dhx_daily_as_u128;
@@ -696,6 +725,9 @@ pub mod pallet {
696725
}
697726
}
698727

728+
log::info!("new_rewards_aggregated_dhx_daily_as_u128: {:?}", new_rewards_aggregated_dhx_daily_as_u128.clone());
729+
// println!("[eligible] block: {:#?}, miner: {:#?}, date_start: {:#?} new_rewards_aggregated_dhx_daily_as_u128: {:#?}", _n, miner_count, start_of_requested_date_millis, new_rewards_aggregated_dhx_daily_as_u128);
730+
699731
let new_rewards_aggregated_dhx_daily;
700732
let _new_rewards_aggregated_dhx_daily = Self::convert_u128_to_balance(new_rewards_aggregated_dhx_daily_as_u128.clone());
701733
match _new_rewards_aggregated_dhx_daily {
@@ -791,6 +823,7 @@ pub mod pallet {
791823
),
792824
);
793825

826+
// println!("[reduce] block: {:#?}, miner: {:#?}, date_start: {:#?} new_cooling_off_period_days_remaining: {:#?}", _n, miner_count, start_of_requested_date_millis, new_cooling_off_period_days_remaining);
794827
log::info!("Unbonded miner. Reducing cooling down period dates remaining {:?} {:?}", miner.clone(), new_cooling_off_period_days_remaining.clone());
795828

796829
// if cooling_off_period_days_remaining.0 is not the start of the current date
@@ -833,6 +866,7 @@ pub mod pallet {
833866
// and still hadn't added to the aggregated rewards for the day
834867
return 0;
835868
}
869+
// println!("[multiplier] block: {:#?}, miner: {:#?}, date_start: {:#?} rewards_aggregated_dhx_daily: {:#?}", _n, miner_count, start_of_requested_date_millis, rewards_aggregated_dhx_daily);
836870

837871
if rewards_aggregated_dhx_daily == 0u32.into() {
838872
log::error!("rewards_aggregated_dhx_daily must be greater than 0 to distribute rewards");
@@ -959,6 +993,7 @@ pub mod pallet {
959993
}
960994
}
961995
log::info!("distribution_multiplier_for_day_fixed128 {:#?}", distribution_multiplier_for_day_fixed128);
996+
// println!("[multiplier] block: {:#?}, miner: {:#?}, date_start: {:#?} distribution_multiplier_for_day_fixed128: {:#?}", _n, miner_count, start_of_requested_date_millis, distribution_multiplier_for_day_fixed128);
962997

963998
// Initialise outside the loop as we need this value after the loop after we finish iterating through all the miners
964999
let mut rewards_allowance_dhx_remaining_today_as_u128 = 0u128;
@@ -1049,6 +1084,8 @@ pub mod pallet {
10491084
return 0;
10501085
}
10511086

1087+
// println!("[rewards] block: {:#?}, miner: {:#?}, date_start: {:#?} restored_proportion_of_daily_reward_for_miner_u128: {:#?}", _n, miner_count, start_of_requested_date_millis, restored_proportion_of_daily_reward_for_miner_u128);
1088+
10521089
let treasury_account_id: T::AccountId = <pallet_treasury::Pallet<T>>::account_id();
10531090
let max_payout = pallet_balances::Pallet::<T>::usable_balance(treasury_account_id.clone());
10541091
log::info!("Treasury account id: {:?}", treasury_account_id.clone());
@@ -1158,6 +1195,8 @@ pub mod pallet {
11581195
new_rewards_allowance_dhx_remaining_today.clone(),
11591196
);
11601197

1198+
// println!("[paid] block: {:#?}, miner: {:#?}, date_start: {:#?} new_rewards_allowance_dhx_remaining_today: {:#?}", _n, miner_count, start_of_requested_date_millis, new_rewards_allowance_dhx_remaining_today);
1199+
11611200
// emit event with reward payment history rather than bloating storage
11621201
Self::deposit_event(Event::TransferredRewardsAllowanceDHXToMinerForDate(
11631202
start_of_requested_date_millis.clone(),
@@ -1198,6 +1237,8 @@ pub mod pallet {
11981237
true
11991238
);
12001239

1240+
// println!("[distributed] block: {:#?}, miner: {:#?}, date_start: {:#?} ", _n, miner_count, start_of_requested_date_millis);
1241+
12011242
Self::deposit_event(Event::DistributedRewardsAllowanceDHXForDate(
12021243
start_of_requested_date_millis.clone(),
12031244
rewards_allowance_dhx_remaining_today.clone(),
@@ -1217,6 +1258,51 @@ pub mod pallet {
12171258
// Dispatchable functions must be annotated with a weight and must return a DispatchResult.
12181259
#[pallet::call]
12191260
impl<T: Config> Pallet<T> {
1261+
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
1262+
pub fn set_registered_dhx_miner(origin: OriginFor<T>) -> DispatchResult {
1263+
let _sender: T::AccountId = ensure_signed(origin)?;
1264+
1265+
<RegisteredDHXMiners<T>>::append(_sender.clone());
1266+
log::info!("register_dhx_miner - account_id: {:?}", &_sender);
1267+
1268+
Self::deposit_event(Event::SetRegisteredDHXMiner(
1269+
_sender.clone(),
1270+
));
1271+
1272+
Ok(())
1273+
}
1274+
1275+
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
1276+
pub fn set_min_bonded_dhx_daily(origin: OriginFor<T>, min_bonded_dhx_daily: BalanceOf<T>) -> DispatchResult {
1277+
let _sender: T::AccountId = ensure_signed(origin)?;
1278+
1279+
let min_bonded_dhx_daily_as_u128 = Self::convert_balance_to_u128(min_bonded_dhx_daily.clone())?;
1280+
1281+
<MinBondedDHXDaily<T>>::put(&min_bonded_dhx_daily.clone());
1282+
log::info!("set_min_bonded_dhx_daily: {:?}", &min_bonded_dhx_daily_as_u128);
1283+
1284+
Self::deposit_event(Event::SetMinBondedDHXDailyStored(
1285+
min_bonded_dhx_daily_as_u128.clone(),
1286+
_sender.clone(),
1287+
));
1288+
1289+
Ok(())
1290+
}
1291+
1292+
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
1293+
pub fn set_cooling_off_period_days(origin: OriginFor<T>, cooling_off_period_days: u32) -> DispatchResult {
1294+
let _sender: T::AccountId = ensure_signed(origin)?;
1295+
1296+
<CoolingOffPeriodDays<T>>::put(&cooling_off_period_days.clone());
1297+
log::info!("cooling_off_period_days: {:?}", &cooling_off_period_days);
1298+
1299+
Self::deposit_event(Event::SetCoolingOffPeriodDaysStored(
1300+
cooling_off_period_days.clone(),
1301+
));
1302+
1303+
Ok(())
1304+
}
1305+
12201306
// customised by governance at any time. this function allows us to change it each year
12211307
// https://docs.google.com/spreadsheets/d/1W2AzOH9Cs9oCR8UYfYCbpmd9X7hp-USbYXL7AuwMY_Q/edit#gid=970997021
12221308
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
@@ -1270,7 +1356,8 @@ pub mod pallet {
12701356
Ok(())
12711357
}
12721358

1273-
// customised by governance at any time
1359+
// TODO: we need to change this in future so it is only modifiable by governance,
1360+
// rather than just any user
12741361
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
12751362
pub fn set_rewards_allowance_dhx_daily(origin: OriginFor<T>, rewards_allowance: BalanceOf<T>) -> DispatchResult {
12761363
let _who = ensure_signed(origin)?;
@@ -1440,7 +1527,6 @@ pub mod pallet {
14401527

14411528
fn convert_u128_to_balance(balance_as_u128: u128) -> Result<BalanceOf<T>, DispatchError> {
14421529
let balance;
1443-
14441530
if let Some(_balance) = TryInto::<BalanceOf<T>>::try_into(balance_as_u128).ok() {
14451531
balance = _balance;
14461532
} else {

pallets/mining/rewards-allowance/src/mock.rs

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,9 @@ pub use module_primitives::{
6161
},
6262
types::{
6363
// AccountId, // Use override below
64-
// Balance, // Use override below
65-
// BlockNumber, // Use override below
64+
Balance,
65+
BlockNumber,
66+
Index,
6667
Moment,
6768
},
6869
};
@@ -97,8 +98,6 @@ frame_support::construct_runtime!(
9798

9899
// Override primitives
99100
pub type AccountId = u128;
100-
pub type Balance = u64;
101-
pub type BlockNumber = u64;
102101
// pub type SysEvent = frame_system::Event<Test>;
103102

104103
pub const MILLISECS_PER_BLOCK: Moment = 4320;
@@ -114,7 +113,7 @@ pub const AYE: Vote = Vote { aye: true, conviction: Conviction::None };
114113
pub const NAY: Vote = Vote { aye: false, conviction: Conviction::None };
115114

116115
parameter_types! {
117-
pub const BlockHashCount: u64 = 250;
116+
pub const BlockHashCount: BlockNumber = 250;
118117
pub BlockWeights: frame_system::limits::BlockWeights =
119118
frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);
120119
}
@@ -125,18 +124,18 @@ impl frame_system::Config for Test {
125124
type DbWeight = ();
126125
type Origin = Origin;
127126
type Call = Call;
128-
type Index = u64;
127+
type Index = Index;
129128
type BlockNumber = BlockNumber;
130129
type Hash = H256;
131130
type Hashing = BlakeTwo256;
132131
type AccountId = AccountId; // u64 is not enough to hold bytes used to generate bounty account
133132
type Lookup = IdentityLookup<Self::AccountId>;
134-
type Header = Header;
133+
type Header = sp_runtime::generic::Header<u32, sp_runtime::traits::BlakeTwo256>;
135134
type Event = ();
136135
type BlockHashCount = ();
137136
type Version = ();
138137
type PalletInfo = PalletInfo;
139-
type AccountData = pallet_balances::AccountData<u64>;
138+
type AccountData = pallet_balances::AccountData<u128>;
140139
type OnNewAccount = ();
141140
type OnKilledAccount = ();
142141
type SystemWeightInfo = ();
@@ -183,21 +182,21 @@ impl pallet_balances::Config for Test {
183182
type MaxLocks = ();
184183
type MaxReserves = ();
185184
type ReserveIdentifier = [u8; 8];
186-
type Balance = u64;
185+
type Balance = Balance;
187186
type DustRemoval = ();
188187
type Event = ();
189188
type ExistentialDeposit = ExistentialDeposit;
190-
type AccountStore = System;
189+
type AccountStore = frame_system::Pallet<Test>;
191190
type WeightInfo = ();
192191
}
193192
parameter_types! {
194-
pub const TransactionByteFee: u64 = 1;
193+
pub const TransactionByteFee: Balance = 1;
195194
}
196195
impl pallet_transaction_payment::Config for Test {
197196
type FeeMultiplierUpdate = ();
198197
type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, ()>;
199198
type TransactionByteFee = TransactionByteFee;
200-
type WeightToFee = IdentityFee<u64>;
199+
type WeightToFee = IdentityFee<Balance>;
201200
}
202201

203202
parameter_types! {
@@ -321,20 +320,20 @@ impl ContainsLengthBound for TenToFourteen {
321320

322321
parameter_types! {
323322
pub const ProposalBond: Permill = Permill::from_percent(5);
324-
pub const ProposalBondMinimum: u64 = 1_000_000_000_000_000_000;
323+
pub const ProposalBondMinimum: Balance = 1_000_000_000_000_000_000;
325324
pub const SpendPeriod: BlockNumber = 1 * DAYS;
326325
pub const Burn: Permill = Permill::from_percent(0);
327326
pub const TipCountdown: BlockNumber = 1;
328327
pub const TipFindersFee: Percent = Percent::from_percent(20);
329-
pub const TipReportDepositBase: u64 = 1_000_000_000_000_000_000;
330-
pub const DataDepositPerByte: u64 = 1;
331-
pub const BountyDepositBase: u64 = 80;
328+
pub const TipReportDepositBase: Balance = 1_000_000_000_000_000_000;
329+
pub const DataDepositPerByte: Balance = 1;
330+
pub const BountyDepositBase: Balance = 80;
332331
pub const BountyDepositPayoutDelay: u32 = 3;
333332
pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry");
334333
pub const BountyUpdatePeriod: u32 = 20;
335334
pub const MaximumReasonLength: u32 = 16384;
336335
pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);
337-
pub const BountyValueMinimum: u64 = 1;
336+
pub const BountyValueMinimum: Balance = 1;
338337
pub const MaxApprovals: u32 = 100;
339338
}
340339

0 commit comments

Comments
 (0)