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

Update Polkadot ideal staking rate #26

Merged
merged 17 commits into from Oct 21, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions relay/polkadot/Cargo.toml
Expand Up @@ -71,6 +71,7 @@ pallet-scheduler = { default-features = false , version = "24.0.0" }
pallet-session = { default-features = false , version = "23.0.0" }
frame-support = { default-features = false , version = "23.0.0" }
pallet-staking = { default-features = false , version = "23.0.0" }
pallet-staking-reward-fn = { default-features = false, version = "14.0.0" }
pallet-staking-reward-curve = { version = "8.0.0" }
pallet-staking-runtime-api = { default-features = false , version = "9.0.0" }
frame-system = { default-features = false , version = "23.0.0" }
Expand Down Expand Up @@ -171,6 +172,7 @@ std = [
"pallet-session-benchmarking?/std",
"pallet-session/std",
"pallet-staking-runtime-api/std",
"pallet-staking-reward-fn/std",
"pallet-staking/std",
"pallet-timestamp/std",
"pallet-tips/std",
Expand Down
130 changes: 115 additions & 15 deletions relay/polkadot/src/lib.rs
Expand Up @@ -115,6 +115,8 @@ use governance::{

pub mod xcm_config;

pub const LOG_TARGET: &'static str = "runtime::polkadot";

impl_runtime_weights!(polkadot_runtime_constants);

// Make the WASM binary available.
Expand Down Expand Up @@ -537,6 +539,54 @@ parameter_types! {
pub const MaxNominations: u32 = <NposCompactSolution16 as frame_election_provider_support::NposSolution>::LIMIT as u32;
}

/// Custom version of `runtime_commong::era_payout` somewhat tailored for Polkadot's crowdloan
/// unlock history. The only tweak should be
///
/// ```diff
/// - let auction_proportion = Perquintill::from_rational(auctioned_slots.min(60), 200u64);
/// + let auction_proportion = Perquintill::from_rational(auctioned_slots.min(60), 300u64);
/// ```
///
/// See <https://forum.polkadot.network/t/adjusting-polkadots-ideal-staking-rate-calculation/3897>.
fn polkadot_era_payout(
ggwpez marked this conversation as resolved.
Show resolved Hide resolved
total_staked: Balance,
total_stakable: Balance,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i also think it would be sensible to peek in on what this value currently is on Polkadot and ensure it makes sense.

max_annual_inflation: Perquintill,
period_fraction: Perquintill,
auctioned_slots: u64,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dont remember the current status, but back when this was originally written, i believe the auctioned slots counter was not exactly correct.

has this logic been updated?

) -> (Balance, Balance) {
use pallet_staking_reward_fn::compute_inflation;
use sp_runtime::traits::Saturating;

let min_annual_inflation = Perquintill::from_rational(25u64, 1000u64);
let delta_annual_inflation = max_annual_inflation.saturating_sub(min_annual_inflation);

// 20% reserved for up to 60 slots.
let auction_proportion = Perquintill::from_rational(auctioned_slots.min(60), 300u64);

// Therefore the ideal amount at stake (as a percentage of total issuance) is 75% less the
// amount that we expect to be taken up with auctions.
let ideal_stake = Perquintill::from_percent(75).saturating_sub(auction_proportion);

let stake = Perquintill::from_rational(total_staked, total_stakable);
let falloff = Perquintill::from_percent(5);
let adjustment = compute_inflation(stake, ideal_stake, falloff);
let staking_inflation =
min_annual_inflation.saturating_add(delta_annual_inflation * adjustment);

let max_payout = period_fraction * max_annual_inflation * total_stakable;
let staking_payout = (period_fraction * staking_inflation) * total_stakable;
let rest = max_payout.saturating_sub(staking_payout);

let other_issuance = total_stakable.saturating_sub(total_staked);
if total_staked > other_issuance {
let _cap_rest = Perquintill::from_rational(other_issuance, total_staked) * staking_payout;
// We don't do anything with this, but if we wanted to, we could introduce a cap on the
// treasury amount with: `rest = rest.min(cap_rest);`
}
(staking_payout, rest)
}

pub struct EraPayout;
impl pallet_staking::EraPayout<Balance> for EraPayout {
fn era_payout(
Expand All @@ -555,7 +605,7 @@ impl pallet_staking::EraPayout<Balance> for EraPayout {
const MAX_ANNUAL_INFLATION: Perquintill = Perquintill::from_percent(10);
const MILLISECONDS_PER_YEAR: u64 = 1000 * 3600 * 24 * 36525 / 100;

runtime_common::impls::era_payout(
polkadot_era_payout(
total_staked,
total_issuance,
MAX_ANNUAL_INFLATION,
Expand Down Expand Up @@ -795,7 +845,7 @@ where
);
let raw_payload = SignedPayload::new(call, extra)
.map_err(|e| {
log::warn!("Unable to create signed payload: {:?}", e);
log::warn!(target: LOG_TARGET, "Unable to create signed payload: {:?}", e);
})
.ok()?;
let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
Expand Down Expand Up @@ -1311,10 +1361,10 @@ impl frame_support::traits::OnRuntimeUpgrade for InitiateNominationPools {
pallet_nomination_pools::MaxPoolMembersPerPool::<Runtime>::put(0);
pallet_nomination_pools::MaxPoolMembers::<Runtime>::put(0);

log::info!(target: "runtime::polkadot", "pools config initiated 🎉");
log::info!(target: LOG_TARGET, "pools config initiated 🎉");
<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 5)
} else {
log::info!(target: "runtime::polkadot", "pools config already initiated 😏");
log::info!(target: LOG_TARGET, "pools config already initiated 😏");
<Runtime as frame_system::Config>::DbWeight::get().reads(1)
}
}
Expand Down Expand Up @@ -2045,7 +2095,7 @@ sp_api::impl_runtime_apis! {
#[cfg(feature = "try-runtime")]
impl frame_try_runtime::TryRuntime<Block> for Runtime {
fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
log::info!("try-runtime::on_runtime_upgrade polkadot.");
log::info!(target: LOG_TARGET, "try-runtime::on_runtime_upgrade polkadot.");
let weight = Executive::try_runtime_upgrade(checks).unwrap();
(weight, BlockWeights::get().max_block)
}
Expand Down Expand Up @@ -2537,21 +2587,15 @@ mod remote_tests {
use super::*;
use frame_try_runtime::{runtime_decl_for_try_runtime::TryRuntime, UpgradeCheckSelect};
use remote_externalities::{
Builder, Mode, OfflineConfig, OnlineConfig, SnapshotConfig, Transport,
Builder, Mode, OfflineConfig, OnlineConfig, RemoteExternalities, SnapshotConfig, Transport,
};
use std::env::var;

#[tokio::test]
async fn run_migrations() {
if var("RUN_MIGRATION_TESTS").is_err() {
return
}

sp_tracing::try_init_simple();
async fn remote_ext_test_setup() -> RemoteExternalities<Block> {
let transport: Transport =
var("WS").unwrap_or("wss://rpc.polkadot.io:443".to_string()).into();
let maybe_state_snapshot: Option<SnapshotConfig> = var("SNAP").map(|s| s.into()).ok();
let mut ext = Builder::<Block>::default()
Builder::<Block>::default()
.mode(if let Some(state_snapshot) = maybe_state_snapshot {
Mode::OfflineOrElseOnline(
OfflineConfig { state_snapshot: state_snapshot.clone() },
Expand All @@ -2566,7 +2610,63 @@ mod remote_tests {
})
.build()
.await
.unwrap();
.unwrap()
}

#[tokio::test]
async fn dispatch_all_proposals() {
if var("RUN_OPENGOV_TEST").is_err() {
return
}

sp_tracing::try_init_simple();
let mut ext = remote_ext_test_setup().await;
ext.execute_with(|| {
type Ref = pallet_referenda::ReferendumInfoOf<Runtime, ()>;
type RefStatus = pallet_referenda::ReferendumStatusOf<Runtime, ()>;
use sp_runtime::traits::Dispatchable;
let all_refs: Vec<(u32, RefStatus)> =
pallet_referenda::ReferendumInfoFor::<Runtime>::iter()
.filter_map(|(idx, reff): (_, Ref)| {
if let Ref::Ongoing(ref_status) = reff {
kianenigma marked this conversation as resolved.
Show resolved Hide resolved
Some((idx, ref_status))
} else {
None
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can eventually clean all the old Referenda, or? Currently they just seem to bloat storage.

}
})
.collect::<Vec<_>>();

for (ref_index, referenda) in all_refs {
log::info!(target: LOG_TARGET, "🚀 executing referenda #{}", ref_index);
let RefStatus { origin, proposal, .. } = referenda;
// we do more or less what the scheduler will do under the hood, as bes tas we can
bkchr marked this conversation as resolved.
Show resolved Hide resolved
// imitate:
let (call, _len) = match <
<Runtime as pallet_scheduler::Config>::Preimages
as
frame_support::traits::QueryPreimage
>::peek(&proposal) {
Ok(x) => x,
Err(e) => {
log::error!(target: LOG_TARGET, "failed to get preimage: {:?}", e);
continue;
}
};

let dispatch_result = call.dispatch(origin.clone().into());
log::info!(target: LOG_TARGET, "outcome of dispatch with origin {:?}: {:?}", origin, dispatch_result);
}
});
}

#[tokio::test]
async fn run_migrations() {
if var("RUN_MIGRATION_TESTS").is_err() {
return
}

sp_tracing::try_init_simple();
let mut ext = remote_ext_test_setup().await;
ext.execute_with(|| Runtime::on_runtime_upgrade(UpgradeCheckSelect::PreAndPost));
}

Expand Down