Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mining: add halving logic #528

Merged
merged 1 commit into from
Oct 13, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 63 additions & 5 deletions pallets/phala/src/mining.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ pub mod pallet {
WorkerPublicKey,
};
use sp_core::U256;
use sp_runtime::{traits::AccountIdConversion, SaturatedConversion};
use sp_runtime::{
traits::{AccountIdConversion, One, Zero},
SaturatedConversion,
};
use sp_std::cmp;

use crate::balance_convert::FixedPointConvert;
Expand Down Expand Up @@ -238,6 +241,14 @@ pub mod pallet {
#[pallet::storage]
pub type NextSessionId<T> = StorageValue<_, u32, ValueQuery>;

/// The block number when the mining starts. Used to calculate halving.
#[pallet::storage]
pub type MiningStartBlock<T: Config> = StorageValue<_, T::BlockNumber>;

/// The interval of halving (75% decay) in block number.
#[pallet::storage]
pub type MiningHalvingInterval<T: Config> = StorageValue<_, T::BlockNumber>;

/// The stakes of miner accounts.
///
/// Only presents for mining and cooling down miners.
Expand Down Expand Up @@ -269,6 +280,10 @@ pub mod pallet {
MinerSettled(T::AccountId, u128, u128),
/// Some internal error happened when settling a miner's ledger. \[worker\]
InternalErrorMinerSettleFailed(WorkerPublicKey),
/// Block subsidy halved by 25%
SubsidyBudgetHalved,
/// Some internal error happened when trying to halve the subsidy
InternalErrorWrongHalvingConfigured,
}

#[pallet::error]
Expand Down Expand Up @@ -384,8 +399,18 @@ pub mod pallet {
where
BalanceOf<T>: FixedPointConvert,
{
fn on_finalize(_n: T::BlockNumber) {
fn on_finalize(n: T::BlockNumber) {
Self::heartbeat_challenge();
if let Some(interval) = MiningHalvingInterval::<T>::get() {
let block_elapsed = n - MiningStartBlock::<T>::get().unwrap_or_default();
// Halve when it reaches the last block in an interval
if interval > Zero::zero() && block_elapsed % interval == interval - One::one() {
let r = Self::trigger_subsidy_halving();
if r.is_err() {
Self::deposit_event(Event::<T>::InternalErrorWrongHalvingConfigured);
}
}
}
}

fn on_runtime_upgrade() -> Weight {
Expand All @@ -401,8 +426,11 @@ pub mod pallet {
// Triggers GK RepairV event (again) to rescure the slashed miners due to
// incorrectly applied tokenomic.
w += migrations::repair_v::<T>();
// Khala-only halving parameters
MiningStartBlock::<T>::put(T::BlockNumber::from(414189u32));
MiningHalvingInterval::<T>::put(T::BlockNumber::from(324000u32));
STORAGE_VERSION.put::<super::Pallet<T>>();
w += T::DbWeight::get().writes(1);
w += T::DbWeight::get().writes(3);
}
w
}
Expand Down Expand Up @@ -432,6 +460,16 @@ pub mod pallet {
Self::push_message(SystemEvent::HeartbeatChallenge(seed_info));
}

fn trigger_subsidy_halving() -> Result<(), ()> {
let mut tokenomic = TokenomicParameters::<T>::get().ok_or(())?;
let budget_per_block = FixedPoint::from_bits(tokenomic.budget_per_block);
let new_budget = budget_per_block * fp!(0.75);
tokenomic.budget_per_block = new_budget.to_bits();
Self::update_tokenomic_parameters(tokenomic);
Self::deposit_event(Event::<T>::SubsidyBudgetHalved);
Ok(())
}

pub fn on_mining_message_received(
message: DecodedMessage<MiningReportEvent>,
) -> DispatchResult {
Expand Down Expand Up @@ -1154,6 +1192,7 @@ pub mod pallet {
#[test]
fn test_tokenomic() {
new_test_ext().execute_with(|| {
set_block_1();
let params = TokenomicParameters::<Test>::get().unwrap();
let tokenomic = Tokenomic::<Test>::new(params);
fn pow(x: FixedPoint, n: u32) -> FixedPoint {
Expand Down Expand Up @@ -1209,13 +1248,32 @@ pub mod pallet {
let rho = FixedPoint::from_bits(tokenomic.params.rho);
assert_eq!(pow(rho, HOUR_BLOCKS), fp!(1.00019999999998037056));
// Budget per day
let budger_per_block = FixedPoint::from_bits(tokenomic.params.budget_per_block);
assert_eq!(budger_per_block * 3600 * 24 / 12, fp!(720000));
let budget_per_block = FixedPoint::from_bits(tokenomic.params.budget_per_block);
assert_eq!(budget_per_block * 3600 * 24 / 12, fp!(720000));
// Cost estimation per year
assert_eq!(
tokenomic.op_cost(2000) / 12 * 3600 * 24 * 365,
fp!(171.71874999975847951583)
);
// Subsidy halving to 75%
let _ = take_messages();
let _ = take_events();
assert_ok!(PhalaMining::trigger_subsidy_halving());
let params = TokenomicParameters::<Test>::get().unwrap();
assert_eq!(FixedPoint::from_bits(params.budget_per_block), fp!(75));
assert_ok!(PhalaMining::trigger_subsidy_halving());
let params = TokenomicParameters::<Test>::get().unwrap();
assert_eq!(FixedPoint::from_bits(params.budget_per_block), fp!(56.25));
let msgs = take_messages();
assert_eq!(msgs.len(), 2);
let ev = take_events();
assert_eq!(
ev,
vec![
TestEvent::PhalaMining(Event::<Test>::SubsidyBudgetHalved),
TestEvent::PhalaMining(Event::<Test>::SubsidyBudgetHalved)
]
);
});
}

Expand Down