Skip to content

Commit

Permalink
feat(pallet-dapp-staking): Add V8 to V9 migration with new staking in…
Browse files Browse the repository at this point in the history
…fo structure

- Introduced a migration for `pallet-dapp-staking` to transition from version 8 to version 9.
- Updated `StakerInfo` storage to use the new `NewSingularStakingInfo` structure with a `BonusStatus` field.
- Implemented the `VersionMigrateV8ToV9` migration logic, translating `OldSingularStakingInfo` to `NewSingularStakingInfo`.
- Modified runtime definitions (`astar`, `local`, `shibuya`, `shiden`) to include the V8 to V9 migration in the `Unreleased` migration type.
- Incremented `STORAGE_VERSION` to 9 in `pallet-dapp-staking`.
- Updated benchmarking for `move_stake` to improve setup and maintain consistency.
- Cleaned up extraneous spacing and formatting in benchmarking code.

This commit prepares for a storage migration and introduces enhancements to staking functionalities, enabling support for bonus status tracking.
  • Loading branch information
sylvaincormier committed Nov 23, 2024
1 parent ef3ed20 commit bb84e54
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 18 deletions.
16 changes: 8 additions & 8 deletions pallets/dapp-staking/src/benchmarking/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ mod benchmarks {
#[benchmark]
fn move_stake() {
initial_config::<T>();

// Set up a staker account and required funds
let staker: T::AccountId = whitelisted_caller();
let amount = T::MinimumLockedAmount::get() * 2;
T::BenchmarkHelper::set_balance(&staker, amount);

// Register the source contract
let owner: T::AccountId = account("dapp_owner", 0, SEED);
let from_contract = T::BenchmarkHelper::get_smart_contract(1);
Expand All @@ -65,15 +65,15 @@ mod benchmarks {
owner.clone().into(),
from_contract.clone(),
));

// Register the destination contract
let to_contract = T::BenchmarkHelper::get_smart_contract(2);
assert_ok!(DappStaking::<T>::register(
RawOrigin::Root.into(),
owner.clone().into(),
to_contract.clone(),
));

// Lock funds and stake on source contract
assert_ok!(DappStaking::<T>::lock(
RawOrigin::Signed(staker.clone()).into(),
Expand All @@ -84,25 +84,25 @@ mod benchmarks {
from_contract.clone(),
amount,
));

// Move to build and earn period to ensure move operation has worst case complexity
force_advance_to_next_subperiod::<T>();
assert_eq!(
ActiveProtocolState::<T>::get().subperiod(),
Subperiod::BuildAndEarn,
"Sanity check - we need to be in build&earn period."
);

let move_amount = amount / 2;

#[extrinsic_call]
_(
RawOrigin::Signed(staker.clone()),
from_contract.clone(),
to_contract.clone(),
move_amount,
);

// Verify that an event was emitted
let last_events = dapp_staking_events::<T>();
assert!(!last_events.is_empty(), "No events found");
Expand Down
2 changes: 1 addition & 1 deletion pallets/dapp-staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ pub mod pallet {
use super::*;

/// The current storage version.
pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(8);
pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(9);

#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
Expand Down
87 changes: 85 additions & 2 deletions pallets/dapp-staking/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use frame_support::{
traits::{OnRuntimeUpgrade, UncheckedOnRuntimeUpgrade},
weights::WeightMeter,
};

use frame_support::StorageDoubleMap;
#[cfg(feature = "try-runtime")]
use sp_std::vec::Vec;

Expand All @@ -33,7 +33,13 @@ use sp_runtime::TryRuntimeError;
/// Exports for versioned migration `type`s for this pallet.
pub mod versioned_migrations {
use super::*;

pub type V8ToV9<T> = frame_support::migrations::VersionedMigration<
8,
9,
v9::VersionMigrateV8ToV9<T>,
Pallet<T>,
<T as frame_system::Config>::DbWeight,
>;
/// Migration V6 to V7 wrapped in a [`frame_support::migrations::VersionedMigration`], ensuring
/// the migration is only performed when on-chain version is 6.
pub type V6ToV7<T> = frame_support::migrations::VersionedMigration<
Expand All @@ -56,6 +62,83 @@ pub mod versioned_migrations {
>;
}

pub mod v9 {
use super::*;
use crate::{BonusStatus, Config, Pallet, StakeAmount};

#[derive(Encode, Decode, Clone, Debug)]
pub struct OldSingularStakingInfo {
pub(crate) previous_staked: StakeAmount,
pub(crate) staked: StakeAmount,
pub(crate) loyal_staker: bool,
}

#[derive(Encode, Decode, Clone, Debug)]
pub struct NewSingularStakingInfo {
pub(crate) previous_staked: StakeAmount,
pub(crate) staked: StakeAmount,
pub(crate) bonus_status: BonusStatus,
}

#[storage_alias]
pub type StakerInfo<T: Config> = StorageDoubleMap<
Pallet<T>,
Blake2_128Concat,
<T as frame_system::Config>::AccountId,
Blake2_128Concat,
<T as Config>::SmartContract,
NewSingularStakingInfo, // Changed to NewSingularStakingInfo
OptionQuery,
>;

pub struct VersionMigrateV8ToV9<T>(PhantomData<T>);

impl<T: Config> UncheckedOnRuntimeUpgrade for VersionMigrateV8ToV9<T> {
fn on_runtime_upgrade() -> Weight {
let current = Pallet::<T>::in_code_storage_version();

let mut translated = 0usize;

StakerInfo::<T>::translate(|_account, _contract, old_value: OldSingularStakingInfo| {
translated.saturating_inc();

let bonus_status = if old_value.loyal_staker {
BonusStatus::SafeMovesRemaining(T::MaxBonusMovesPerPeriod::get().into())
} else {
BonusStatus::NoBonus
};

Some(NewSingularStakingInfo {
previous_staked: old_value.previous_staked,
staked: old_value.staked,
bonus_status,
})
});

current.put::<Pallet<T>>();

log::info!("Upgraded {translated} StakerInfo entries to {current:?}");

T::DbWeight::get().reads_writes(1 + translated as u64, 1 + translated as u64)
}

#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
Ok(Vec::new())
}

#[cfg(feature = "try-runtime")]
fn post_upgrade(_: Vec<u8>) -> Result<(), TryRuntimeError> {
ensure!(
Pallet::<T>::on_chain_storage_version() >= 9,
"dapp-staking::migration::v9: Wrong storage version"
);

Ok(())
}
}
}

// TierThreshold as percentage of the total issuance
mod v8 {
use super::*;
Expand Down
3 changes: 2 additions & 1 deletion runtime/astar/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ pub mod xcm_config;
pub type AstarAssetLocationIdConverter = AssetLocationIdConverter<AssetId, XcAssetConfig>;

pub use precompiles::{AstarPrecompiles, ASSET_PRECOMPILE_ADDRESS_PREFIX};
use pallet_dapp_staking::migration::versioned_migrations;
pub type Precompiles = AstarPrecompiles<Runtime, AstarAssetLocationIdConverter>;

use chain_extensions::AstarChainExtensions;
Expand Down Expand Up @@ -1342,7 +1343,7 @@ parameter_types! {
pub type Migrations = (Unreleased, Permanent);

/// Unreleased migrations. Add new ones here:
pub type Unreleased = (cumulus_pallet_xcmp_queue::migration::v5::MigrateV4ToV5<Runtime>,);
pub type Unreleased = (versioned_migrations::V8ToV9<Runtime>,);

/// Migrations/checks that do not need to be versioned and can run on every upgrade.
pub type Permanent = (pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,);
Expand Down
4 changes: 2 additions & 2 deletions runtime/local/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ pub use pallet_timestamp::Call as TimestampCall;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;

use pallet_dapp_staking::migration::versioned_migrations;
#[cfg(feature = "std")]
/// Wasm binary unwrapped. If built with `BUILD_DUMMY_WASM_BINARY`, the function panics.
pub fn wasm_binary_unwrap() -> &'static [u8] {
Expand Down Expand Up @@ -1213,7 +1213,7 @@ pub type Executive = frame_executive::Executive<
Migrations,
>;

pub type Migrations = ();
pub type Migrations = (versioned_migrations::V8ToV9<Runtime>,);

type EventRecord = frame_system::EventRecord<
<Runtime as frame_system::Config>::RuntimeEvent,
Expand Down
4 changes: 2 additions & 2 deletions runtime/shibuya/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ use parachains_common::message_queue::NarrowOriginToSibling;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;

use pallet_dapp_staking::migration::versioned_migrations;
mod chain_extensions;
pub mod genesis_config;
mod precompiles;
Expand Down Expand Up @@ -1659,7 +1659,7 @@ pub type Executive = frame_executive::Executive<
pub type Migrations = (Unreleased, Permanent);

/// Unreleased migrations. Add new ones here:
pub type Unreleased = ();
pub type Unreleased = (versioned_migrations::V8ToV9<Runtime>,);

/// Migrations/checks that do not need to be versioned and can run on every upgrade.
pub type Permanent = (pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,);
Expand Down
4 changes: 2 additions & 2 deletions runtime/shiden/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ pub const MILLISDN: Balance = 1_000 * MICROSDN;
pub const SDN: Balance = 1_000 * MILLISDN;

pub const STORAGE_BYTE_FEE: Balance = 200 * NANOSDN;

use pallet_dapp_staking::migration::versioned_migrations;
/// Charge fee for stored bytes and items.
pub const fn deposit(items: u32, bytes: u32) -> Balance {
items as Balance * MILLISDN + (bytes as Balance) * STORAGE_BYTE_FEE
Expand Down Expand Up @@ -1338,7 +1338,7 @@ parameter_types! {
pub type Migrations = (Unreleased, Permanent);

/// Unreleased migrations. Add new ones here:
pub type Unreleased = ();
pub type Unreleased = (versioned_migrations::V8ToV9<Runtime>,);

/// Migrations/checks that do not need to be versioned and can run on every upgrade.
pub type Permanent = (pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>,);
Expand Down

0 comments on commit bb84e54

Please sign in to comment.