From 948b1cade3f6d9f48438a83e50c2a2b93f7b3028 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 23 Sep 2024 08:06:07 +0000 Subject: [PATCH 01/14] Revert "Revert "Identity staking follow up " (#3077)" This reverts commit 7607ebff3b2eaa2901f3552fb1246a87dd509e2e. --- Cargo.lock | 3 + pallets/score-staking/Cargo.toml | 5 + pallets/score-staking/src/lib.rs | 88 ++++++- pallets/score-staking/src/mock.rs | 74 +++++- pallets/score-staking/src/tests.rs | 234 +++++++++++++++--- pallets/score-staking/src/types.rs | 1 + precompiles/score-staking/Cargo.toml | 3 + precompiles/score-staking/src/mock.rs | 61 ++++- precompiles/score-staking/src/tests.rs | 14 +- runtime/litentry/src/lib.rs | 1 + runtime/paseo/src/lib.rs | 1 + runtime/rococo/src/lib.rs | 1 + tee-worker/Cargo.lock | 143 ++++++----- .../app-libs/parentchain-interface/Cargo.toml | 13 +- .../src/integritee/event_filter.rs | 8 +- .../src/integritee/event_handler.rs | 209 ++++++++++++++-- .../src/target_a/event_filter.rs | 6 + .../src/target_a/event_handler.rs | 2 + .../src/target_b/event_filter.rs | 6 + .../src/target_b/event_handler.rs | 2 + .../extrinsics-factory/src/lib.rs | 2 +- .../node-api/metadata/src/lib.rs | 28 ++- .../node-api/metadata/src/metadata_mocks.rs | 32 ++- .../metadata/src/pallet_score_staking.rs | 36 +++ .../core-primitives/storage/src/keys.rs | 14 ++ tee-worker/core-primitives/types/src/lib.rs | 4 +- .../types/src/parentchain/events.rs | 25 ++ .../types/src/parentchain/mod.rs | 16 +- .../indirect-calls-executor/src/executor.rs | 5 +- .../indirect-calls-executor/src/mock.rs | 8 + tee-worker/enclave-runtime/Cargo.lock | 9 + .../src/initialization/global_components.rs | 6 +- .../src/initialization/parentchain/common.rs | 5 +- tee-worker/litentry/primitives/Cargo.toml | 2 + tee-worker/litentry/primitives/src/lib.rs | 1 + 35 files changed, 917 insertions(+), 151 deletions(-) create mode 100644 tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs diff --git a/Cargo.lock b/Cargo.lock index 2140ce3ff0..d02e3dfda6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7449,6 +7449,7 @@ dependencies = [ "pallet-evm", "pallet-parachain-staking", "pallet-score-staking", + "pallet-teebag", "pallet-timestamp", "parity-scale-codec", "precompile-utils", @@ -7942,6 +7943,8 @@ dependencies = [ "num-integer", "pallet-balances", "pallet-parachain-staking", + "pallet-teebag", + "pallet-timestamp", "parity-scale-codec", "scale-info", "serde", diff --git a/pallets/score-staking/Cargo.toml b/pallets/score-staking/Cargo.toml index a4869ecd19..f6c91f9a8d 100644 --- a/pallets/score-staking/Cargo.toml +++ b/pallets/score-staking/Cargo.toml @@ -13,12 +13,14 @@ serde = { workspace = true } frame-benchmarking = { workspace = true, optional = true } frame-support = { workspace = true } frame-system = { workspace = true } +pallet-timestamp = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } sp-std = { workspace = true } core-primitives = { workspace = true } pallet-parachain-staking = { workspace = true } +pallet-teebag = { workspace = true } [dev-dependencies] sp-io = { workspace = true } @@ -42,12 +44,15 @@ std = [ "pallet-balances/std", "core-primitives/std", "pallet-parachain-staking/std", + "pallet-teebag/std", + "pallet-timestamp/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "sp-runtime/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index 9d8b09aa7b..16d947f403 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -114,6 +114,8 @@ pub mod pallet { type AdminOrigin: EnsureOrigin; /// AccountId converter type AccountIdConvert: AccountIdConvert; + // For extrinsics that should only be called by origins from TEE + type TEECallOrigin: EnsureOrigin; } #[pallet::error] @@ -150,20 +152,45 @@ pub mod pallet { ScoreUserCountUnderflow, // when the score user count would exceed `MaxScoreUserCount` MaxScoreUserCountReached, + // the token staking amount has been updated already for the round + TokenStakingAmountAlreadyUpdated, } #[pallet::event] #[pallet::generate_deposit(pub (crate) fn deposit_event)] pub enum Event { - PoolStarted { start_block: BlockNumberFor }, + PoolStarted { + start_block: BlockNumberFor, + }, PoolStopped {}, - ScoreFeederSet { new_score_feeder: Option }, - RoundConfigSet { new_config: RoundSetting }, - ScoreUpdated { who: Identity, new_score: Score }, - ScoreRemoved { who: Identity }, + ScoreFeederSet { + new_score_feeder: Option, + }, + RoundConfigSet { + new_config: RoundSetting, + }, + ScoreUpdated { + who: Identity, + new_score: Score, + }, + ScoreRemoved { + who: Identity, + }, ScoreCleared {}, - RewardCalculated { total: BalanceOf, distributed: BalanceOf }, - RewardClaimed { who: T::AccountId, amount: BalanceOf }, + TokenStakingAmountUpdated { + account: T::AccountId, + amount: BalanceOf, + }, + RewardDistributionStarted { + total: BalanceOf, + distributed: BalanceOf, + round_index: RoundIndex, + }, + RewardDistributionCompleted {}, + RewardClaimed { + who: T::AccountId, + amount: BalanceOf, + }, } #[pallet::storage] @@ -242,7 +269,8 @@ pub mod pallet { // We are about to start a new round // 1. update round info - r.index = r.index.saturating_add(1); + let round_index = r.index.saturating_add(1); + r.index = round_index; r.start_block = now; Round::::put(r); weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); @@ -279,9 +307,10 @@ pub mod pallet { weight = weight.saturating_add(T::DbWeight::get().reads_writes(2, 1)); } - Self::deposit_event(Event::::RewardCalculated { + Self::deposit_event(Event::::RewardDistributionStarted { total: round_reward, distributed: all_user_reward, + round_index, }); weight @@ -445,6 +474,47 @@ pub mod pallet { let payment = Scores::::get(&account).ok_or(Error::::UserNotExist)?; Self::claim(origin, payment.unpaid_reward) } + + #[pallet::call_index(9)] + #[pallet::weight((195_000_000, DispatchClass::Normal))] + pub fn update_token_staking_amount( + origin: OriginFor, + account: T::AccountId, + amount: BalanceOf, + round_index: RoundIndex, + ) -> DispatchResultWithPostInfo { + let _ = T::TEECallOrigin::ensure_origin(origin)?; + + match Scores::::get(&account) { + Some(mut s) => { + if round_index <= s.last_token_distributed_round { + return Err(Error::::TokenStakingAmountAlreadyUpdated.into()); + } + let last_round = Round::::get(); + s.last_round_reward += amount; + s.total_reward += amount; + s.unpaid_reward += amount; + s.last_token_distributed_round = last_round.index; + Scores::::insert(account.clone(), s); + Self::deposit_event(Event::TokenStakingAmountUpdated { + account: account.clone(), + amount, + }); + Ok(Pays::No.into()) + }, + None => Err(Error::::UserNotExist.into()), + } + } + + #[pallet::call_index(10)] + #[pallet::weight((195_000_000, DispatchClass::Normal))] + pub fn complete_reward_distribution(origin: OriginFor) -> DispatchResultWithPostInfo { + let _ = T::TEECallOrigin::ensure_origin(origin)?; + + Self::deposit_event(Event::RewardDistributionCompleted {}); + + Ok(Pays::No.into()) + } } } diff --git a/pallets/score-staking/src/mock.rs b/pallets/score-staking/src/mock.rs index 2463ac0540..d50d8acff3 100644 --- a/pallets/score-staking/src/mock.rs +++ b/pallets/score-staking/src/mock.rs @@ -18,8 +18,11 @@ use crate::{ self as pallet_score_staking, AccountIdConvert, Config, Perbill, PoolState, RoundSetting, }; +use core::marker::PhantomData; use frame_support::{ - assert_ok, construct_runtime, ord_parameter_types, parameter_types, + assert_ok, construct_runtime, ord_parameter_types, + pallet_prelude::EnsureOrigin, + parameter_types, traits::{OnFinalize, OnInitialize}, }; use frame_system::{EnsureRoot, EnsureSignedBy}; @@ -51,6 +54,7 @@ construct_runtime!( Balances: pallet_balances, ParachainStaking: pallet_parachain_staking, ScoreStaking: pallet_score_staking, + Teebag: pallet_teebag, } ); @@ -166,6 +170,66 @@ impl pallet_score_staking::Config for Test { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; + type TEECallOrigin = EnsureEnclaveSigner; +} + +parameter_types! { + pub const MinimumPeriod: u64 = 6000 / 2; +} + +pub type Moment = u64; + +impl pallet_timestamp::Config for Test { + type Moment = Moment; + type OnTimestampSet = (); + type MinimumPeriod = MinimumPeriod; + type WeightInfo = (); +} + +parameter_types! { + pub const MomentsPerDay: u64 = 86_400_000; // [ms/d] +} + +impl pallet_teebag::Config for Test { + type RuntimeEvent = RuntimeEvent; + type MomentsPerDay = MomentsPerDay; + type SetAdminOrigin = EnsureRoot; + type MaxEnclaveIdentifier = ConstU32<1>; + type MaxAuthorizedEnclave = ConstU32<2>; + type WeightInfo = (); +} + +pub struct EnsureEnclaveSigner(PhantomData); +impl EnsureOrigin for EnsureEnclaveSigner +where + T: frame_system::Config + pallet_teebag::Config + pallet_timestamp::Config, + ::AccountId: From<[u8; 32]>, + ::Hash: From<[u8; 32]>, +{ + type Success = T::AccountId; + fn try_origin(o: T::RuntimeOrigin) -> Result { + o.into().and_then(|o| match o { + frame_system::RawOrigin::Signed(who) + if pallet_teebag::EnclaveRegistry::::contains_key(&who) => + { + Ok(who) + }, + r => Err(T::RuntimeOrigin::from(r)), + }) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + use pallet_teebag::test_util::{get_signer, TEST8_MRENCLAVE, TEST8_SIGNER_PUB}; + let signer: ::AccountId = get_signer(TEST8_SIGNER_PUB); + if !pallet_teebag::EnclaveRegistry::::contains_key(signer.clone()) { + assert_ok!(pallet_teebag::Pallet::::add_enclave( + &signer, + &pallet_teebag::Enclave::default().with_mrenclave(TEST8_MRENCLAVE), + )); + } + Ok(frame_system::RawOrigin::Signed(signer).into()) + } } pub fn alice() -> AccountId { @@ -186,6 +250,14 @@ pub fn new_test_ext(fast_round: bool) -> sp_io::TestExternalities { .assimilate_storage(&mut t) .unwrap(); + pallet_teebag::GenesisConfig:: { + allow_sgx_debug_mode: true, + admin: Some(AccountKeyring::Alice.to_account_id()), + mode: pallet_teebag::OperationalMode::Production, + } + .assimilate_storage(&mut t) + .unwrap(); + pallet_score_staking::GenesisConfig:: { state: PoolState::Stopped, marker: Default::default(), diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index 77b87b4dcc..3075fd5400 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -18,8 +18,9 @@ use crate::{mock::*, Error, Event, PoolState, RoundInfo, RoundSetting, ScorePayment, Scores}; use core_primitives::{Identity, DAYS, YEARS}; -use frame_support::{assert_err, assert_ok}; +use frame_support::{assert_err, assert_noop, assert_ok}; use pallet_parachain_staking::{Delegator, OnAllDelegationRemoved}; +use pallet_teebag::{Enclave, WorkerType}; use sp_runtime::Perbill; fn round_reward() -> Balance { @@ -127,10 +128,13 @@ fn default_mint_works() { // run to next reward distribution round run_to_block(7); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: 0, - })); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: 0, + round_index: 2, + }, + )); }); } @@ -165,7 +169,13 @@ fn score_staking_works() { assert_ok!(ScoreStaking::update_score(RuntimeOrigin::signed(alice()), alice().into(), 500)); assert_eq!( ScoreStaking::scores(alice()).unwrap(), - ScorePayment { score: 500, total_reward: 0, last_round_reward: 0, unpaid_reward: 0 } + ScorePayment { + score: 500, + total_reward: 0, + last_round_reward: 0, + unpaid_reward: 0, + last_token_distributed_round: 0 + } ); assert_eq!(ScoreStaking::total_score(), 500); assert_eq!(ScoreStaking::score_user_count(), 1); @@ -181,11 +191,14 @@ fn score_staking_works() { // run to next reward distribution round, alice should win all rewards run_to_block(7); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: round_reward(), - })); - // total reward round 1 + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: round_reward(), + round_index: 2, + }, + )); + // total reward first distribution let mut alice_total_reward = round_reward(); assert_eq!( ScoreStaking::scores(alice()).unwrap(), @@ -194,18 +207,22 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_total_reward, unpaid_reward: alice_total_reward, + last_token_distributed_round: 0, } ); // alice's winning should accumulate run_to_block(12); - // total reward round 2 + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: round_reward(), + round_index: 3, + }, + )); + // total reward second distribution alice_total_reward += round_reward(); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: round_reward(), - })); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -213,6 +230,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward(), unpaid_reward: alice_total_reward, + last_token_distributed_round: 0, } ); @@ -221,13 +239,16 @@ fn score_staking_works() { pallet_parachain_staking::Total::::put(1600); run_to_block(17); - // total reward round 3 + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: calculate_round_reward(2000, 2000, 900, 1600), + round_index: 4, + }, + )); + // total reward third distribution alice_total_reward += calculate_round_reward(2000, 2000, 900, 1600); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: calculate_round_reward(2000, 2000, 900, 1600), - })); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -235,6 +256,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: calculate_round_reward(2000, 2000, 900, 1600), unpaid_reward: alice_total_reward, + last_token_distributed_round: 0, } ); @@ -247,7 +269,7 @@ fn score_staking_works() { assert_eq!(ScoreStaking::score_user_count(), 2); run_to_block(22); - // total rewards round 4 + // total rewards fourth distribution alice_total_reward += calculate_round_reward(2000, 3000, 900, 3200); let mut bob_total_reward = calculate_round_reward(1000, 3000, 1600, 3200); @@ -258,6 +280,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: calculate_round_reward(2000, 3000, 900, 3200), unpaid_reward: alice_total_reward, + last_token_distributed_round: 0, } ); assert_eq!( @@ -267,6 +290,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: bob_total_reward, unpaid_reward: bob_total_reward, + last_token_distributed_round: 0, } ); @@ -288,7 +312,7 @@ fn score_staking_works() { )); run_to_block(25); - // total rewards round 5 + // total rewards fifth distribution alice_total_reward += calculate_round_reward(2000, 3000, 900, 3200); bob_total_reward += calculate_round_reward(1000, 3000, 1600, 3200); @@ -300,7 +324,7 @@ fn score_staking_works() { )); run_to_block(31); - // total reward round 6 + // total reward sixth distribution alice_total_reward += calculate_round_reward(2000, 2000, 900, 900); // remove increased stake (keep only alice's stake) @@ -316,6 +340,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward(), unpaid_reward: alice_total_reward, + last_token_distributed_round: 0, } ); @@ -327,6 +352,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: 0, unpaid_reward: bob_total_reward, + last_token_distributed_round: 0, } ); assert_eq!(ScoreStaking::total_score(), 2000); @@ -360,10 +386,13 @@ fn claim_works() { // run to next reward distribution round, alice should win all rewards run_to_block(7); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: round_reward(), - })); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: round_reward(), + round_index: 2, + }, + )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -371,6 +400,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), + last_token_distributed_round: 0, } ); @@ -386,6 +416,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, + last_token_distributed_round: 0, } ); @@ -401,6 +432,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, + last_token_distributed_round: 0, } ); @@ -412,6 +444,152 @@ fn claim_works() { }); } +#[test] +fn update_token_staking_amount_works() { + new_test_ext_with_parachain_staking().execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + + run_to_block(2); + assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); + + run_to_block(3); + pallet_parachain_staking::DelegatorState::::insert( + alice(), + Delegator::new(bob(), bob(), 900), + ); + pallet_parachain_staking::Total::::put(900); + assert_ok!(ScoreStaking::update_score(RuntimeOrigin::signed(alice()), alice().into(), 500)); + + // run to next reward distribution round, alice should win all rewards + run_to_block(7); + let mut total_reward = round_reward(); + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: total_reward, + distributed: total_reward, + round_index: 2, + }, + )); + + assert_ok!(ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice(), + 1000, + 2, + )); + + total_reward += 1000; + + assert_eq!( + ScoreStaking::scores(alice()).unwrap(), + ScorePayment { + score: 500, + total_reward, + last_round_reward: total_reward, + unpaid_reward: total_reward, + last_token_distributed_round: 2, + } + ); + + run_to_block(12); + + total_reward += round_reward(); + + assert_noop!( + ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice(), + 1000, + 2, + ), + Error::::TokenStakingAmountAlreadyUpdated + ); + + assert_ok!(ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice(), + 1200, + 3, + )); + + total_reward += 1200; + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::TokenStakingAmountUpdated { account: alice(), amount: 1200 }, + )); + + assert_eq!( + ScoreStaking::scores(alice()).unwrap(), + ScorePayment { + score: 500, + total_reward, + last_round_reward: round_reward() + 1200, + unpaid_reward: total_reward, + last_token_distributed_round: 3, + } + ); + }) +} + +#[test] +fn update_token_staking_amount_origin_check_works() { + new_test_ext(false).execute_with(|| { + assert_noop!( + ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice(), + 1000, + 1 + ), + sp_runtime::DispatchError::BadOrigin + ); + }) +} + +#[test] +fn update_token_staking_amount_existing_user_check_works() { + new_test_ext(false).execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + + assert_noop!( + ScoreStaking::update_token_staking_amount( + RuntimeOrigin::signed(alice()), + alice(), + 1000, + 1 + ), + Error::::UserNotExist + ); + }) +} + +#[test] +fn complete_reward_distribution_works() { + new_test_ext(false).execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + + assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()))); + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionCompleted {}, + )); + }); +} + +#[test] +fn complete_reward_distribution_origin_check_works() { + new_test_ext(false).execute_with(|| { + assert_noop!( + ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice())), + sp_runtime::DispatchError::BadOrigin + ); + }); +} + #[test] fn on_all_delegation_removed_works() { new_test_ext(true).execute_with(|| { diff --git a/pallets/score-staking/src/types.rs b/pallets/score-staking/src/types.rs index 1456f4e67d..5b6edda153 100644 --- a/pallets/score-staking/src/types.rs +++ b/pallets/score-staking/src/types.rs @@ -83,4 +83,5 @@ pub struct ScorePayment { pub total_reward: Balance, pub last_round_reward: Balance, pub unpaid_reward: Balance, + pub last_token_distributed_round: RoundIndex, } diff --git a/precompiles/score-staking/Cargo.toml b/precompiles/score-staking/Cargo.toml index e9bc95f33d..0913f0877b 100644 --- a/precompiles/score-staking/Cargo.toml +++ b/precompiles/score-staking/Cargo.toml @@ -6,6 +6,7 @@ version = '0.1.0' [dependencies] pallet-score-staking = { workspace = true } +pallet-teebag = { workspace = true } precompile-utils = { workspace = true } fp-evm = { workspace = true } @@ -38,9 +39,11 @@ std = [ "frame-system/std", "pallet-evm/std", "pallet-score-staking/std", + "pallet-teebag/std", "precompile-utils/std", "sp-core/std", "sp-io/std", "sp-runtime/std", "sp-std/std", ] +runtime-benchmarks = [] diff --git a/precompiles/score-staking/src/mock.rs b/precompiles/score-staking/src/mock.rs index 6c5cbb288c..c127b263d8 100644 --- a/precompiles/score-staking/src/mock.rs +++ b/precompiles/score-staking/src/mock.rs @@ -15,8 +15,11 @@ // along with Litentry. If not, see . use super::*; +use core::marker::PhantomData; use frame_support::{ - assert_ok, construct_runtime, parameter_types, + assert_ok, construct_runtime, + pallet_prelude::EnsureOrigin, + parameter_types, traits::{OnFinalize, OnInitialize}, weights::Weight, }; @@ -43,6 +46,7 @@ construct_runtime!( Evm: pallet_evm, ParachainStaking: pallet_parachain_staking, ScoreStaking: pallet_score_staking, + Teebag: pallet_teebag, } ); @@ -164,6 +168,7 @@ impl pallet_score_staking::Config for Test { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; + type TEECallOrigin = EnsureEnclaveSigner; } pub fn precompile_address() -> H160 { @@ -245,6 +250,52 @@ impl pallet_timestamp::Config for Test { type WeightInfo = (); } +parameter_types! { + pub const MomentsPerDay: u64 = 86_400_000; // [ms/d] +} + +impl pallet_teebag::Config for Test { + type RuntimeEvent = RuntimeEvent; + type MomentsPerDay = MomentsPerDay; + type SetAdminOrigin = EnsureRoot; + type MaxEnclaveIdentifier = ConstU32<1>; + type MaxAuthorizedEnclave = ConstU32<2>; + type WeightInfo = (); +} + +pub struct EnsureEnclaveSigner(PhantomData); +impl EnsureOrigin for EnsureEnclaveSigner +where + T: frame_system::Config + pallet_teebag::Config + pallet_timestamp::Config, + ::AccountId: From<[u8; 32]>, + ::Hash: From<[u8; 32]>, +{ + type Success = T::AccountId; + fn try_origin(o: T::RuntimeOrigin) -> Result { + o.into().and_then(|o| match o { + frame_system::RawOrigin::Signed(who) + if pallet_teebag::EnclaveRegistry::::contains_key(&who) => + { + Ok(who) + }, + r => Err(T::RuntimeOrigin::from(r)), + }) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + use pallet_teebag::test_util::{get_signer, TEST8_MRENCLAVE, TEST8_SIGNER_PUB}; + let signer: ::AccountId = get_signer(TEST8_SIGNER_PUB); + if !pallet_teebag::EnclaveRegistry::::contains_key(signer.clone()) { + assert_ok!(pallet_teebag::Pallet::::add_enclave( + &signer, + &pallet_teebag::Enclave::default().with_mrenclave(TEST8_MRENCLAVE), + )); + } + Ok(frame_system::RawOrigin::Signed(signer).into()) + } +} + pub fn alice() -> AccountId { U8Wrapper(1u8).into() } @@ -259,6 +310,14 @@ pub fn new_test_ext(fast_round: bool) -> sp_io::TestExternalities { .assimilate_storage(&mut t) .unwrap(); + pallet_teebag::GenesisConfig:: { + allow_sgx_debug_mode: true, + admin: Some(alice()), + mode: pallet_teebag::OperationalMode::Production, + } + .assimilate_storage(&mut t) + .unwrap(); + pallet_score_staking::GenesisConfig:: { state: PoolState::Stopped, marker: Default::default(), diff --git a/precompiles/score-staking/src/tests.rs b/precompiles/score-staking/src/tests.rs index b3e61b6e0e..c096c09a73 100644 --- a/precompiles/score-staking/src/tests.rs +++ b/precompiles/score-staking/src/tests.rs @@ -52,10 +52,13 @@ fn claim_is_ok() { // run to next reward distribution round, alice should win all rewards run_to_block(7); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardCalculated { - total: round_reward(), - distributed: round_reward(), - })); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + total: round_reward(), + distributed: round_reward(), + round_index: 2, + }, + )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -63,6 +66,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), + last_token_distributed_round: 0, } ); @@ -86,6 +90,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, + last_token_distributed_round: 0, } ); @@ -109,6 +114,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, + last_token_distributed_round: 0, } ); diff --git a/runtime/litentry/src/lib.rs b/runtime/litentry/src/lib.rs index 4815a5fc21..29171d88d9 100644 --- a/runtime/litentry/src/lib.rs +++ b/runtime/litentry/src/lib.rs @@ -1127,6 +1127,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; + type TEECallOrigin = EnsureEnclaveSigner; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/runtime/paseo/src/lib.rs b/runtime/paseo/src/lib.rs index f80bc095ec..7121e83eb1 100644 --- a/runtime/paseo/src/lib.rs +++ b/runtime/paseo/src/lib.rs @@ -1169,6 +1169,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; + type TEECallOrigin = EnsureEnclaveSigner; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/runtime/rococo/src/lib.rs b/runtime/rococo/src/lib.rs index c875ce5e53..25ed6b2bf7 100644 --- a/runtime/rococo/src/lib.rs +++ b/runtime/rococo/src/lib.rs @@ -1168,6 +1168,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyIssuance = ConstU128<{ 100_000_000 * UNIT }>; type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; + type TEECallOrigin = EnsureEnclaveSigner; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/tee-worker/Cargo.lock b/tee-worker/Cargo.lock index 3f7693cab8..4ffdf6c929 100644 --- a/tee-worker/Cargo.lock +++ b/tee-worker/Cargo.lock @@ -384,7 +384,7 @@ dependencies = [ [[package]] name = "binary-merkle-tree" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -886,7 +886,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "strum 0.26.1", @@ -1837,7 +1837,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -1855,7 +1855,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-runtime-interface", "sp-std 5.0.0", @@ -1900,7 +1900,7 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "frame-benchmarking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-support-procedural", @@ -1914,7 +1914,7 @@ dependencies = [ "sp-api", "sp-application-crypto", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-runtime-interface", "sp-std 5.0.0", @@ -1925,14 +1925,14 @@ dependencies = [ [[package]] name = "frame-executive" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-tracing", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "frame-support" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bitflags 1.3.2", "environmental 1.1.4", @@ -1973,7 +1973,7 @@ dependencies = [ "sp-core", "sp-core-hashing-proc-macro", "sp-inherents", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-staking", "sp-state-machine", @@ -1986,7 +1986,7 @@ dependencies = [ [[package]] name = "frame-support-procedural" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "cfg-expr", @@ -2002,7 +2002,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support-procedural-tools-derive", "proc-macro-crate", @@ -2014,7 +2014,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools-derive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "frame-system" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "log 0.4.20", @@ -2032,7 +2032,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-version", @@ -2944,6 +2944,7 @@ name = "ita-parentchain-interface" version = "0.1.0" dependencies = [ "env_logger 0.9.3", + "frame-support", "ita-sgx-runtime", "ita-stf", "itc-parentchain-indirect-calls-executor", @@ -2953,15 +2954,21 @@ dependencies = [ "itp-node-api", "itp-ocall-api", "itp-sgx-crypto", + "itp-sgx-externalities", "itp-stf-executor", "itp-stf-primitives", + "itp-stf-state-handler", + "itp-storage", "itp-test", "itp-top-pool-author", "itp-types", "lc-dynamic-assertion", "lc-evm-dynamic-assertions", + "lc-parachain-extrinsic-task-sender", + "litentry-hex-utils 0.1.0", "litentry-primitives", "log 0.4.20", + "pallet-identity-management-tee", "parity-scale-codec", "sgx_tstd", "sp-core", @@ -5016,7 +5023,9 @@ dependencies = [ "core-primitives", "hex", "itp-sgx-crypto", + "itp-utils", "log 0.4.20", + "pallet-parachain-staking", "pallet-teebag", "parity-scale-codec", "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -5027,7 +5036,7 @@ dependencies = [ "serde 1.0.204", "sgx_tstd", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -5910,7 +5919,7 @@ checksum = "4d5d9eb14b174ee9aa2ef96dc2b94637a2d4b6e7cb873c7e171f0c20c6cf3eac" [[package]] name = "pallet-assets" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -5925,7 +5934,7 @@ dependencies = [ [[package]] name = "pallet-authorship" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -5939,7 +5948,7 @@ dependencies = [ [[package]] name = "pallet-balances" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -5970,7 +5979,7 @@ dependencies = [ "rlp", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -5995,7 +6004,7 @@ dependencies = [ "rlp", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6013,7 +6022,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6047,14 +6056,14 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", ] [[package]] name = "pallet-session" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -6064,7 +6073,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-session", "sp-staking", @@ -6074,13 +6083,13 @@ dependencies = [ [[package]] name = "pallet-sudo" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", "parity-scale-codec", "scale-info", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6107,7 +6116,7 @@ dependencies = [ "serde 1.0.204", "serde_json 1.0.103", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "x509-cert", @@ -6116,7 +6125,7 @@ dependencies = [ [[package]] name = "pallet-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -6125,7 +6134,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-inherents", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-timestamp", @@ -6134,7 +6143,7 @@ dependencies = [ [[package]] name = "pallet-transaction-payment" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -6142,7 +6151,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -7316,7 +7325,7 @@ dependencies = [ [[package]] name = "sc-keystore" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "array-bytes 4.2.0", "async-trait", @@ -8079,7 +8088,7 @@ dependencies = [ [[package]] name = "sp-api" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -8099,7 +8108,7 @@ dependencies = [ [[package]] name = "sp-api-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "blake2", @@ -8113,20 +8122,20 @@ dependencies = [ [[package]] name = "sp-application-crypto" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-std 5.0.0", ] [[package]] name = "sp-arithmetic" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "integer-sqrt", "num-traits 0.2.16", @@ -8140,7 +8149,7 @@ dependencies = [ [[package]] name = "sp-consensus-grandpa" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "finality-grandpa", "log 0.4.20", @@ -8158,7 +8167,7 @@ dependencies = [ [[package]] name = "sp-consensus-slots" version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8170,7 +8179,7 @@ dependencies = [ [[package]] name = "sp-core" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "array-bytes 4.2.0", "bitflags 1.3.2", @@ -8214,7 +8223,7 @@ dependencies = [ [[package]] name = "sp-core-hashing" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "blake2b_simd", "byteorder 1.4.3", @@ -8243,7 +8252,7 @@ dependencies = [ [[package]] name = "sp-core-hashing-proc-macro" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -8254,7 +8263,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -8264,7 +8273,7 @@ dependencies = [ [[package]] name = "sp-externalities" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "environmental 1.1.4", "parity-scale-codec", @@ -8275,7 +8284,7 @@ dependencies = [ [[package]] name = "sp-inherents" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "impl-trait-for-tuples", @@ -8302,7 +8311,7 @@ dependencies = [ [[package]] name = "sp-io" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bytes 1.4.0", "ed25519", @@ -8328,7 +8337,7 @@ dependencies = [ [[package]] name = "sp-keyring" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "lazy_static", "sp-core", @@ -8339,7 +8348,7 @@ dependencies = [ [[package]] name = "sp-keystore" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "futures 0.3.28", "parity-scale-codec", @@ -8353,7 +8362,7 @@ dependencies = [ [[package]] name = "sp-metadata-ir" version = "0.1.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-metadata", "parity-scale-codec", @@ -8364,7 +8373,7 @@ dependencies = [ [[package]] name = "sp-panic-handler" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "backtrace", "lazy_static", @@ -8374,7 +8383,7 @@ dependencies = [ [[package]] name = "sp-runtime" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "either", "hash256-std-hasher", @@ -8388,7 +8397,7 @@ dependencies = [ "sp-application-crypto", "sp-arithmetic", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-std 5.0.0", "sp-weights", ] @@ -8396,7 +8405,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bytes 1.4.0", "impl-trait-for-tuples", @@ -8414,7 +8423,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "proc-macro-crate", @@ -8426,7 +8435,7 @@ dependencies = [ [[package]] name = "sp-session" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8439,7 +8448,7 @@ dependencies = [ [[package]] name = "sp-staking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8452,7 +8461,7 @@ dependencies = [ [[package]] name = "sp-state-machine" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -8472,7 +8481,7 @@ dependencies = [ [[package]] name = "sp-std" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" [[package]] name = "sp-std" @@ -8483,7 +8492,7 @@ checksum = "af0ee286f98455272f64ac5bb1384ff21ac029fbb669afbaf48477faff12760e" [[package]] name = "sp-storage" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "impl-serde", "parity-scale-codec", @@ -8496,7 +8505,7 @@ dependencies = [ [[package]] name = "sp-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "futures-timer", @@ -8511,7 +8520,7 @@ dependencies = [ [[package]] name = "sp-tracing" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "sp-std 5.0.0", @@ -8523,7 +8532,7 @@ dependencies = [ [[package]] name = "sp-trie" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "ahash 0.8.3", "hash-db 0.16.0", @@ -8546,7 +8555,7 @@ dependencies = [ [[package]] name = "sp-version" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "impl-serde", "parity-scale-codec", @@ -8563,7 +8572,7 @@ dependencies = [ [[package]] name = "sp-version-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "proc-macro2", @@ -8574,7 +8583,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "anyhow", "impl-trait-for-tuples", @@ -8588,7 +8597,7 @@ dependencies = [ [[package]] name = "sp-weights" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", diff --git a/tee-worker/app-libs/parentchain-interface/Cargo.toml b/tee-worker/app-libs/parentchain-interface/Cargo.toml index 46cd6d9f6d..f1ab5fc840 100644 --- a/tee-worker/app-libs/parentchain-interface/Cargo.toml +++ b/tee-worker/app-libs/parentchain-interface/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [dependencies] # sgx dependencies +pallet-identity-management-tee = { path = "../../litentry/pallets/identity-management", default-features = false } sgx_tstd = { branch = "master", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true } # local dependencies @@ -16,9 +17,12 @@ itp-api-client-types = { path = "../../core-primitives/node-api/api-client-types itp-enclave-metrics = { path = "../../core-primitives/enclave-metrics", default-features = false } itp-node-api = { path = "../../core-primitives/node-api", default-features = false } itp-ocall-api = { path = "../../core-primitives/ocall-api", default-features = false } +itp-sgx-externalities = { path = "../../core-primitives/substrate-sgx/externalities", default-features = false } itp-stf-primitives = { path = "../../core-primitives/stf-primitives", default-features = false } +itp-stf-state-handler = { path = "../../core-primitives/stf-state-handler", default-features = false } +itp-storage = { path = "../../core-primitives/storage", default-features = false } itp-types = { path = "../../core-primitives/types", default-features = false } - +lc-parachain-extrinsic-task-sender = { path = "../../litentry/core/parachain-extrinsic-task/sender", default-features = false } # no-std compatible libraries codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } log = { version = "0.4", default-features = false } @@ -26,12 +30,14 @@ log = { version = "0.4", default-features = false } substrate-api-client = { optional = true, default-features = false, features = ["std", "sync-api"], git = "https://github.com/scs/substrate-api-client.git", branch = "polkadot-v0.9.42-tag-v0.14.0" } # substrate dep +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } sp-core = { default-features = false, features = ["full_crypto"], git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } # litentry lc-dynamic-assertion = { path = "../../litentry/core/dynamic-assertion", default-features = false } lc-evm-dynamic-assertions = { path = "../../litentry/core/evm-dynamic-assertions", default-features = false } +litentry-hex-utils = { path = "../../../primitives/hex", default-features = false } litentry-primitives = { path = "../../litentry/primitives", default-features = false } sp-std = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" } @@ -45,7 +51,6 @@ itp-test = { path = "../../core-primitives/test" } itp-top-pool-author = { path = "../../core-primitives/top-pool-author", features = ["mocks"] } itc-parentchain-test = { path = "../../core/parentchain/test" } - [features] default = ["std"] std = [ @@ -59,6 +64,7 @@ std = [ "itp-stf-executor/std", "itp-stf-primitives/std", "itp-top-pool-author/std", + "itp-sgx-externalities/std", "itp-types/std", "log/std", "sp-core/std", @@ -67,6 +73,7 @@ std = [ "litentry-primitives/std", "lc-dynamic-assertion/std", "lc-evm-dynamic-assertions/std", + "lc-parachain-extrinsic-task-sender/std", "sp-std/std", ] sgx = [ @@ -76,8 +83,10 @@ sgx = [ "itp-node-api/sgx", "itp-sgx-crypto/sgx", "itp-stf-executor/sgx", + "itp-sgx-externalities/sgx", "itp-top-pool-author/sgx", "litentry-primitives/sgx", "lc-dynamic-assertion/sgx", "lc-evm-dynamic-assertions/sgx", + "lc-parachain-extrinsic-task-sender/sgx", ] diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_filter.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_filter.rs index 456cebe639..0c15bbdfcc 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_filter.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_filter.rs @@ -25,7 +25,7 @@ use itp_types::{ events::{ ActivateIdentityRequested, AssertionCreated, DeactivateIdentityRequested, EnclaveUnauthorized, LinkIdentityRequested, OpaqueTaskPosted, - ParentchainBlockProcessed, VCRequested, + ParentchainBlockProcessed, RewardDistributionStarted, VCRequested, }, FilterEvents, }, @@ -104,4 +104,10 @@ impl FilterEvents for FilterableEvents { ) -> Result, Self::Error> { self.filter() } + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error> { + self.filter() + } } diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 015cdaee70..c8eb71eb6f 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -16,39 +16,52 @@ */ use codec::{Decode, Encode}; -pub use ita_sgx_runtime::{Balance, Index}; +use frame_support::storage::storage_prefix; +pub use ita_sgx_runtime::{Balance, Index, Runtime}; use ita_stf::{Getter, TrustedCall, TrustedCallSigned}; use itc_parentchain_indirect_calls_executor::error::Error; use itp_api_client_types::StaticEvent; use itp_enclave_metrics::EnclaveMetric; -use itp_ocall_api::EnclaveMetricsOCallApi; +use itp_node_api::metadata::{ + pallet_score_staking::ScoreStakingCallIndexes, provider::AccessNodeMetadata, NodeMetadataTrait, +}; +use itp_ocall_api::{EnclaveMetricsOCallApi, EnclaveOnChainOCallApi}; +use itp_sgx_externalities::{SgxExternalities, SgxExternalitiesTrait}; use itp_stf_primitives::{traits::IndirectExecutor, types::TrustedOperation}; +use itp_stf_state_handler::handle_state::HandleState; +use itp_storage::{key_to_account_id, storage_map_key, StorageHasher}; use itp_types::{ parentchain::{ events::ParentchainBlockProcessed, AccountId, FilterEvents, HandleParentchainEvents, - ParentchainEventProcessingError, ProcessedEventsArtifacts, + ParentchainEventProcessingError, ParentchainId, ProcessedEventsArtifacts, }, - RsaRequest, H256, + Delegator, OpaqueCall, RsaRequest, H256, }; use lc_dynamic_assertion::AssertionLogicRepository; use lc_evm_dynamic_assertions::repository::EvmAssertionRepository; +use lc_parachain_extrinsic_task_sender::{ParachainExtrinsicSender, SendParachainExtrinsic}; +use litentry_hex_utils::decode_hex; use litentry_primitives::{Assertion, Identity, ValidationData, Web3Network}; use log::*; +use pallet_identity_management_tee::IdentityContext; use sp_core::{blake2_256, H160}; +use sp_runtime::traits::Header; use sp_std::vec::Vec; -use std::{format, string::String, sync::Arc, time::Instant}; +use std::{collections::BTreeMap, format, println, string::String, sync::Arc, time::Instant}; -pub struct ParentchainEventHandler -where - MetricsApi: EnclaveMetricsOCallApi, -{ +pub struct ParentchainEventHandler { pub assertion_repository: Arc, - pub metrics_api: Arc, + pub ocall_api: Arc, + pub state_handler: Arc, + pub node_metadata_repository: Arc, } -impl ParentchainEventHandler +impl ParentchainEventHandler where - MetricsApi: EnclaveMetricsOCallApi, + OCallApi: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, + HS: HandleState, + NMR: AccessNodeMetadata, + NMR::MetadataType: NodeMetadataTrait, { fn link_identity>( executor: &Executor, @@ -210,27 +223,169 @@ where .save(id, (byte_code, decrypted_secrets)) .map_err(Error::AssertionCreatedHandling)?; let duration = start_time.elapsed(); - if let Err(e) = self - .metrics_api - .update_metric(EnclaveMetric::DynamicAssertionSaveTime(duration)) + if let Err(e) = + self.ocall_api.update_metric(EnclaveMetric::DynamicAssertionSaveTime(duration)) { warn!("Failed to update DynamicAssertionSaveTime metric with error: {:?}", e); } Ok(()) } + + fn update_staking_scores>( + &self, + executor: &Executor, + block_header: impl Header, + round_index: u32, + ) -> Result<(), Error> { + let scores_key_prefix = storage_prefix(b"ScoreStaking", b"Scores"); + let scores_storage_keys_response = self + .ocall_api + .get_storage_keys(scores_key_prefix.into()) + .map_err(|_| Error::Other("Failed to get storage keys".into()))?; + let scores_storage_keys: Vec> = scores_storage_keys_response + .into_iter() + .filter_map(decode_storage_key) + .collect(); + let account_ids: Vec = + scores_storage_keys.iter().filter_map(key_to_account_id).collect(); + + let delegator_state_storage_keys: Vec> = account_ids + .iter() + .map(|account_id| { + storage_map_key( + "ParachainStaking", + "DelegatorState", + account_id, + &StorageHasher::Blake2_128Concat, + ) + }) + .collect(); + let delegator_states: BTreeMap> = self + .ocall_api + .get_multiple_storages_verified( + delegator_state_storage_keys, + &block_header, + &ParentchainId::Litentry, + ) + .map_err(|_| Error::Other("Failed to get multiple storages".into()))? + .into_iter() + .filter_map(|entry| { + let storage_key = decode_storage_key(entry.key)?; + let account_id = key_to_account_id(&storage_key)?; + let delegator = entry.value?; + Some((account_id, delegator)) + }) + .collect(); + + let id_graphs_storage_keys: Vec> = account_ids + .iter() + .map(|account_id| { + storage_map_key( + "IdentityManagement", + "IDGraphs", + &Identity::from(account_id.clone()), + &StorageHasher::Blake2_128Concat, + ) + }) + .collect(); + + let shard = executor.get_default_shard(); + + let accounts_graphs = self + .state_handler + .execute_on_current(&shard, |state, _| { + let mut id_graphs_accounts: BTreeMap> = BTreeMap::new(); + for id_graph_storage_key in id_graphs_storage_keys.iter() { + let id_graph: Vec<(Identity, IdentityContext)> = state + .iter_prefix::>(id_graph_storage_key) + .unwrap_or_default(); + let graph_accounts: Vec = id_graph + .iter() + .filter_map(|(identity, _)| identity.to_account_id()) + .collect(); + if let Some(account_id) = key_to_account_id(id_graph_storage_key) { + id_graphs_accounts.insert(account_id, graph_accounts); + } + } + + id_graphs_accounts + }) + .map_err(|_| Error::Other("Failed to get id graphs".into()))?; + + let extrinsic_sender = ParachainExtrinsicSender::new(); + + let update_token_staking_amount_call_index = self + .node_metadata_repository + .get_from_metadata(|m| m.update_token_staking_amount_call_indexes()) + .map_err(|_| { + Error::Other( + "Metadata retrieval for update_token_staking_amount_call_indexes failed".into(), + ) + })? + .map_err(|_| Error::Other("Invalid metadata".into()))?; + + for account_id in account_ids.iter() { + let default_id_graph = Vec::new(); + let id_graph = accounts_graphs.get(account_id).unwrap_or(&default_id_graph); + let staking_amount: Balance = id_graph + .iter() + .filter_map(|identity| { + let delegator = delegator_states.get(identity)?; + Some(delegator.total) + }) + .sum(); + let call = OpaqueCall::from_tuple(&( + update_token_staking_amount_call_index, + account_id, + staking_amount, + round_index, + )); + extrinsic_sender + .send(call) + .map_err(|_| Error::Other("Failed to send extrinsic".into()))?; + } + + let complete_reward_distribution_call_index = self + .node_metadata_repository + .get_from_metadata(|m| m.complete_reward_distribution_call_indexes()) + .map_err(|_| { + Error::Other( + "Metadata retrieval for complete_reward_distribution_call_indexes failed" + .into(), + ) + })? + .map_err(|_| Error::Other("Invalid metadata".into()))?; + + let complete_reward_distribution_call = + OpaqueCall::from_tuple(&(complete_reward_distribution_call_index.clone())); + extrinsic_sender.send(complete_reward_distribution_call).map_err(|_| { + Error::Other("Failed to send complete_reward_distribution_call extrinsic".into()) + })?; + + Ok(()) + } +} + +fn decode_storage_key(raw_key: Vec) -> Option> { + let hex_key = String::decode(&mut raw_key.as_slice()).unwrap_or_default(); + decode_hex(hex_key).ok() } -impl HandleParentchainEvents - for ParentchainEventHandler +impl HandleParentchainEvents + for ParentchainEventHandler where Executor: IndirectExecutor, - MetricsApi: EnclaveMetricsOCallApi, + OCallApi: EnclaveOnChainOCallApi + EnclaveMetricsOCallApi, + HS: HandleState, + NMR: AccessNodeMetadata, + NMR::MetadataType: NodeMetadataTrait, { fn handle_events( &self, executor: &Executor, events: impl FilterEvents, + block_header: impl Header, ) -> Result { let mut handled_events: Vec = Vec::new(); let mut successful_assertion_ids: Vec = Vec::new(); @@ -349,6 +504,24 @@ where }); } + if let Ok(events) = events.get_reward_distribution_started_events() { + println!("Handling RewardDistributionStarted events"); + events + .iter() + .try_for_each(|event| { + let event_hash = hash_of(&event); + let result = self.update_staking_scores( + executor, + block_header.clone(), + event.round_index, + ); + handled_events.push(event_hash); + + result + }) + .map_err(|_| ParentchainEventProcessingError::RewardDistributionStartedFailure)?; + } + Ok((handled_events, successful_assertion_ids, failed_assertion_ids)) } } diff --git a/tee-worker/app-libs/parentchain-interface/src/target_a/event_filter.rs b/tee-worker/app-libs/parentchain-interface/src/target_a/event_filter.rs index 2490b2e1d9..8209b16a18 100644 --- a/tee-worker/app-libs/parentchain-interface/src/target_a/event_filter.rs +++ b/tee-worker/app-libs/parentchain-interface/src/target_a/event_filter.rs @@ -105,4 +105,10 @@ impl FilterEvents for FilterableEvents { ) -> Result, Self::Error> { Ok(Vec::new()) } + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error> { + Ok(Vec::new()) + } } diff --git a/tee-worker/app-libs/parentchain-interface/src/target_a/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/target_a/event_handler.rs index af091e98f8..a73312c63e 100644 --- a/tee-worker/app-libs/parentchain-interface/src/target_a/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/target_a/event_handler.rs @@ -22,6 +22,7 @@ use itc_parentchain_indirect_calls_executor::error::Error; use itp_stf_primitives::traits::IndirectExecutor; use itp_types::parentchain::{FilterEvents, HandleParentchainEvents, ProcessedEventsArtifacts}; use log::*; +use sp_runtime::traits::Header; use sp_std::vec::Vec; pub struct ParentchainEventHandler {} @@ -35,6 +36,7 @@ where &self, _executor: &Executor, _events: impl FilterEvents, + _block_header: impl Header, ) -> Result { debug!("not handling any events for target a"); Ok((Vec::new(), Vec::new(), Vec::new())) diff --git a/tee-worker/app-libs/parentchain-interface/src/target_b/event_filter.rs b/tee-worker/app-libs/parentchain-interface/src/target_b/event_filter.rs index 2490b2e1d9..8209b16a18 100644 --- a/tee-worker/app-libs/parentchain-interface/src/target_b/event_filter.rs +++ b/tee-worker/app-libs/parentchain-interface/src/target_b/event_filter.rs @@ -105,4 +105,10 @@ impl FilterEvents for FilterableEvents { ) -> Result, Self::Error> { Ok(Vec::new()) } + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error> { + Ok(Vec::new()) + } } diff --git a/tee-worker/app-libs/parentchain-interface/src/target_b/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/target_b/event_handler.rs index 56151a9ccc..ce279228bf 100644 --- a/tee-worker/app-libs/parentchain-interface/src/target_b/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/target_b/event_handler.rs @@ -22,6 +22,7 @@ use itc_parentchain_indirect_calls_executor::error::Error; use itp_stf_primitives::traits::IndirectExecutor; use itp_types::parentchain::{FilterEvents, HandleParentchainEvents, ProcessedEventsArtifacts}; use log::*; +use sp_runtime::traits::Header; use sp_std::vec::Vec; pub struct ParentchainEventHandler {} @@ -35,6 +36,7 @@ where &self, _executor: &Executor, _events: impl FilterEvents, + _block_header: impl Header, ) -> Result { debug!("not handling any events for target B"); Ok((Vec::new(), Vec::new(), Vec::new())) diff --git a/tee-worker/core-primitives/extrinsics-factory/src/lib.rs b/tee-worker/core-primitives/extrinsics-factory/src/lib.rs index ab58d65853..f869917b27 100644 --- a/tee-worker/core-primitives/extrinsics-factory/src/lib.rs +++ b/tee-worker/core-primitives/extrinsics-factory/src/lib.rs @@ -35,7 +35,7 @@ use itp_node_api::{ api_client::{ ExtrinsicParams, ParentchainAdditionalParams, ParentchainExtrinsicParams, SignExtrinsic, }, - metadata::{provider::AccessNodeMetadata, NodeMetadata}, + metadata::{provider::AccessNodeMetadata, NodeMetadata, NodeMetadataProvider}, }; use itp_nonce_cache::{MutateNonce, Nonce}; use itp_types::{parentchain::AccountId, OpaqueCall}; diff --git a/tee-worker/core-primitives/node-api/metadata/src/lib.rs b/tee-worker/core-primitives/node-api/metadata/src/lib.rs index 1705582b90..5625e77ed1 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/lib.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/lib.rs @@ -22,9 +22,10 @@ use crate::{ error::Result, pallet_balances::BalancesCallIndexes, pallet_evm_assertion::EvmAssertionsCallIndexes, pallet_imp::IMPCallIndexes, - pallet_proxy::ProxyCallIndexes, pallet_system::SystemConstants, - pallet_teebag::TeebagCallIndexes, pallet_timestamp::TimestampCallIndexes, - pallet_utility::UtilityCallIndexes, pallet_vcmp::VCMPCallIndexes, + pallet_proxy::ProxyCallIndexes, pallet_score_staking::ScoreStakingCallIndexes, + pallet_system::SystemConstants, pallet_teebag::TeebagCallIndexes, + pallet_timestamp::TimestampCallIndexes, pallet_utility::UtilityCallIndexes, + pallet_vcmp::VCMPCallIndexes, }; use codec::{Decode, Encode}; use sp_core::storage::StorageKey; @@ -37,6 +38,7 @@ pub mod pallet_balances; pub mod pallet_evm_assertion; pub mod pallet_imp; pub mod pallet_proxy; +pub mod pallet_score_staking; pub mod pallet_system; pub mod pallet_teebag; pub mod pallet_utility; @@ -48,6 +50,10 @@ pub mod pallet_timestamp; #[cfg(feature = "mocks")] pub mod metadata_mocks; +pub trait NodeMetadataProvider { + fn get_metadata(&self) -> Option<&Metadata>; +} + pub trait NodeMetadataTrait: TeebagCallIndexes + IMPCallIndexes @@ -58,6 +64,8 @@ pub trait NodeMetadataTrait: + BalancesCallIndexes + TimestampCallIndexes + EvmAssertionsCallIndexes + + ScoreStakingCallIndexes + + NodeMetadataProvider { } @@ -70,7 +78,9 @@ impl< + ProxyCallIndexes + BalancesCallIndexes + TimestampCallIndexes - + EvmAssertionsCallIndexes, + + EvmAssertionsCallIndexes + + ScoreStakingCallIndexes + + NodeMetadataProvider, > NodeMetadataTrait for T { } @@ -103,10 +113,6 @@ impl NodeMetadata { } } - pub fn get_metadata(&self) -> Option<&Metadata> { - self.node_metadata.as_ref() - } - /// Return the substrate chain runtime version. pub fn get_runtime_version(&self) -> u32 { self.runtime_spec_version @@ -181,3 +187,9 @@ impl NodeMetadata { } } } + +impl NodeMetadataProvider for NodeMetadata { + fn get_metadata(&self) -> Option<&Metadata> { + self.node_metadata.as_ref() + } +} diff --git a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs index adf13c8cf8..a4461eb72a 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs @@ -18,9 +18,10 @@ use crate::{ error::Result, pallet_balances::BalancesCallIndexes, pallet_evm_assertion::EvmAssertionsCallIndexes, pallet_imp::IMPCallIndexes, - pallet_proxy::ProxyCallIndexes, pallet_system::SystemConstants, - pallet_teebag::TeebagCallIndexes, pallet_timestamp::TimestampCallIndexes, - pallet_utility::UtilityCallIndexes, pallet_vcmp::VCMPCallIndexes, runtime_call::RuntimeCall, + pallet_proxy::ProxyCallIndexes, pallet_score_staking::ScoreStakingCallIndexes, + pallet_system::SystemConstants, pallet_teebag::TeebagCallIndexes, + pallet_timestamp::TimestampCallIndexes, pallet_utility::UtilityCallIndexes, + pallet_vcmp::VCMPCallIndexes, runtime_call::RuntimeCall, NodeMetadataProvider, }; use codec::{Decode, Encode}; @@ -88,6 +89,11 @@ pub struct NodeMetadataMock { timestamp_set: u8, runtime_spec_version: u32, runtime_transaction_version: u32, + + //ScoreStaking + score_staking_module: u8, + update_token_staking_amount: u8, + complete_reward_distribution: u8, } impl NodeMetadataMock { @@ -143,6 +149,10 @@ impl NodeMetadataMock { timestamp_set: 0, runtime_spec_version: 25, runtime_transaction_version: 4, + + score_staking_module: 100u8, + update_token_staking_amount: 0u8, + complete_reward_distribution: 1u8, } } } @@ -177,6 +187,16 @@ impl TeebagCallIndexes for NodeMetadataMock { } } +impl ScoreStakingCallIndexes for NodeMetadataMock { + fn update_token_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { + Ok([self.score_staking_module, self.update_token_staking_amount]) + } + + fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]> { + Ok([self.score_staking_module, self.complete_reward_distribution]) + } +} + impl IMPCallIndexes for NodeMetadataMock { fn link_identity_call_indexes(&self) -> Result<[u8; 2]> { Ok([self.imp_module, self.imp_link_identity]) @@ -310,3 +330,9 @@ impl EvmAssertionsCallIndexes for NodeMetadataMock { Ok([self.evm_assertions_module, self.evm_assertions_void_assertion]) } } + +impl NodeMetadataProvider for NodeMetadataMock { + fn get_metadata(&self) -> Option<&Metadata> { + None + } +} diff --git a/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs b/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs new file mode 100644 index 0000000000..9450e36c01 --- /dev/null +++ b/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs @@ -0,0 +1,36 @@ +/* + Copyright 2021 Integritee AG and Supercomputing Systems AG + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ +use crate::{error::Result, NodeMetadata}; + +/// Pallet' name: +pub const SCORE_STAKING: &str = "ScoreStaking"; + +// we only list the extrinsics that we care +pub trait ScoreStakingCallIndexes { + fn update_token_staking_amount_call_indexes(&self) -> Result<[u8; 2]>; + + fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]>; +} + +impl ScoreStakingCallIndexes for NodeMetadata { + fn update_token_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { + self.call_indexes(SCORE_STAKING, "update_token_staking_amount") + } + fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]> { + self.call_indexes(SCORE_STAKING, "complete_reward_distribution") + } +} diff --git a/tee-worker/core-primitives/storage/src/keys.rs b/tee-worker/core-primitives/storage/src/keys.rs index 43de4f667e..c4767097d7 100644 --- a/tee-worker/core-primitives/storage/src/keys.rs +++ b/tee-worker/core-primitives/storage/src/keys.rs @@ -17,6 +17,7 @@ use codec::Encode; use frame_metadata::v14::StorageHasher; +use sp_core::crypto::AccountId32 as AccountId; use sp_std::vec::Vec; pub fn storage_value_key(module_prefix: &str, storage_prefix: &str) -> Vec { @@ -69,3 +70,16 @@ fn key_hash(key: &K, hasher: &StorageHasher) -> Vec { StorageHasher::Twox64Concat => sp_core::twox_64(&encoded_key).to_vec(), } } + +/// Extracts the AccountId from a storage key +pub fn key_to_account_id(key: &Vec) -> Option { + if key.len() >= 32 { + let account_id_bytes = &key[key.len() - 32..]; + let mut account_id_32_bytes = [0; 32]; + account_id_32_bytes.copy_from_slice(account_id_bytes); + + Some(AccountId::new(account_id_32_bytes)) + } else { + None + } +} diff --git a/tee-worker/core-primitives/types/src/lib.rs b/tee-worker/core-primitives/types/src/lib.rs index a4d58a2969..35c31f1f18 100644 --- a/tee-worker/core-primitives/types/src/lib.rs +++ b/tee-worker/core-primitives/types/src/lib.rs @@ -29,8 +29,8 @@ pub mod storage; pub use itp_sgx_runtime_primitives::types::*; pub use litentry_primitives::{ - Assertion, AttestationType, DcapProvider, DecryptableRequest, Enclave, EnclaveFingerprint, - MrEnclave, SidechainBlockNumber, WorkerType, + Assertion, AttestationType, DcapProvider, DecryptableRequest, Delegator, Enclave, + EnclaveFingerprint, MrEnclave, SidechainBlockNumber, WorkerType, }; pub use sp_core::{crypto::AccountId32 as AccountId, H256}; diff --git a/tee-worker/core-primitives/types/src/parentchain/events.rs b/tee-worker/core-primitives/types/src/parentchain/events.rs index f6b40d1339..3cce6e2e10 100644 --- a/tee-worker/core-primitives/types/src/parentchain/events.rs +++ b/tee-worker/core-primitives/types/src/parentchain/events.rs @@ -244,3 +244,28 @@ impl StaticEvent for AssertionCreated { const PALLET: &'static str = "EvmAssertions"; const EVENT: &'static str = "AssertionCreated"; } + +#[derive(Encode, Decode, Debug)] +pub struct RewardDistributionStarted { + pub total: Balance, + pub distributed: Balance, + pub round_index: u32, +} + +impl core::fmt::Display for RewardDistributionStarted { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + let message = format!( + "{:?} :: total: {}, distributed: {}, round_index: {}", + RewardDistributionStarted::EVENT, + self.total, + self.distributed, + self.round_index + ); + write!(f, "{}", message) + } +} + +impl StaticEvent for RewardDistributionStarted { + const PALLET: &'static str = "ScoreStaking"; + const EVENT: &'static str = "RewardDistributionStarted"; +} diff --git a/tee-worker/core-primitives/types/src/parentchain/mod.rs b/tee-worker/core-primitives/types/src/parentchain/mod.rs index 723127eafa..34bd9f24fa 100644 --- a/tee-worker/core-primitives/types/src/parentchain/mod.rs +++ b/tee-worker/core-primitives/types/src/parentchain/mod.rs @@ -23,13 +23,17 @@ use codec::{Decode, Encode}; use core::fmt::Debug; use events::{ ActivateIdentityRequested, DeactivateIdentityRequested, EnclaveUnauthorized, - LinkIdentityRequested, OpaqueTaskPosted, VCRequested, + LinkIdentityRequested, OpaqueTaskPosted, RewardDistributionStarted, VCRequested, }; use itp_stf_primitives::traits::{IndirectExecutor, TrustedCallVerification}; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; use sp_core::{bounded::alloc, H160, H256}; -use sp_runtime::{generic::Header as HeaderG, traits::BlakeTwo256, MultiAddress, MultiSignature}; +use sp_runtime::{ + generic::Header as HeaderG, + traits::{BlakeTwo256, Header as HeaderT}, + MultiAddress, MultiSignature, +}; use self::events::ParentchainBlockProcessed; @@ -116,6 +120,10 @@ pub trait FilterEvents { fn get_parentchain_block_proccessed_events( &self, ) -> Result, Self::Error>; + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error>; } #[derive(Debug)] @@ -135,6 +143,7 @@ where &self, executor: &Executor, events: impl FilterEvents, + block_header: impl HeaderT, ) -> Result; } @@ -149,6 +158,7 @@ pub enum ParentchainEventProcessingError { OpaqueTaskPostedFailure, AssertionCreatedFailure, ParentchainBlockProcessedFailure, + RewardDistributionStartedFailure, } impl core::fmt::Display for ParentchainEventProcessingError { @@ -172,6 +182,8 @@ impl core::fmt::Display for ParentchainEventProcessingError { "Parentchain Event Processing Error: AssertionCreatedFailure", ParentchainEventProcessingError::ParentchainBlockProcessedFailure => "Parentchain Event Processing Error: ParentchainBlockProcessedFailure", + ParentchainEventProcessingError::RewardDistributionStartedFailure => + "Parentchain Event Processing Error: RewardDistributionStartedFailure", }; write!(f, "{}", message) } diff --git a/tee-worker/core/parentchain/indirect-calls-executor/src/executor.rs b/tee-worker/core/parentchain/indirect-calls-executor/src/executor.rs index 61ced37b8a..14815c880a 100644 --- a/tee-worker/core/parentchain/indirect-calls-executor/src/executor.rs +++ b/tee-worker/core/parentchain/indirect-calls-executor/src/executor.rs @@ -167,8 +167,9 @@ impl< })? .ok_or_else(|| Error::Other("Could not create events from metadata".into()))?; - let (processed_events, successful_assertion_ids, failed_assertion_ids) = - self.parentchain_event_handler.handle_events(self, events)?; + let (processed_events, successful_assertion_ids, failed_assertion_ids) = self + .parentchain_event_handler + .handle_events(self, events, block.header().clone())?; let mut calls: Vec = Vec::new(); if !successful_assertion_ids.is_empty() { calls.extend(self.create_assertion_stored_call(successful_assertion_ids)?); diff --git a/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs b/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs index bc63f95317..ad621adef6 100644 --- a/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs +++ b/tee-worker/core/parentchain/indirect-calls-executor/src/mock.rs @@ -12,6 +12,7 @@ use itp_types::{ RsaRequest, H256, }; use sp_core::H160; +use sp_runtime::traits::Header; use std::vec::Vec; pub struct TestEventCreator; @@ -70,6 +71,12 @@ impl FilterEvents for MockEvents { ) -> Result, Self::Error> { Ok(Vec::new()) } + + fn get_reward_distribution_started_events( + &self, + ) -> Result, Self::Error> { + Ok(Vec::new()) + } } pub struct MockParentchainEventHandler {} @@ -83,6 +90,7 @@ where &self, _: &Executor, _: impl FilterEvents, + _: impl Header, ) -> Result { Ok(( Vec::from([H256::default()]), diff --git a/tee-worker/enclave-runtime/Cargo.lock b/tee-worker/enclave-runtime/Cargo.lock index e589c28d07..fa4b39f168 100644 --- a/tee-worker/enclave-runtime/Cargo.lock +++ b/tee-worker/enclave-runtime/Cargo.lock @@ -1966,6 +1966,7 @@ dependencies = [ name = "ita-parentchain-interface" version = "0.1.0" dependencies = [ + "frame-support", "ita-sgx-runtime", "ita-stf", "itc-parentchain-indirect-calls-executor", @@ -1973,12 +1974,18 @@ dependencies = [ "itp-enclave-metrics", "itp-node-api", "itp-ocall-api", + "itp-sgx-externalities", "itp-stf-primitives", + "itp-stf-state-handler", + "itp-storage", "itp-types", "lc-dynamic-assertion", "lc-evm-dynamic-assertions", + "lc-parachain-extrinsic-task-sender", + "litentry-hex-utils 0.1.0", "litentry-primitives", "log", + "pallet-identity-management-tee", "parity-scale-codec", "sgx_tstd", "sp-core", @@ -3384,7 +3391,9 @@ dependencies = [ "core-primitives", "hex", "itp-sgx-crypto", + "itp-utils", "log", + "pallet-parachain-staking", "pallet-teebag", "parity-scale-codec", "rand 0.7.3", diff --git a/tee-worker/enclave-runtime/src/initialization/global_components.rs b/tee-worker/enclave-runtime/src/initialization/global_components.rs index 5255d5303e..939d69fe18 100644 --- a/tee-worker/enclave-runtime/src/initialization/global_components.rs +++ b/tee-worker/enclave-runtime/src/initialization/global_components.rs @@ -177,7 +177,11 @@ pub type IntegriteeParentchainIndirectCallsExecutor = IndirectCallsExecutor< EnclaveTopPoolAuthor, EnclaveNodeMetadataRepository, EventCreator, - integritee::ParentchainEventHandler, + integritee::ParentchainEventHandler< + EnclaveOCallApi, + EnclaveStateHandler, + EnclaveNodeMetadataRepository, + >, EnclaveTrustedCallSigned, EnclaveGetter, >; diff --git a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs index 52b345d75a..40fa90d6c7 100644 --- a/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs +++ b/tee-worker/enclave-runtime/src/initialization/parentchain/common.rs @@ -69,10 +69,13 @@ pub(crate) fn create_integritee_parentchain_block_importer( let shielding_key_repository = GLOBAL_SHIELDING_KEY_REPOSITORY_COMPONENT.get()?; let ocall_api = GLOBAL_OCALL_API_COMPONENT.get()?; let repository = GLOBAL_ASSERTION_REPOSITORY.get()?; + let state_handler = GLOBAL_STATE_HANDLER_COMPONENT.get()?; let parentchain_event_handler = LitentryParentchainEventHandler { assertion_repository: repository, - metrics_api: ocall_api.clone(), + ocall_api: ocall_api.clone(), + state_handler, + node_metadata_repository: node_metadata_repository.clone(), }; let stf_enclave_signer = Arc::new(EnclaveStfEnclaveSigner::new( diff --git a/tee-worker/litentry/primitives/Cargo.toml b/tee-worker/litentry/primitives/Cargo.toml index 9f3a4e6cfa..adbc8da826 100644 --- a/tee-worker/litentry/primitives/Cargo.toml +++ b/tee-worker/litentry/primitives/Cargo.toml @@ -25,6 +25,8 @@ sgx_tstd = { git = "https://github.com/apache/teaclave-sgx-sdk.git", branch = "m # internal dependencies itp-sgx-crypto = { path = "../../core-primitives/sgx/crypto", default-features = false } +itp-utils = { path = "../../core-primitives/utils", default-features = false } +pallet-parachain-staking = { git = "https://github.com/litentry/litentry-parachain", branch = "release-v0.9.19", default-features = false } pallet-teebag = { git = "https://github.com/litentry/litentry-parachain", branch = "release-v0.9.19", default-features = false } parentchain-primitives = { package = "core-primitives", git = "https://github.com/litentry/litentry-parachain", branch = "release-v0.9.19", default-features = false } diff --git a/tee-worker/litentry/primitives/src/lib.rs b/tee-worker/litentry/primitives/src/lib.rs index da8d5e8e94..1f05bb0afc 100644 --- a/tee-worker/litentry/primitives/src/lib.rs +++ b/tee-worker/litentry/primitives/src/lib.rs @@ -42,6 +42,7 @@ use bitcoin::sign_message::{signed_msg_hash, MessageSignature}; use codec::{Decode, Encode, MaxEncodedLen}; use itp_sgx_crypto::ShieldingCryptoDecrypt; use log::error; +pub use pallet_parachain_staking::Delegator; pub use pallet_teebag::{ decl_rsa_request, extract_tcb_info_from_raw_dcap_quote, AttestationType, DcapProvider, Enclave, EnclaveFingerprint, MrEnclave, ShardIdentifier, SidechainBlockNumber, WorkerMode, WorkerType, From e903f270d8605037db7952e3d94dceeca4babf5a Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 23 Sep 2024 08:08:23 +0000 Subject: [PATCH 02/14] merging identity-staking-improvement branch --- pallets/score-staking/src/lib.rs | 171 +++--- pallets/score-staking/src/mock.rs | 3 +- pallets/score-staking/src/tests.rs | 560 +++++++++++++----- pallets/score-staking/src/types.rs | 1 - precompiles/score-staking/src/mock.rs | 3 +- precompiles/score-staking/src/tests.rs | 21 +- runtime/litentry/src/lib.rs | 5 +- runtime/paseo/src/lib.rs | 3 +- runtime/rococo/src/lib.rs | 3 +- .../src/integritee/event_handler.rs | 49 +- .../node-api/metadata/src/metadata_mocks.rs | 8 +- .../metadata/src/pallet_score_staking.rs | 7 +- .../types/src/parentchain/events.rs | 11 +- 13 files changed, 552 insertions(+), 293 deletions(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index 16d947f403..912e1317a8 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -47,7 +47,11 @@ use frame_support::{ }; use pallet_parachain_staking as ParaStaking; use sp_core::crypto::AccountId32; -use sp_runtime::{traits::CheckedSub, Perbill, SaturatedConversion}; +use sp_runtime::{ + traits::{CheckedSub, Zero}, + Perbill, SaturatedConversion, +}; +use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; pub use pallet::*; @@ -74,7 +78,6 @@ pub mod pallet { use core_primitives::Identity; use frame_system::pallet_prelude::*; - use sp_runtime::traits::Zero; /// The current storage version. const STORAGE_VERSION: StorageVersion = StorageVersion::new(0); @@ -116,6 +119,8 @@ pub mod pallet { type AccountIdConvert: AccountIdConvert; // For extrinsics that should only be called by origins from TEE type TEECallOrigin: EnsureOrigin; + #[pallet::constant] + type MaxIDGraphAccountsPerCall: Get; } #[pallet::error] @@ -153,44 +158,24 @@ pub mod pallet { // when the score user count would exceed `MaxScoreUserCount` MaxScoreUserCountReached, // the token staking amount has been updated already for the round - TokenStakingAmountAlreadyUpdated, + RoundRewardsAlreadyDistributed, + // the maximum number of IDGraph accounts has been reached + MaxIDGraphAccountsPerCallReached, } #[pallet::event] #[pallet::generate_deposit(pub (crate) fn deposit_event)] pub enum Event { - PoolStarted { - start_block: BlockNumberFor, - }, + PoolStarted { start_block: BlockNumberFor }, PoolStopped {}, - ScoreFeederSet { - new_score_feeder: Option, - }, - RoundConfigSet { - new_config: RoundSetting, - }, - ScoreUpdated { - who: Identity, - new_score: Score, - }, - ScoreRemoved { - who: Identity, - }, + ScoreFeederSet { new_score_feeder: Option }, + RoundConfigSet { new_config: RoundSetting }, + ScoreUpdated { who: Identity, new_score: Score }, + ScoreRemoved { who: Identity }, ScoreCleared {}, - TokenStakingAmountUpdated { - account: T::AccountId, - amount: BalanceOf, - }, - RewardDistributionStarted { - total: BalanceOf, - distributed: BalanceOf, - round_index: RoundIndex, - }, - RewardDistributionCompleted {}, - RewardClaimed { - who: T::AccountId, - amount: BalanceOf, - }, + RewardDistributionStarted { round_index: RoundIndex }, + RewardDistributionCompleted { round_index: RoundIndex }, + RewardClaimed { who: T::AccountId, amount: BalanceOf }, } #[pallet::storage] @@ -231,6 +216,11 @@ pub mod pallet { #[pallet::getter(fn state)] pub type State = StorageValue<_, PoolState, ValueQuery>; + /// The round index of the last token distribution + #[pallet::storage] + #[pallet::getter(fn last_rewards_distribution_round)] + pub type LastTokenDistributionRound = StorageValue<_, RoundIndex, ValueQuery>; + #[pallet::genesis_config] pub struct GenesisConfig { pub state: PoolState, @@ -268,50 +258,14 @@ pub mod pallet { } // We are about to start a new round - // 1. update round info + // - update round info let round_index = r.index.saturating_add(1); r.index = round_index; r.start_block = now; Round::::put(r); weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); - // 2. calculate payout - let round_reward: BalanceOf = (T::YearlyInflation::get() * T::YearlyIssuance::get() - / YEARS.into()) * Self::round_config().interval.into(); - let round_reward_u128 = round_reward.saturated_into::(); - - let total_stake_u128 = ParaStaking::Pallet::::total().saturated_into::(); - let total_score = Self::total_score(); - let n = Self::round_config().stake_coef_n; - let m = Self::round_config().stake_coef_m; - - let mut all_user_reward = BalanceOf::::zero(); - - for (a, mut p) in Scores::::iter() { - let user_stake_u128 = ParaStaking::Pallet::::delegator_state(&a) - .map(|s| s.total) - .unwrap_or_default() - .saturated_into::(); - let user_reward_u128 = round_reward_u128 - .saturating_mul(p.score.into()) - .saturating_div(total_score.into()) - .saturating_mul(num_integer::Roots::nth_root(&user_stake_u128.pow(n), m)) - .saturating_div(num_integer::Roots::nth_root(&total_stake_u128.pow(n), m)); - let user_reward = user_reward_u128.saturated_into::>(); - - p.last_round_reward = user_reward; - p.total_reward += user_reward; - p.unpaid_reward += user_reward; - all_user_reward += user_reward; - Scores::::insert(&a, p); - weight = weight.saturating_add(T::DbWeight::get().reads_writes(2, 1)); - } - - Self::deposit_event(Event::::RewardDistributionStarted { - total: round_reward, - distributed: all_user_reward, - round_index, - }); + Self::deposit_event(Event::::RewardDistributionStarted { round_index }); weight } @@ -477,41 +431,70 @@ pub mod pallet { #[pallet::call_index(9)] #[pallet::weight((195_000_000, DispatchClass::Normal))] - pub fn update_token_staking_amount( + pub fn distribute_rewards( origin: OriginFor, - account: T::AccountId, - amount: BalanceOf, round_index: RoundIndex, + id_graphs_staking: Vec<(T::AccountId, BalanceOf)>, ) -> DispatchResultWithPostInfo { let _ = T::TEECallOrigin::ensure_origin(origin)?; - match Scores::::get(&account) { - Some(mut s) => { - if round_index <= s.last_token_distributed_round { - return Err(Error::::TokenStakingAmountAlreadyUpdated.into()); - } - let last_round = Round::::get(); - s.last_round_reward += amount; - s.total_reward += amount; - s.unpaid_reward += amount; - s.last_token_distributed_round = last_round.index; - Scores::::insert(account.clone(), s); - Self::deposit_event(Event::TokenStakingAmountUpdated { - account: account.clone(), - amount, - }); - Ok(Pays::No.into()) - }, - None => Err(Error::::UserNotExist.into()), + ensure!( + round_index > LastTokenDistributionRound::::get(), + Error::::RoundRewardsAlreadyDistributed + ); + + let id_graphs_staking_map: BTreeMap> = + id_graphs_staking.into_iter().collect(); + + ensure!( + id_graphs_staking_map.len() <= T::MaxIDGraphAccountsPerCall::get() as usize, + Error::::MaxIDGraphAccountsPerCallReached + ); + + let round_reward: BalanceOf = (T::YearlyInflation::get() * T::YearlyIssuance::get() + / YEARS.into()) * Self::round_config().interval.into(); + let round_reward_u128 = round_reward.saturated_into::(); + + let total_stake_u128 = ParaStaking::Pallet::::total().saturated_into::(); + let total_score = Self::total_score(); + let n = Self::round_config().stake_coef_n; + let m = Self::round_config().stake_coef_m; + + for (a, mut p) in Scores::::iter() { + let default_staking = BalanceOf::::zero(); + let id_graph_staking = id_graphs_staking_map.get(&a).unwrap_or(&default_staking); + let user_stake_u128 = ParaStaking::Pallet::::delegator_state(&a) + .map(|s| s.total) + .unwrap_or_default() + .saturated_into::() + + (*id_graph_staking).saturated_into::(); + let user_reward_u128 = round_reward_u128 + .saturating_mul(p.score.into()) + .saturating_div(total_score.into()) + .saturating_mul(num_integer::Roots::nth_root(&user_stake_u128.pow(n), m)) + .saturating_div(num_integer::Roots::nth_root(&total_stake_u128.pow(n), m)); + let user_reward = user_reward_u128.saturated_into::>(); + + p.last_round_reward = user_reward; + p.total_reward += user_reward; + p.unpaid_reward += user_reward; + Scores::::insert(&a, p); } + + Ok(Pays::No.into()) } #[pallet::call_index(10)] #[pallet::weight((195_000_000, DispatchClass::Normal))] - pub fn complete_reward_distribution(origin: OriginFor) -> DispatchResultWithPostInfo { + pub fn complete_reward_distribution( + origin: OriginFor, + round_index: RoundIndex, + ) -> DispatchResultWithPostInfo { let _ = T::TEECallOrigin::ensure_origin(origin)?; - Self::deposit_event(Event::RewardDistributionCompleted {}); + LastTokenDistributionRound::::put(round_index); + + Self::deposit_event(Event::RewardDistributionCompleted { round_index }); Ok(Pays::No.into()) } diff --git a/pallets/score-staking/src/mock.rs b/pallets/score-staking/src/mock.rs index d50d8acff3..cb0d433b82 100644 --- a/pallets/score-staking/src/mock.rs +++ b/pallets/score-staking/src/mock.rs @@ -26,7 +26,7 @@ use frame_support::{ traits::{OnFinalize, OnInitialize}, }; use frame_system::{EnsureRoot, EnsureSignedBy}; -use sp_core::{ConstU128, ConstU32, H256}; +use sp_core::{ConstU128, ConstU16, ConstU32, H256}; use sp_keyring::AccountKeyring; use sp_runtime::{ generic, @@ -171,6 +171,7 @@ impl pallet_score_staking::Config for Test { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; type TEECallOrigin = EnsureEnclaveSigner; + type MaxIDGraphAccountsPerCall = ConstU16<2>; } parameter_types! { diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index 3075fd5400..03d0925d9d 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -22,6 +22,7 @@ use frame_support::{assert_err, assert_noop, assert_ok}; use pallet_parachain_staking::{Delegator, OnAllDelegationRemoved}; use pallet_teebag::{Enclave, WorkerType}; use sp_runtime::Perbill; +use sp_std::vec; fn round_reward() -> Balance { (Perbill::from_perthousand(5) * 100_000_000 * UNIT / (YEARS as u128)) * 5 @@ -129,11 +130,7 @@ fn default_mint_works() { // run to next reward distribution round run_to_block(7); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { - total: round_reward(), - distributed: 0, - round_index: 2, - }, + Event::::RewardDistributionStarted { round_index: 2 }, )); }); } @@ -156,141 +153,228 @@ fn score_update_checks_staking() { #[allow(clippy::identity_op)] fn score_staking_works() { new_test_ext_with_parachain_staking().execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + run_to_block(2); assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); + let alice_staking = 900; + let alice_id_graph_staking = 0; + let mut alice_score = 500; + run_to_block(3); pallet_parachain_staking::DelegatorState::::insert( alice(), - Delegator::new(bob(), bob(), 900), + Delegator::new(bob(), bob(), alice_staking), ); - pallet_parachain_staking::Total::::put(900); + pallet_parachain_staking::Total::::put(alice_staking); - assert_ok!(ScoreStaking::update_score(RuntimeOrigin::signed(alice()), alice().into(), 500)); + assert_ok!(ScoreStaking::update_score( + RuntimeOrigin::signed(alice()), + alice().into(), + alice_score + )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { - score: 500, + score: alice_score, total_reward: 0, last_round_reward: 0, - unpaid_reward: 0, - last_token_distributed_round: 0 + unpaid_reward: 0 } ); - assert_eq!(ScoreStaking::total_score(), 500); + + assert_eq!(ScoreStaking::total_score(), alice_score); assert_eq!(ScoreStaking::score_user_count(), 1); + alice_score = 2000; + assert_ok!(ScoreStaking::update_score( RuntimeOrigin::signed(alice()), alice().into(), - 2000 + alice_score )); - assert_eq!(ScoreStaking::scores(alice()).unwrap().score, 2000); - assert_eq!(ScoreStaking::total_score(), 2000); + assert_eq!(ScoreStaking::scores(alice()).unwrap().score, alice_score); + assert_eq!(ScoreStaking::total_score(), alice_score); assert_eq!(ScoreStaking::score_user_count(), 1); // run to next reward distribution round, alice should win all rewards run_to_block(7); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { - total: round_reward(), - distributed: round_reward(), - round_index: 2, - }, + Event::::RewardDistributionStarted { round_index: 2 }, )); // total reward first distribution - let mut alice_total_reward = round_reward(); + let mut alice_total_reward = 0; + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + let round_reward = calculate_round_reward( + alice_score.into(), + total_score.into(), + alice_staking + alice_id_graph_staking, + total_staking, + ); + alice_total_reward += round_reward; + + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 2, + vec![(alice(), alice_id_graph_staking)] + )); + assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 2)); + + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 2, + })); + assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { - score: 2000, + score: alice_score, total_reward: alice_total_reward, - last_round_reward: alice_total_reward, + last_round_reward: round_reward, unpaid_reward: alice_total_reward, - last_token_distributed_round: 0, } ); // alice's winning should accumulate run_to_block(12); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { - total: round_reward(), - distributed: round_reward(), - round_index: 3, - }, + Event::::RewardDistributionStarted { round_index: 3 }, )); // total reward second distribution - alice_total_reward += round_reward(); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + let round_reward = calculate_round_reward( + alice_score.into(), + total_score.into(), + alice_staking + alice_id_graph_staking, + total_staking, + ); + alice_total_reward += round_reward; + + // calculates the rewards + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 3, + vec![(alice(), alice_id_graph_staking)] + )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { - score: 2000, + score: alice_score, total_reward: alice_total_reward, - last_round_reward: round_reward(), + last_round_reward: round_reward, unpaid_reward: alice_total_reward, - last_token_distributed_round: 0, } ); + let other_staking = 1000; + // increase the total staked amount, alice should win less run_to_block(13); - pallet_parachain_staking::Total::::put(1600); + pallet_parachain_staking::Total::::put(alice_staking + other_staking); run_to_block(17); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { - total: round_reward(), - distributed: calculate_round_reward(2000, 2000, 900, 1600), - round_index: 4, - }, + Event::::RewardDistributionStarted { round_index: 4 }, )); + + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 4, + vec![(alice(), alice_id_graph_staking)] + )); + + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + let round_reward = calculate_round_reward( + alice_score.into(), + total_score.into(), + alice_staking + alice_id_graph_staking, + total_staking, + ); // total reward third distribution - alice_total_reward += calculate_round_reward(2000, 2000, 900, 1600); + alice_total_reward += round_reward; assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { - score: 2000, + score: alice_score, total_reward: alice_total_reward, - last_round_reward: calculate_round_reward(2000, 2000, 900, 1600), + last_round_reward: round_reward, unpaid_reward: alice_total_reward, - last_token_distributed_round: 0, } ); - // add bob's score run_to_block(18); - assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(bob()), alice(), 1600)); - assert_eq!(pallet_parachain_staking::Total::::get(), 3200); - assert_ok!(ScoreStaking::update_score(RuntimeOrigin::signed(alice()), bob().into(), 1000)); - assert_eq!(ScoreStaking::total_score(), 3000); + + // add bob's score + let mut bob_staking = 1600; + let mut bob_score = 1000; + let bob_id_graph_staking = 0; + + assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(bob()), alice(), bob_staking)); + assert_eq!( + pallet_parachain_staking::Total::::get(), + alice_staking + bob_staking + other_staking + ); + assert_ok!(ScoreStaking::update_score( + RuntimeOrigin::signed(alice()), + bob().into(), + bob_score + )); + assert_eq!(ScoreStaking::total_score(), alice_score + bob_score); assert_eq!(ScoreStaking::score_user_count(), 2); run_to_block(22); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { round_index: 5 }, + )); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 5, + vec![(alice(), alice_id_graph_staking), (bob(), bob_id_graph_staking)] + )); + // total rewards fourth distribution - alice_total_reward += calculate_round_reward(2000, 3000, 900, 3200); - let mut bob_total_reward = calculate_round_reward(1000, 3000, 1600, 3200); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + + let alice_round_reward = calculate_round_reward( + alice_score.into(), + total_score.into(), + alice_staking + alice_id_graph_staking, + total_staking, + ); + alice_total_reward += alice_round_reward; + + let mut bob_total_reward = 0; + let bob_round_reward = calculate_round_reward( + bob_score.into(), + total_score.into(), + bob_staking + bob_id_graph_staking, + total_staking, + ); + bob_total_reward += bob_round_reward; assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { - score: 2000, + score: alice_score, total_reward: alice_total_reward, - last_round_reward: calculate_round_reward(2000, 3000, 900, 3200), + last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, - last_token_distributed_round: 0, } ); assert_eq!( ScoreStaking::scores(bob()).unwrap(), ScorePayment { - score: 1000, + score: bob_score, total_reward: bob_total_reward, - last_round_reward: bob_total_reward, + last_round_reward: bob_round_reward, unpaid_reward: bob_total_reward, - last_token_distributed_round: 0, } ); @@ -311,10 +395,55 @@ fn score_staking_works() { alice() )); - run_to_block(25); + run_to_block(27); + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { round_index: 6 }, + )); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 6, + vec![(alice(), alice_id_graph_staking), (bob(), bob_id_graph_staking)] + )); + // total rewards fifth distribution - alice_total_reward += calculate_round_reward(2000, 3000, 900, 3200); - bob_total_reward += calculate_round_reward(1000, 3000, 1600, 3200); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + + let alice_round_reward = calculate_round_reward( + alice_score.into(), + total_score.into(), + alice_staking + alice_id_graph_staking, + total_staking, + ); + alice_total_reward += alice_round_reward; + + let bob_round_reward = calculate_round_reward( + bob_score.into(), + total_score.into(), + bob_staking + bob_id_graph_staking, + total_staking, + ); + bob_total_reward += bob_round_reward; + + assert_eq!( + ScoreStaking::scores(alice()).unwrap(), + ScorePayment { + score: alice_score, + total_reward: alice_total_reward, + last_round_reward: alice_round_reward, + unpaid_reward: alice_total_reward, + } + ); + assert_eq!( + ScoreStaking::scores(bob()).unwrap(), + ScorePayment { + score: bob_score, + total_reward: bob_total_reward, + last_round_reward: bob_round_reward, + unpaid_reward: bob_total_reward, + } + ); run_to_block(30); assert_ok!(ParachainStaking::execute_delegation_request( @@ -322,28 +451,94 @@ fn score_staking_works() { bob(), alice() )); + bob_staking = 0; + bob_score = 0; + + run_to_block(33); + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { round_index: 7 }, + )); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 7, + vec![(alice(), alice_id_graph_staking), (bob(), bob_id_graph_staking)] + )); - run_to_block(31); // total reward sixth distribution - alice_total_reward += calculate_round_reward(2000, 2000, 900, 900); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + + let alice_round_reward = calculate_round_reward( + alice_score.into(), + total_score.into(), + alice_staking + alice_id_graph_staking, + total_staking, + ); + alice_total_reward += alice_round_reward; + + let bob_round_reward = calculate_round_reward( + bob_score.into(), + total_score.into(), + bob_staking + bob_id_graph_staking, + total_staking, + ); + bob_total_reward += bob_round_reward; + + assert_eq!( + ScoreStaking::scores(alice()).unwrap(), + ScorePayment { + score: alice_score, + total_reward: alice_total_reward, + last_round_reward: alice_round_reward, + unpaid_reward: alice_total_reward, + } + ); + assert_eq!( + ScoreStaking::scores(bob()).unwrap(), + ScorePayment { + score: bob_score, + total_reward: bob_total_reward, + last_round_reward: bob_round_reward, + unpaid_reward: bob_total_reward, + } + ); // remove increased stake (keep only alice's stake) - pallet_parachain_staking::Total::::put(900); + pallet_parachain_staking::Total::::put(alice_staking); + + run_to_block(37); - run_to_block(32); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { round_index: 8 }, + )); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 8, + vec![(alice(), alice_id_graph_staking), (bob(), bob_id_graph_staking)] + )); + + // total reward sixth distribution + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + + let alice_round_reward = calculate_round_reward( + alice_score.into(), + total_score.into(), + alice_staking + alice_id_graph_staking, + total_staking, + ); + alice_total_reward += alice_round_reward; - // alice should get all rewards assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { - score: 2000, + score: alice_score, total_reward: alice_total_reward, - last_round_reward: round_reward(), + last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, - last_token_distributed_round: 0, } ); - // bob should not participate in the reward calculation assert_eq!( ScoreStaking::scores(bob()).unwrap(), @@ -352,15 +547,14 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: 0, unpaid_reward: bob_total_reward, - last_token_distributed_round: 0, } ); - assert_eq!(ScoreStaking::total_score(), 2000); + assert_eq!(ScoreStaking::total_score(), alice_score); assert_eq!(ScoreStaking::score_user_count(), 2); // entry is not yet removed // remove_score works assert_ok!(ScoreStaking::remove_score(RuntimeOrigin::signed(alice()), bob().into())); - assert_eq!(ScoreStaking::total_score(), 2000); + assert_eq!(ScoreStaking::total_score(), alice_score); assert_eq!(ScoreStaking::score_user_count(), 1); }); } @@ -368,6 +562,9 @@ fn score_staking_works() { #[test] fn claim_works() { new_test_ext(true).execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + run_to_block(2); assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); @@ -387,22 +584,17 @@ fn claim_works() { // run to next reward distribution round, alice should win all rewards run_to_block(7); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { - total: round_reward(), - distributed: round_reward(), - round_index: 2, - }, + Event::::RewardDistributionStarted { round_index: 2 }, )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), - ScorePayment { - score: 2000, - total_reward: round_reward(), - last_round_reward: round_reward(), - unpaid_reward: round_reward(), - last_token_distributed_round: 0, - } + ScorePayment { score: 2000, total_reward: 0, last_round_reward: 0, unpaid_reward: 0 } ); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 2, + vec![(alice(), 0)] + )); assert_ok!(ScoreStaking::claim(RuntimeOrigin::signed(alice()), 200)); System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardClaimed { @@ -416,7 +608,6 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, - last_token_distributed_round: 0, } ); @@ -432,7 +623,6 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, - last_token_distributed_round: 0, } ); @@ -445,7 +635,7 @@ fn claim_works() { } #[test] -fn update_token_staking_amount_works() { +fn distribute_rewards_works() { new_test_ext_with_parachain_staking().execute_with(|| { let enclave = Enclave::new(WorkerType::Identity); pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); @@ -453,117 +643,191 @@ fn update_token_staking_amount_works() { run_to_block(2); assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); + let alice_staking = 900; + let alice_score = 500; + run_to_block(3); pallet_parachain_staking::DelegatorState::::insert( alice(), - Delegator::new(bob(), bob(), 900), + Delegator::new(bob(), bob(), alice_staking), ); - pallet_parachain_staking::Total::::put(900); - assert_ok!(ScoreStaking::update_score(RuntimeOrigin::signed(alice()), alice().into(), 500)); + pallet_parachain_staking::Total::::put(alice_staking); + assert_ok!(ScoreStaking::update_score( + RuntimeOrigin::signed(alice()), + alice().into(), + alice_score + )); // run to next reward distribution round, alice should win all rewards run_to_block(7); - let mut total_reward = round_reward(); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { - total: total_reward, - distributed: total_reward, - round_index: 2, - }, + Event::::RewardDistributionStarted { round_index: 2 }, )); - assert_ok!(ScoreStaking::update_token_staking_amount( + let alice_id_graph_staking = 1000; + + assert_ok!(ScoreStaking::distribute_rewards( RuntimeOrigin::signed(alice()), - alice(), - 1000, 2, + vec![(alice(), alice_id_graph_staking)] )); - total_reward += 1000; + let mut alice_total_reward = 0; + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + let round_reward = calculate_round_reward( + alice_score.into(), + total_score.into(), + alice_staking + alice_id_graph_staking, + total_staking, + ); + alice_total_reward += round_reward; assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { - score: 500, - total_reward, - last_round_reward: total_reward, - unpaid_reward: total_reward, - last_token_distributed_round: 2, + score: alice_score, + total_reward: alice_total_reward, + last_round_reward: round_reward, + unpaid_reward: alice_total_reward, } ); run_to_block(12); - total_reward += round_reward(); - - assert_noop!( - ScoreStaking::update_token_staking_amount( - RuntimeOrigin::signed(alice()), - alice(), - 1000, - 2, - ), - Error::::TokenStakingAmountAlreadyUpdated - ); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { round_index: 3 }, + )); - assert_ok!(ScoreStaking::update_token_staking_amount( + assert_ok!(ScoreStaking::distribute_rewards( RuntimeOrigin::signed(alice()), - alice(), - 1200, 3, + vec![(alice(), alice_id_graph_staking)] )); + assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 3)); + + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + let round_reward = calculate_round_reward( + alice_score.into(), + total_score.into(), + alice_staking + alice_id_graph_staking, + total_staking, + ); + alice_total_reward += round_reward; - total_reward += 1200; - - System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::TokenStakingAmountUpdated { account: alice(), amount: 1200 }, - )); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 3, + })); assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { - score: 500, - total_reward, - last_round_reward: round_reward() + 1200, - unpaid_reward: total_reward, - last_token_distributed_round: 3, + score: alice_score, + total_reward: alice_total_reward, + last_round_reward: round_reward, + unpaid_reward: alice_total_reward, } ); }) } #[test] -fn update_token_staking_amount_origin_check_works() { +fn distribute_rewards_round_rewards_already_distributed_works() { + new_test_ext_with_parachain_staking().execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + + run_to_block(2); + assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); + + let alice_staking = 900; + let alice_score = 500; + + run_to_block(3); + pallet_parachain_staking::DelegatorState::::insert( + alice(), + Delegator::new(bob(), bob(), alice_staking), + ); + pallet_parachain_staking::Total::::put(alice_staking); + assert_ok!(ScoreStaking::update_score( + RuntimeOrigin::signed(alice()), + alice().into(), + alice_score + )); + + // run to next reward distribution round, alice should win all rewards + run_to_block(7); + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { round_index: 2 }, + )); + + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 2, + vec![(alice(), 0)] + )); + assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 2)); + + assert_noop!( + ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2, vec![(alice(), 0)]), + Error::::RoundRewardsAlreadyDistributed + ); + }) +} + +#[test] +fn distribute_rewards_origin_check_works() { new_test_ext(false).execute_with(|| { assert_noop!( - ScoreStaking::update_token_staking_amount( - RuntimeOrigin::signed(alice()), - alice(), - 1000, - 1 - ), + ScoreStaking::distribute_rewards(RuntimeOrigin::signed(bob()), 1, vec![(alice(), 0)]), sp_runtime::DispatchError::BadOrigin ); }) } #[test] -fn update_token_staking_amount_existing_user_check_works() { - new_test_ext(false).execute_with(|| { +fn distribute_rewards_max_id_graph_accounts_per_call_check_works() { + new_test_ext(true).execute_with(|| { let enclave = Enclave::new(WorkerType::Identity); pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + run_to_block(2); + assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); + + let alice_staking = 900; + let alice_score = 500; + + run_to_block(3); + pallet_parachain_staking::DelegatorState::::insert( + alice(), + Delegator::new(bob(), bob(), alice_staking), + ); + pallet_parachain_staking::Total::::put(alice_staking); + assert_ok!(ScoreStaking::update_score( + RuntimeOrigin::signed(alice()), + alice().into(), + alice_score + )); + + // run to next reward distribution round, alice should win all rewards + run_to_block(7); + + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { round_index: 2 }, + )); + assert_noop!( - ScoreStaking::update_token_staking_amount( + ScoreStaking::distribute_rewards( RuntimeOrigin::signed(alice()), - alice(), - 1000, - 1 + 2, + vec![(alice(), 0), (bob(), 0), (charlie(), 0)] ), - Error::::UserNotExist + Error::::MaxIDGraphAccountsPerCallReached ); - }) + }); } #[test] @@ -572,11 +836,15 @@ fn complete_reward_distribution_works() { let enclave = Enclave::new(WorkerType::Identity); pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); - assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()))); + assert_eq!(ScoreStaking::last_rewards_distribution_round(), 0); + + assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 1)); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionCompleted {}, + Event::::RewardDistributionCompleted { round_index: 1 }, )); + + assert_eq!(ScoreStaking::last_rewards_distribution_round(), 1); }); } @@ -584,7 +852,7 @@ fn complete_reward_distribution_works() { fn complete_reward_distribution_origin_check_works() { new_test_ext(false).execute_with(|| { assert_noop!( - ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice())), + ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 2), sp_runtime::DispatchError::BadOrigin ); }); diff --git a/pallets/score-staking/src/types.rs b/pallets/score-staking/src/types.rs index 5b6edda153..1456f4e67d 100644 --- a/pallets/score-staking/src/types.rs +++ b/pallets/score-staking/src/types.rs @@ -83,5 +83,4 @@ pub struct ScorePayment { pub total_reward: Balance, pub last_round_reward: Balance, pub unpaid_reward: Balance, - pub last_token_distributed_round: RoundIndex, } diff --git a/precompiles/score-staking/src/mock.rs b/precompiles/score-staking/src/mock.rs index c127b263d8..6d5729437a 100644 --- a/precompiles/score-staking/src/mock.rs +++ b/precompiles/score-staking/src/mock.rs @@ -27,7 +27,7 @@ use frame_system::EnsureRoot; use pallet_evm::{AddressMapping, EnsureAddressNever, EnsureAddressRoot}; use pallet_score_staking::{AccountIdConvert, PoolState, RoundSetting}; use precompile_utils::precompile_set::{AddressU64, PrecompileAt, PrecompileSetBuilder}; -use sp_core::{ConstU128, ConstU32, ConstU64, H160, H256}; +use sp_core::{ConstU128, ConstU16, ConstU32, ConstU64, H160, H256}; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, Percent, @@ -169,6 +169,7 @@ impl pallet_score_staking::Config for Test { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; type TEECallOrigin = EnsureEnclaveSigner; + type MaxIDGraphAccountsPerCall = ConstU16<2>; } pub fn precompile_address() -> H160 { diff --git a/precompiles/score-staking/src/tests.rs b/precompiles/score-staking/src/tests.rs index c096c09a73..ecf45855f0 100644 --- a/precompiles/score-staking/src/tests.rs +++ b/precompiles/score-staking/src/tests.rs @@ -20,8 +20,10 @@ use core_primitives::YEARS; use frame_support::{assert_err, assert_ok}; use pallet_parachain_staking::Delegator; use pallet_score_staking::{Error, Event, ScorePayment}; +use pallet_teebag::{Enclave, WorkerType}; use precompile_utils::testing::*; use sp_runtime::Perbill; +use sp_std::vec; fn round_reward() -> Balance { (Perbill::from_perthousand(5) * 100_000_000 * UNIT / (YEARS as u128)) * 5 @@ -34,6 +36,9 @@ fn precompiles() -> ScoreStakingMockPrecompile { #[test] fn claim_is_ok() { new_test_ext(true).execute_with(|| { + let enclave = Enclave::new(WorkerType::Identity); + pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); + run_to_block(2); assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); @@ -53,12 +58,15 @@ fn claim_is_ok() { // run to next reward distribution round, alice should win all rewards run_to_block(7); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { - total: round_reward(), - distributed: round_reward(), - round_index: 2, - }, + Event::::RewardDistributionStarted { round_index: 2 }, + )); + // calculates the rewards + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + 2, + vec![(alice(), 0)] )); + assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -66,7 +74,6 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), - last_token_distributed_round: 0, } ); @@ -90,7 +97,6 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, - last_token_distributed_round: 0, } ); @@ -114,7 +120,6 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, - last_token_distributed_round: 0, } ); diff --git a/runtime/litentry/src/lib.rs b/runtime/litentry/src/lib.rs index 29171d88d9..5a529ab3f6 100644 --- a/runtime/litentry/src/lib.rs +++ b/runtime/litentry/src/lib.rs @@ -28,8 +28,8 @@ use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use frame_support::{ construct_runtime, parameter_types, traits::{ - ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, EnsureOrigin, Everything, - FindAuthor, InstanceFilter, OnFinalize, SortedMembers, WithdrawReasons, + ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, EnsureOrigin, + Everything, FindAuthor, InstanceFilter, OnFinalize, SortedMembers, WithdrawReasons, }, weights::{constants::RocksDbWeight, ConstantMultiplier, Weight}, ConsensusEngineId, PalletId, @@ -1128,6 +1128,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; type TEECallOrigin = EnsureEnclaveSigner; + type MaxIDGraphAccountsPerCall = ConstU16<1000>; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/runtime/paseo/src/lib.rs b/runtime/paseo/src/lib.rs index 7121e83eb1..179a0df95a 100644 --- a/runtime/paseo/src/lib.rs +++ b/runtime/paseo/src/lib.rs @@ -29,7 +29,7 @@ use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use frame_support::{ construct_runtime, parameter_types, traits::{ - ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, ContainsLengthBound, + ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, ContainsLengthBound, EnsureOrigin, Everything, FindAuthor, InstanceFilter, OnFinalize, SortedMembers, WithdrawReasons, }, @@ -1170,6 +1170,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; type TEECallOrigin = EnsureEnclaveSigner; + type MaxIDGraphAccountsPerCall = ConstU16<1000>; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/runtime/rococo/src/lib.rs b/runtime/rococo/src/lib.rs index 25ed6b2bf7..03e64dd4e5 100644 --- a/runtime/rococo/src/lib.rs +++ b/runtime/rococo/src/lib.rs @@ -28,7 +28,7 @@ use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use frame_support::{ construct_runtime, parameter_types, traits::{ - ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, ContainsLengthBound, + ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, ContainsLengthBound, EnsureOrigin, Everything, FindAuthor, InstanceFilter, OnFinalize, SortedMembers, WithdrawReasons, }, @@ -1169,6 +1169,7 @@ impl pallet_score_staking::Config for Runtime { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; type TEECallOrigin = EnsureEnclaveSigner; + type MaxIDGraphAccountsPerCall = ConstU16<1000>; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index c8eb71eb6f..9714a51cde 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -232,7 +232,7 @@ where Ok(()) } - fn update_staking_scores>( + fn distribute_staking_rewards>( &self, executor: &Executor, block_header: impl Header, @@ -315,36 +315,41 @@ where let extrinsic_sender = ParachainExtrinsicSender::new(); - let update_token_staking_amount_call_index = self + let distribute_rewards_call_index = self .node_metadata_repository - .get_from_metadata(|m| m.update_token_staking_amount_call_indexes()) + .get_from_metadata(|m| m.distribute_rewards_call_indexes()) .map_err(|_| { - Error::Other( - "Metadata retrieval for update_token_staking_amount_call_indexes failed".into(), - ) + Error::Other("Metadata retrieval for distribute_rewards_call_indexes failed".into()) })? .map_err(|_| Error::Other("Invalid metadata".into()))?; - for account_id in account_ids.iter() { - let default_id_graph = Vec::new(); - let id_graph = accounts_graphs.get(account_id).unwrap_or(&default_id_graph); - let staking_amount: Balance = id_graph - .iter() - .filter_map(|identity| { - let delegator = delegator_states.get(identity)?; - Some(delegator.total) - }) - .sum(); + let id_graphs_staking: Vec<(AccountId, Balance)> = account_ids + .into_iter() + .map(|account_id| { + let default_id_graph = Vec::new(); + let id_graph = accounts_graphs.get(&account_id).unwrap_or(&default_id_graph); + let staking_amount: Balance = id_graph + .iter() + .filter_map(|identity| { + let delegator = delegator_states.get(identity)?; + Some(delegator.total) + }) + .sum(); + (account_id, staking_amount) + }) + .collect(); + + id_graphs_staking.chunks(1000).for_each(|batch| { let call = OpaqueCall::from_tuple(&( - update_token_staking_amount_call_index, - account_id, - staking_amount, + distribute_rewards_call_index, round_index, + batch.to_vec(), )); extrinsic_sender .send(call) - .map_err(|_| Error::Other("Failed to send extrinsic".into()))?; - } + .map_err(|_| Error::Other("Failed to send extrinsic".into())) + .unwrap(); + }); let complete_reward_distribution_call_index = self .node_metadata_repository @@ -510,7 +515,7 @@ where .iter() .try_for_each(|event| { let event_hash = hash_of(&event); - let result = self.update_staking_scores( + let result = self.distribute_staking_rewards( executor, block_header.clone(), event.round_index, diff --git a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs index a4461eb72a..295cc4ee48 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs @@ -92,7 +92,7 @@ pub struct NodeMetadataMock { //ScoreStaking score_staking_module: u8, - update_token_staking_amount: u8, + distribute_rewards: u8, complete_reward_distribution: u8, } @@ -151,7 +151,7 @@ impl NodeMetadataMock { runtime_transaction_version: 4, score_staking_module: 100u8, - update_token_staking_amount: 0u8, + distribute_rewards: 0u8, complete_reward_distribution: 1u8, } } @@ -188,8 +188,8 @@ impl TeebagCallIndexes for NodeMetadataMock { } impl ScoreStakingCallIndexes for NodeMetadataMock { - fn update_token_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { - Ok([self.score_staking_module, self.update_token_staking_amount]) + fn distribute_rewards_call_indexes(&self) -> Result<[u8; 2]> { + Ok([self.score_staking_module, self.distribute_rewards]) } fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]> { diff --git a/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs b/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs index 9450e36c01..91f31fe3ab 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs @@ -21,15 +21,16 @@ pub const SCORE_STAKING: &str = "ScoreStaking"; // we only list the extrinsics that we care pub trait ScoreStakingCallIndexes { - fn update_token_staking_amount_call_indexes(&self) -> Result<[u8; 2]>; + fn distribute_rewards_call_indexes(&self) -> Result<[u8; 2]>; fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]>; } impl ScoreStakingCallIndexes for NodeMetadata { - fn update_token_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { - self.call_indexes(SCORE_STAKING, "update_token_staking_amount") + fn distribute_rewards_call_indexes(&self) -> Result<[u8; 2]> { + self.call_indexes(SCORE_STAKING, "distribute_rewards") } + fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]> { self.call_indexes(SCORE_STAKING, "complete_reward_distribution") } diff --git a/tee-worker/core-primitives/types/src/parentchain/events.rs b/tee-worker/core-primitives/types/src/parentchain/events.rs index 3cce6e2e10..45b2838604 100644 --- a/tee-worker/core-primitives/types/src/parentchain/events.rs +++ b/tee-worker/core-primitives/types/src/parentchain/events.rs @@ -247,20 +247,13 @@ impl StaticEvent for AssertionCreated { #[derive(Encode, Decode, Debug)] pub struct RewardDistributionStarted { - pub total: Balance, - pub distributed: Balance, pub round_index: u32, } impl core::fmt::Display for RewardDistributionStarted { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - let message = format!( - "{:?} :: total: {}, distributed: {}, round_index: {}", - RewardDistributionStarted::EVENT, - self.total, - self.distributed, - self.round_index - ); + let message = + format!("{:?} :: round_index: {}", RewardDistributionStarted::EVENT, self.round_index); write!(f, "{}", message) } } From 58bad421b9e72c8cb45c49054b7f0f7159eaee4b Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 23 Sep 2024 09:53:32 +0000 Subject: [PATCH 03/14] refactoring identity staking rewards distribution --- pallets/score-staking/src/lib.rs | 65 +++++++++++++----------------- pallets/score-staking/src/types.rs | 1 + 2 files changed, 30 insertions(+), 36 deletions(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index 912e1317a8..304e7534b3 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -51,7 +51,6 @@ use sp_runtime::{ traits::{CheckedSub, Zero}, Perbill, SaturatedConversion, }; -use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; pub use pallet::*; @@ -92,6 +91,7 @@ pub mod pallet { if let Some(mut s) = Scores::::get(delegator) { let _ = Self::update_total_score(s.score, 0); s.score = 0; + s.total_staking_amount = BalanceOf::::zero(); Scores::::insert(delegator, s); } @@ -119,8 +119,6 @@ pub mod pallet { type AccountIdConvert: AccountIdConvert; // For extrinsics that should only be called by origins from TEE type TEECallOrigin: EnsureOrigin; - #[pallet::constant] - type MaxIDGraphAccountsPerCall: Get; } #[pallet::error] @@ -157,10 +155,10 @@ pub mod pallet { ScoreUserCountUnderflow, // when the score user count would exceed `MaxScoreUserCount` MaxScoreUserCountReached, + // when the token staking amount has been updated already for the round + TotalStakingAmountAlreadyUpdated, // the token staking amount has been updated already for the round RoundRewardsAlreadyDistributed, - // the maximum number of IDGraph accounts has been reached - MaxIDGraphAccountsPerCallReached, } #[pallet::event] @@ -174,6 +172,7 @@ pub mod pallet { ScoreRemoved { who: Identity }, ScoreCleared {}, RewardDistributionStarted { round_index: RoundIndex }, + TotalStakingAmountUpdated { account: T::AccountId, amount: BalanceOf }, RewardDistributionCompleted { round_index: RoundIndex }, RewardClaimed { who: T::AccountId, amount: BalanceOf }, } @@ -258,7 +257,7 @@ pub mod pallet { } // We are about to start a new round - // - update round info + // update round info let round_index = r.index.saturating_add(1); r.index = round_index; r.start_block = now; @@ -431,43 +430,48 @@ pub mod pallet { #[pallet::call_index(9)] #[pallet::weight((195_000_000, DispatchClass::Normal))] + pub fn update_total_staking_amount( + origin: OriginFor, + account: T::AccountId, + amount: BalanceOf, + ) -> DispatchResultWithPostInfo { + let _ = T::TEECallOrigin::ensure_origin(origin)?; + + match Scores::::get(&account) { + Some(mut s) => { + s.total_staking_amount = amount; + Scores::::insert(account.clone(), s); + Self::deposit_event(Event::TotalStakingAmountUpdated { + account: account.clone(), + amount, + }); + Ok(Pays::No.into()) + }, + None => Err(Error::::UserNotExist.into()), + } + } + + #[pallet::call_index(10)] + #[pallet::weight((195_000_000, DispatchClass::Normal))] pub fn distribute_rewards( origin: OriginFor, round_index: RoundIndex, - id_graphs_staking: Vec<(T::AccountId, BalanceOf)>, ) -> DispatchResultWithPostInfo { let _ = T::TEECallOrigin::ensure_origin(origin)?; - ensure!( round_index > LastTokenDistributionRound::::get(), Error::::RoundRewardsAlreadyDistributed ); - - let id_graphs_staking_map: BTreeMap> = - id_graphs_staking.into_iter().collect(); - - ensure!( - id_graphs_staking_map.len() <= T::MaxIDGraphAccountsPerCall::get() as usize, - Error::::MaxIDGraphAccountsPerCallReached - ); - let round_reward: BalanceOf = (T::YearlyInflation::get() * T::YearlyIssuance::get() / YEARS.into()) * Self::round_config().interval.into(); let round_reward_u128 = round_reward.saturated_into::(); - let total_stake_u128 = ParaStaking::Pallet::::total().saturated_into::(); let total_score = Self::total_score(); let n = Self::round_config().stake_coef_n; let m = Self::round_config().stake_coef_m; for (a, mut p) in Scores::::iter() { - let default_staking = BalanceOf::::zero(); - let id_graph_staking = id_graphs_staking_map.get(&a).unwrap_or(&default_staking); - let user_stake_u128 = ParaStaking::Pallet::::delegator_state(&a) - .map(|s| s.total) - .unwrap_or_default() - .saturated_into::() - + (*id_graph_staking).saturated_into::(); + let user_stake_u128 = p.total_staking_amount.saturated_into::(); let user_reward_u128 = round_reward_u128 .saturating_mul(p.score.into()) .saturating_div(total_score.into()) @@ -481,17 +485,6 @@ pub mod pallet { Scores::::insert(&a, p); } - Ok(Pays::No.into()) - } - - #[pallet::call_index(10)] - #[pallet::weight((195_000_000, DispatchClass::Normal))] - pub fn complete_reward_distribution( - origin: OriginFor, - round_index: RoundIndex, - ) -> DispatchResultWithPostInfo { - let _ = T::TEECallOrigin::ensure_origin(origin)?; - LastTokenDistributionRound::::put(round_index); Self::deposit_event(Event::RewardDistributionCompleted { round_index }); diff --git a/pallets/score-staking/src/types.rs b/pallets/score-staking/src/types.rs index 1456f4e67d..eb7dfa6236 100644 --- a/pallets/score-staking/src/types.rs +++ b/pallets/score-staking/src/types.rs @@ -83,4 +83,5 @@ pub struct ScorePayment { pub total_reward: Balance, pub last_round_reward: Balance, pub unpaid_reward: Balance, + pub total_staking_amount: Balance, } From 1a3914f67e4a861c397e151a23b79e054575faf5 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 23 Sep 2024 09:54:04 +0000 Subject: [PATCH 04/14] updating mocks --- pallets/score-staking/src/mock.rs | 1 - precompiles/score-staking/src/mock.rs | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/pallets/score-staking/src/mock.rs b/pallets/score-staking/src/mock.rs index cb0d433b82..7e815d464a 100644 --- a/pallets/score-staking/src/mock.rs +++ b/pallets/score-staking/src/mock.rs @@ -171,7 +171,6 @@ impl pallet_score_staking::Config for Test { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; type TEECallOrigin = EnsureEnclaveSigner; - type MaxIDGraphAccountsPerCall = ConstU16<2>; } parameter_types! { diff --git a/precompiles/score-staking/src/mock.rs b/precompiles/score-staking/src/mock.rs index 6d5729437a..c127b263d8 100644 --- a/precompiles/score-staking/src/mock.rs +++ b/precompiles/score-staking/src/mock.rs @@ -27,7 +27,7 @@ use frame_system::EnsureRoot; use pallet_evm::{AddressMapping, EnsureAddressNever, EnsureAddressRoot}; use pallet_score_staking::{AccountIdConvert, PoolState, RoundSetting}; use precompile_utils::precompile_set::{AddressU64, PrecompileAt, PrecompileSetBuilder}; -use sp_core::{ConstU128, ConstU16, ConstU32, ConstU64, H160, H256}; +use sp_core::{ConstU128, ConstU32, ConstU64, H160, H256}; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, Percent, @@ -169,7 +169,6 @@ impl pallet_score_staking::Config for Test { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<2>; type TEECallOrigin = EnsureEnclaveSigner; - type MaxIDGraphAccountsPerCall = ConstU16<2>; } pub fn precompile_address() -> H160 { From eb7f1fe3c5c13f9c7675a9f4e4a1a15215761c3d Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 23 Sep 2024 09:54:15 +0000 Subject: [PATCH 05/14] updating tests --- pallets/score-staking/src/tests.rs | 270 ++++++++++++------------- precompiles/score-staking/src/tests.rs | 26 ++- 2 files changed, 145 insertions(+), 151 deletions(-) diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index 03d0925d9d..6c93b232f0 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -160,7 +160,6 @@ fn score_staking_works() { assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); let alice_staking = 900; - let alice_id_graph_staking = 0; let mut alice_score = 500; run_to_block(3); @@ -181,7 +180,8 @@ fn score_staking_works() { score: alice_score, total_reward: 0, last_round_reward: 0, - unpaid_reward: 0 + unpaid_reward: 0, + total_staking_amount: 0 } ); @@ -211,18 +211,22 @@ fn score_staking_works() { let round_reward = calculate_round_reward( alice_score.into(), total_score.into(), - alice_staking + alice_id_graph_staking, + alice_staking, total_staking, ); alice_total_reward += round_reward; - assert_ok!(ScoreStaking::distribute_rewards( + assert_ok!(ScoreStaking::update_total_staking_amount( RuntimeOrigin::signed(alice()), - 2, - vec![(alice(), alice_id_graph_staking)] + alice(), + alice_staking )); - assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 2)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { + account: alice(), + amount: alice_staking, + })); + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { round_index: 2, })); @@ -234,6 +238,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, + total_staking_amount: alice_staking } ); @@ -248,17 +253,15 @@ fn score_staking_works() { let round_reward = calculate_round_reward( alice_score.into(), total_score.into(), - alice_staking + alice_id_graph_staking, + alice_staking, total_staking, ); alice_total_reward += round_reward; - // calculates the rewards - assert_ok!(ScoreStaking::distribute_rewards( - RuntimeOrigin::signed(alice()), - 3, - vec![(alice(), alice_id_graph_staking)] - )); + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 3)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 3, + })); assert_eq!( ScoreStaking::scores(alice()).unwrap(), @@ -267,6 +270,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, + total_staking_amount: alice_staking } ); @@ -281,18 +285,17 @@ fn score_staking_works() { Event::::RewardDistributionStarted { round_index: 4 }, )); - assert_ok!(ScoreStaking::distribute_rewards( - RuntimeOrigin::signed(alice()), - 4, - vec![(alice(), alice_id_graph_staking)] - )); + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 4)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 4, + })); let total_staking = pallet_parachain_staking::Total::::get(); let total_score = ScoreStaking::total_score(); let round_reward = calculate_round_reward( alice_score.into(), total_score.into(), - alice_staking + alice_id_graph_staking, + alice_staking, total_staking, ); // total reward third distribution @@ -305,6 +308,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, + total_staking_amount: alice_staking } ); @@ -313,7 +317,6 @@ fn score_staking_works() { // add bob's score let mut bob_staking = 1600; let mut bob_score = 1000; - let bob_id_graph_staking = 0; assert_ok!(ParachainStaking::delegate(RuntimeOrigin::signed(bob()), alice(), bob_staking)); assert_eq!( @@ -332,11 +335,20 @@ fn score_staking_works() { System::assert_last_event(RuntimeEvent::ScoreStaking( Event::::RewardDistributionStarted { round_index: 5 }, )); - assert_ok!(ScoreStaking::distribute_rewards( + assert_ok!(ScoreStaking::update_total_staking_amount( RuntimeOrigin::signed(alice()), - 5, - vec![(alice(), alice_id_graph_staking), (bob(), bob_id_graph_staking)] + bob(), + bob_staking )); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { + account: bob(), + amount: bob_staking, + })); + + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 5)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 5, + })); // total rewards fourth distribution let total_staking = pallet_parachain_staking::Total::::get(); @@ -345,7 +357,7 @@ fn score_staking_works() { let alice_round_reward = calculate_round_reward( alice_score.into(), total_score.into(), - alice_staking + alice_id_graph_staking, + alice_staking, total_staking, ); alice_total_reward += alice_round_reward; @@ -354,7 +366,7 @@ fn score_staking_works() { let bob_round_reward = calculate_round_reward( bob_score.into(), total_score.into(), - bob_staking + bob_id_graph_staking, + bob_staking, total_staking, ); bob_total_reward += bob_round_reward; @@ -366,6 +378,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, + total_staking_amount: alice_staking } ); assert_eq!( @@ -375,6 +388,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: bob_round_reward, unpaid_reward: bob_total_reward, + total_staking_amount: bob_staking } ); @@ -400,11 +414,10 @@ fn score_staking_works() { System::assert_last_event(RuntimeEvent::ScoreStaking( Event::::RewardDistributionStarted { round_index: 6 }, )); - assert_ok!(ScoreStaking::distribute_rewards( - RuntimeOrigin::signed(alice()), - 6, - vec![(alice(), alice_id_graph_staking), (bob(), bob_id_graph_staking)] - )); + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 6)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 6, + })); // total rewards fifth distribution let total_staking = pallet_parachain_staking::Total::::get(); @@ -413,7 +426,7 @@ fn score_staking_works() { let alice_round_reward = calculate_round_reward( alice_score.into(), total_score.into(), - alice_staking + alice_id_graph_staking, + alice_staking, total_staking, ); alice_total_reward += alice_round_reward; @@ -421,7 +434,7 @@ fn score_staking_works() { let bob_round_reward = calculate_round_reward( bob_score.into(), total_score.into(), - bob_staking + bob_id_graph_staking, + bob_staking, total_staking, ); bob_total_reward += bob_round_reward; @@ -433,6 +446,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, + total_staking_amount: alice_staking } ); assert_eq!( @@ -442,6 +456,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: bob_round_reward, unpaid_reward: bob_total_reward, + total_staking_amount: bob_staking } ); @@ -459,11 +474,10 @@ fn score_staking_works() { System::assert_last_event(RuntimeEvent::ScoreStaking( Event::::RewardDistributionStarted { round_index: 7 }, )); - assert_ok!(ScoreStaking::distribute_rewards( - RuntimeOrigin::signed(alice()), - 7, - vec![(alice(), alice_id_graph_staking), (bob(), bob_id_graph_staking)] - )); + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 7)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 7, + })); // total reward sixth distribution let total_staking = pallet_parachain_staking::Total::::get(); @@ -472,7 +486,7 @@ fn score_staking_works() { let alice_round_reward = calculate_round_reward( alice_score.into(), total_score.into(), - alice_staking + alice_id_graph_staking, + alice_staking, total_staking, ); alice_total_reward += alice_round_reward; @@ -480,7 +494,7 @@ fn score_staking_works() { let bob_round_reward = calculate_round_reward( bob_score.into(), total_score.into(), - bob_staking + bob_id_graph_staking, + bob_staking, total_staking, ); bob_total_reward += bob_round_reward; @@ -492,6 +506,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, + total_staking_amount: alice_staking } ); assert_eq!( @@ -501,6 +516,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: bob_round_reward, unpaid_reward: bob_total_reward, + total_staking_amount: bob_staking } ); @@ -512,11 +528,10 @@ fn score_staking_works() { System::assert_last_event(RuntimeEvent::ScoreStaking( Event::::RewardDistributionStarted { round_index: 8 }, )); - assert_ok!(ScoreStaking::distribute_rewards( - RuntimeOrigin::signed(alice()), - 8, - vec![(alice(), alice_id_graph_staking), (bob(), bob_id_graph_staking)] - )); + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 8)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 8, + })); // total reward sixth distribution let total_staking = pallet_parachain_staking::Total::::get(); @@ -525,7 +540,7 @@ fn score_staking_works() { let alice_round_reward = calculate_round_reward( alice_score.into(), total_score.into(), - alice_staking + alice_id_graph_staking, + alice_staking, total_staking, ); alice_total_reward += alice_round_reward; @@ -537,6 +552,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, + total_staking_amount: alice_staking } ); // bob should not participate in the reward calculation @@ -547,6 +563,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: 0, unpaid_reward: bob_total_reward, + total_staking_amount: bob_staking } ); assert_eq!(ScoreStaking::total_score(), alice_score); @@ -569,11 +586,12 @@ fn claim_works() { assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); run_to_block(3); + let alice_staking = 1000; pallet_parachain_staking::DelegatorState::::insert( alice(), - Delegator::new(bob(), bob(), 1000), + Delegator::new(bob(), bob(), alice_staking), ); - pallet_parachain_staking::Total::::put(1000); + pallet_parachain_staking::Total::::put(alice_staking); assert_ok!(ScoreStaking::update_score( RuntimeOrigin::signed(alice()), @@ -588,13 +606,38 @@ fn claim_works() { )); assert_eq!( ScoreStaking::scores(alice()).unwrap(), - ScorePayment { score: 2000, total_reward: 0, last_round_reward: 0, unpaid_reward: 0 } + ScorePayment { + score: 2000, + total_reward: 0, + last_round_reward: 0, + unpaid_reward: 0, + total_staking_amount: 0 + } ); - assert_ok!(ScoreStaking::distribute_rewards( + assert_ok!(ScoreStaking::update_total_staking_amount( RuntimeOrigin::signed(alice()), - 2, - vec![(alice(), 0)] + alice(), + alice_staking )); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { + account: alice(), + amount: alice_staking, + })); + + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 2, + })); + assert_eq!( + ScoreStaking::scores(alice()).unwrap(), + ScorePayment { + score: 2000, + total_reward: round_reward(), + last_round_reward: round_reward(), + unpaid_reward: round_reward(), + total_staking_amount: alice_staking + } + ); assert_ok!(ScoreStaking::claim(RuntimeOrigin::signed(alice()), 200)); System::assert_last_event(RuntimeEvent::ScoreStaking(Event::::RewardClaimed { @@ -608,6 +651,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, + total_staking_amount: alice_staking } ); @@ -623,6 +667,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, + total_staking_amount: alice_staking } ); @@ -643,7 +688,7 @@ fn distribute_rewards_works() { run_to_block(2); assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); - let alice_staking = 900; + let mut alice_staking = 900; let alice_score = 500; run_to_block(3); @@ -665,13 +710,23 @@ fn distribute_rewards_works() { Event::::RewardDistributionStarted { round_index: 2 }, )); - let alice_id_graph_staking = 1000; + let alice_id_graph_staking = 1900; - assert_ok!(ScoreStaking::distribute_rewards( + assert_ok!(ScoreStaking::update_total_staking_amount( RuntimeOrigin::signed(alice()), - 2, - vec![(alice(), alice_id_graph_staking)] + alice(), + alice_id_graph_staking )); + alice_staking = alice_id_graph_staking; + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { + account: alice(), + amount: alice_staking, + })); + + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 2, + })); let mut alice_total_reward = 0; let total_staking = pallet_parachain_staking::Total::::get(); @@ -679,7 +734,7 @@ fn distribute_rewards_works() { let round_reward = calculate_round_reward( alice_score.into(), total_score.into(), - alice_staking + alice_id_graph_staking, + alice_staking, total_staking, ); alice_total_reward += round_reward; @@ -691,6 +746,7 @@ fn distribute_rewards_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, + total_staking_amount: alice_staking } ); @@ -700,19 +756,17 @@ fn distribute_rewards_works() { Event::::RewardDistributionStarted { round_index: 3 }, )); - assert_ok!(ScoreStaking::distribute_rewards( - RuntimeOrigin::signed(alice()), - 3, - vec![(alice(), alice_id_graph_staking)] - )); - assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 3)); + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 3)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 3, + })); let total_staking = pallet_parachain_staking::Total::::get(); let total_score = ScoreStaking::total_score(); let round_reward = calculate_round_reward( alice_score.into(), total_score.into(), - alice_staking + alice_id_graph_staking, + alice_staking, total_staking, ); alice_total_reward += round_reward; @@ -728,6 +782,7 @@ fn distribute_rewards_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, + total_staking_amount: alice_staking } ); }) @@ -763,16 +818,13 @@ fn distribute_rewards_round_rewards_already_distributed_works() { System::assert_last_event(RuntimeEvent::ScoreStaking( Event::::RewardDistributionStarted { round_index: 2 }, )); - - assert_ok!(ScoreStaking::distribute_rewards( - RuntimeOrigin::signed(alice()), - 2, - vec![(alice(), 0)] - )); - assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 2)); + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 2, + })); assert_noop!( - ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2, vec![(alice(), 0)]), + ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2), Error::::RoundRewardsAlreadyDistributed ); }) @@ -782,82 +834,12 @@ fn distribute_rewards_round_rewards_already_distributed_works() { fn distribute_rewards_origin_check_works() { new_test_ext(false).execute_with(|| { assert_noop!( - ScoreStaking::distribute_rewards(RuntimeOrigin::signed(bob()), 1, vec![(alice(), 0)]), + ScoreStaking::distribute_rewards(RuntimeOrigin::signed(bob()), 1), sp_runtime::DispatchError::BadOrigin ); }) } -#[test] -fn distribute_rewards_max_id_graph_accounts_per_call_check_works() { - new_test_ext(true).execute_with(|| { - let enclave = Enclave::new(WorkerType::Identity); - pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); - - run_to_block(2); - assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); - - let alice_staking = 900; - let alice_score = 500; - - run_to_block(3); - pallet_parachain_staking::DelegatorState::::insert( - alice(), - Delegator::new(bob(), bob(), alice_staking), - ); - pallet_parachain_staking::Total::::put(alice_staking); - assert_ok!(ScoreStaking::update_score( - RuntimeOrigin::signed(alice()), - alice().into(), - alice_score - )); - - // run to next reward distribution round, alice should win all rewards - run_to_block(7); - - System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 2 }, - )); - - assert_noop!( - ScoreStaking::distribute_rewards( - RuntimeOrigin::signed(alice()), - 2, - vec![(alice(), 0), (bob(), 0), (charlie(), 0)] - ), - Error::::MaxIDGraphAccountsPerCallReached - ); - }); -} - -#[test] -fn complete_reward_distribution_works() { - new_test_ext(false).execute_with(|| { - let enclave = Enclave::new(WorkerType::Identity); - pallet_teebag::EnclaveRegistry::::insert(alice(), enclave); - - assert_eq!(ScoreStaking::last_rewards_distribution_round(), 0); - - assert_ok!(ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 1)); - - System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionCompleted { round_index: 1 }, - )); - - assert_eq!(ScoreStaking::last_rewards_distribution_round(), 1); - }); -} - -#[test] -fn complete_reward_distribution_origin_check_works() { - new_test_ext(false).execute_with(|| { - assert_noop!( - ScoreStaking::complete_reward_distribution(RuntimeOrigin::signed(alice()), 2), - sp_runtime::DispatchError::BadOrigin - ); - }); -} - #[test] fn on_all_delegation_removed_works() { new_test_ext(true).execute_with(|| { diff --git a/precompiles/score-staking/src/tests.rs b/precompiles/score-staking/src/tests.rs index ecf45855f0..206ff2d454 100644 --- a/precompiles/score-staking/src/tests.rs +++ b/precompiles/score-staking/src/tests.rs @@ -23,7 +23,6 @@ use pallet_score_staking::{Error, Event, ScorePayment}; use pallet_teebag::{Enclave, WorkerType}; use precompile_utils::testing::*; use sp_runtime::Perbill; -use sp_std::vec; fn round_reward() -> Balance { (Perbill::from_perthousand(5) * 100_000_000 * UNIT / (YEARS as u128)) * 5 @@ -43,11 +42,12 @@ fn claim_is_ok() { assert_ok!(ScoreStaking::start_pool(RuntimeOrigin::root())); run_to_block(3); + let alice_staking = 1000; pallet_parachain_staking::DelegatorState::::insert( alice(), - Delegator::new(bob(), bob(), 1000), + Delegator::new(bob(), bob(), alice_staking), ); - pallet_parachain_staking::Total::::put(1000); + pallet_parachain_staking::Total::::put(alice_staking); assert_ok!(ScoreStaking::update_score( RuntimeOrigin::signed(alice()), @@ -60,12 +60,21 @@ fn claim_is_ok() { System::assert_last_event(RuntimeEvent::ScoreStaking( Event::::RewardDistributionStarted { round_index: 2 }, )); - // calculates the rewards - assert_ok!(ScoreStaking::distribute_rewards( + assert_ok!(ScoreStaking::update_total_staking_amount( RuntimeOrigin::signed(alice()), - 2, - vec![(alice(), 0)] + alice(), + alice_staking )); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { + account: alice(), + amount: alice_staking, + })); + + // calculates the rewards + assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + round_index: 2, + })); assert_eq!( ScoreStaking::scores(alice()).unwrap(), @@ -74,6 +83,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), + total_staking_amount: alice_staking, } ); @@ -97,6 +107,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, + total_staking_amount: alice_staking, } ); @@ -120,6 +131,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, + total_staking_amount: alice_staking, } ); From 9d42f2c0199891c4d7af1caf6708719f4e0ede97 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 23 Sep 2024 09:54:22 +0000 Subject: [PATCH 06/14] updating runtimes --- runtime/litentry/src/lib.rs | 5 ++--- runtime/paseo/src/lib.rs | 3 +-- runtime/rococo/src/lib.rs | 3 +-- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/runtime/litentry/src/lib.rs b/runtime/litentry/src/lib.rs index 5a529ab3f6..29171d88d9 100644 --- a/runtime/litentry/src/lib.rs +++ b/runtime/litentry/src/lib.rs @@ -28,8 +28,8 @@ use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use frame_support::{ construct_runtime, parameter_types, traits::{ - ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, EnsureOrigin, - Everything, FindAuthor, InstanceFilter, OnFinalize, SortedMembers, WithdrawReasons, + ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, EnsureOrigin, Everything, + FindAuthor, InstanceFilter, OnFinalize, SortedMembers, WithdrawReasons, }, weights::{constants::RocksDbWeight, ConstantMultiplier, Weight}, ConsensusEngineId, PalletId, @@ -1128,7 +1128,6 @@ impl pallet_score_staking::Config for Runtime { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; type TEECallOrigin = EnsureEnclaveSigner; - type MaxIDGraphAccountsPerCall = ConstU16<1000>; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/runtime/paseo/src/lib.rs b/runtime/paseo/src/lib.rs index 179a0df95a..7121e83eb1 100644 --- a/runtime/paseo/src/lib.rs +++ b/runtime/paseo/src/lib.rs @@ -29,7 +29,7 @@ use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use frame_support::{ construct_runtime, parameter_types, traits::{ - ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, ContainsLengthBound, + ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, ContainsLengthBound, EnsureOrigin, Everything, FindAuthor, InstanceFilter, OnFinalize, SortedMembers, WithdrawReasons, }, @@ -1170,7 +1170,6 @@ impl pallet_score_staking::Config for Runtime { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; type TEECallOrigin = EnsureEnclaveSigner; - type MaxIDGraphAccountsPerCall = ConstU16<1000>; } impl runtime_common::BaseRuntimeRequirements for Runtime {} diff --git a/runtime/rococo/src/lib.rs b/runtime/rococo/src/lib.rs index 03e64dd4e5..25ed6b2bf7 100644 --- a/runtime/rococo/src/lib.rs +++ b/runtime/rococo/src/lib.rs @@ -28,7 +28,7 @@ use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use frame_support::{ construct_runtime, parameter_types, traits::{ - ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Contains, ContainsLengthBound, + ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, ContainsLengthBound, EnsureOrigin, Everything, FindAuthor, InstanceFilter, OnFinalize, SortedMembers, WithdrawReasons, }, @@ -1169,7 +1169,6 @@ impl pallet_score_staking::Config for Runtime { type YearlyInflation = DefaultYearlyInflation; type MaxScoreUserCount = ConstU32<1_000_000>; type TEECallOrigin = EnsureEnclaveSigner; - type MaxIDGraphAccountsPerCall = ConstU16<1000>; } impl runtime_common::BaseRuntimeRequirements for Runtime {} From 79d40082a5d72e3310559faf1e0bb6a61d199795 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 23 Sep 2024 12:10:34 +0000 Subject: [PATCH 07/14] updating event parameters --- pallets/score-staking/src/lib.rs | 10 +++++----- pallets/score-staking/src/tests.rs | 8 ++++---- precompiles/score-staking/src/tests.rs | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/pallets/score-staking/src/lib.rs b/pallets/score-staking/src/lib.rs index 304e7534b3..e077e9d1d1 100644 --- a/pallets/score-staking/src/lib.rs +++ b/pallets/score-staking/src/lib.rs @@ -172,7 +172,7 @@ pub mod pallet { ScoreRemoved { who: Identity }, ScoreCleared {}, RewardDistributionStarted { round_index: RoundIndex }, - TotalStakingAmountUpdated { account: T::AccountId, amount: BalanceOf }, + TotalStakingAmountUpdated { account_id: T::AccountId, amount: BalanceOf }, RewardDistributionCompleted { round_index: RoundIndex }, RewardClaimed { who: T::AccountId, amount: BalanceOf }, } @@ -432,17 +432,17 @@ pub mod pallet { #[pallet::weight((195_000_000, DispatchClass::Normal))] pub fn update_total_staking_amount( origin: OriginFor, - account: T::AccountId, + account_id: T::AccountId, amount: BalanceOf, ) -> DispatchResultWithPostInfo { let _ = T::TEECallOrigin::ensure_origin(origin)?; - match Scores::::get(&account) { + match Scores::::get(&account_id) { Some(mut s) => { s.total_staking_amount = amount; - Scores::::insert(account.clone(), s); + Scores::::insert(account_id.clone(), s); Self::deposit_event(Event::TotalStakingAmountUpdated { - account: account.clone(), + account_id: account_id.clone(), amount, }); Ok(Pays::No.into()) diff --git a/pallets/score-staking/src/tests.rs b/pallets/score-staking/src/tests.rs index 6c93b232f0..5ae3094ab8 100644 --- a/pallets/score-staking/src/tests.rs +++ b/pallets/score-staking/src/tests.rs @@ -222,7 +222,7 @@ fn score_staking_works() { alice_staking )); System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account: alice(), + account_id: alice(), amount: alice_staking, })); @@ -341,7 +341,7 @@ fn score_staking_works() { bob_staking )); System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account: bob(), + account_id: bob(), amount: bob_staking, })); @@ -620,7 +620,7 @@ fn claim_works() { alice_staking )); System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account: alice(), + account_id: alice(), amount: alice_staking, })); @@ -719,7 +719,7 @@ fn distribute_rewards_works() { )); alice_staking = alice_id_graph_staking; System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account: alice(), + account_id: alice(), amount: alice_staking, })); diff --git a/precompiles/score-staking/src/tests.rs b/precompiles/score-staking/src/tests.rs index 206ff2d454..d0c0db241a 100644 --- a/precompiles/score-staking/src/tests.rs +++ b/precompiles/score-staking/src/tests.rs @@ -66,7 +66,7 @@ fn claim_is_ok() { alice_staking )); System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account: alice(), + account_id: alice(), amount: alice_staking, })); From 0c75cae4ab0994431ac88873c45462047d132d27 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 23 Sep 2024 13:03:08 +0000 Subject: [PATCH 08/14] updating metadata --- .../node-api/metadata/src/metadata_mocks.rs | 10 +++++----- .../node-api/metadata/src/pallet_score_staking.rs | 12 ++++++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs index 295cc4ee48..e376bccc71 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/metadata_mocks.rs @@ -92,8 +92,8 @@ pub struct NodeMetadataMock { //ScoreStaking score_staking_module: u8, + update_total_staking_amount: u8, distribute_rewards: u8, - complete_reward_distribution: u8, } impl NodeMetadataMock { @@ -151,8 +151,8 @@ impl NodeMetadataMock { runtime_transaction_version: 4, score_staking_module: 100u8, - distribute_rewards: 0u8, - complete_reward_distribution: 1u8, + update_total_staking_amount: 9u8, + distribute_rewards: 10u8, } } } @@ -192,8 +192,8 @@ impl ScoreStakingCallIndexes for NodeMetadataMock { Ok([self.score_staking_module, self.distribute_rewards]) } - fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]> { - Ok([self.score_staking_module, self.complete_reward_distribution]) + fn update_total_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { + Ok([self.score_staking_module, self.update_total_staking_amount]) } } diff --git a/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs b/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs index 91f31fe3ab..b4772f979f 100644 --- a/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs +++ b/tee-worker/core-primitives/node-api/metadata/src/pallet_score_staking.rs @@ -21,17 +21,17 @@ pub const SCORE_STAKING: &str = "ScoreStaking"; // we only list the extrinsics that we care pub trait ScoreStakingCallIndexes { - fn distribute_rewards_call_indexes(&self) -> Result<[u8; 2]>; + fn update_total_staking_amount_call_indexes(&self) -> Result<[u8; 2]>; - fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]>; + fn distribute_rewards_call_indexes(&self) -> Result<[u8; 2]>; } impl ScoreStakingCallIndexes for NodeMetadata { - fn distribute_rewards_call_indexes(&self) -> Result<[u8; 2]> { - self.call_indexes(SCORE_STAKING, "distribute_rewards") + fn update_total_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { + self.call_indexes(SCORE_STAKING, "update_total_staking_amount") } - fn complete_reward_distribution_call_indexes(&self) -> Result<[u8; 2]> { - self.call_indexes(SCORE_STAKING, "complete_reward_distribution") + fn distribute_rewards_call_indexes(&self) -> Result<[u8; 2]> { + self.call_indexes(SCORE_STAKING, "distribute_rewards") } } From bb9d48841ba2aac138df47c2ba133fb13068d70a Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Mon, 23 Sep 2024 13:16:32 +0000 Subject: [PATCH 09/14] updating event_handler to update staking amounts and distribute rewards --- .../src/integritee/event_handler.rs | 61 ++++++++----------- 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs index 9714a51cde..17a2b276e6 100644 --- a/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -292,7 +292,7 @@ where let shard = executor.get_default_shard(); - let accounts_graphs = self + let id_graphs = self .state_handler .execute_on_current(&shard, |state, _| { let mut id_graphs_accounts: BTreeMap> = BTreeMap::new(); @@ -315,58 +315,51 @@ where let extrinsic_sender = ParachainExtrinsicSender::new(); - let distribute_rewards_call_index = self + let update_total_staking_amount_call_index = self .node_metadata_repository - .get_from_metadata(|m| m.distribute_rewards_call_indexes()) + .get_from_metadata(|m| m.update_total_staking_amount_call_indexes()) .map_err(|_| { - Error::Other("Metadata retrieval for distribute_rewards_call_indexes failed".into()) + Error::Other( + "Metadata retrieval for update_token_staking_amount_call_indexes failed".into(), + ) })? .map_err(|_| Error::Other("Invalid metadata".into()))?; - let id_graphs_staking: Vec<(AccountId, Balance)> = account_ids - .into_iter() - .map(|account_id| { - let default_id_graph = Vec::new(); - let id_graph = accounts_graphs.get(&account_id).unwrap_or(&default_id_graph); - let staking_amount: Balance = id_graph + for account_id in account_ids.iter() { + let staking_amount: Balance = match id_graphs.get(account_id) { + Some(id_graph) => id_graph .iter() .filter_map(|identity| { let delegator = delegator_states.get(identity)?; Some(delegator.total) }) - .sum(); - (account_id, staking_amount) - }) - .collect(); - - id_graphs_staking.chunks(1000).for_each(|batch| { + .sum(), + None => match delegator_states.get(account_id) { + Some(delegator) => delegator.total, + None => 0, + }, + }; let call = OpaqueCall::from_tuple(&( - distribute_rewards_call_index, - round_index, - batch.to_vec(), + update_total_staking_amount_call_index, + account_id, + staking_amount, )); extrinsic_sender .send(call) - .map_err(|_| Error::Other("Failed to send extrinsic".into())) - .unwrap(); - }); + .map_err(|_| Error::Other("Failed to send extrinsic".into()))?; + } - let complete_reward_distribution_call_index = self + let distribute_rewards_call_index = self .node_metadata_repository - .get_from_metadata(|m| m.complete_reward_distribution_call_indexes()) + .get_from_metadata(|m| m.distribute_rewards_call_indexes()) .map_err(|_| { - Error::Other( - "Metadata retrieval for complete_reward_distribution_call_indexes failed" - .into(), - ) + Error::Other("Metadata retrieval for distribute_rewards_call_indexes failed".into()) })? .map_err(|_| Error::Other("Invalid metadata".into()))?; - - let complete_reward_distribution_call = - OpaqueCall::from_tuple(&(complete_reward_distribution_call_index.clone())); - extrinsic_sender.send(complete_reward_distribution_call).map_err(|_| { - Error::Other("Failed to send complete_reward_distribution_call extrinsic".into()) - })?; + let call = OpaqueCall::from_tuple(&(distribute_rewards_call_index, round_index)); + extrinsic_sender + .send(call) + .map_err(|_| Error::Other("Failed to send extrinsic".into()))?; Ok(()) } From 66222a9704d67b5655ca50be5b0effc7d31a60b3 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 25 Sep 2024 09:06:07 +0000 Subject: [PATCH 10/14] removing failed merged code --- .../bitacross/core-primitives/storage/src/keys.rs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/tee-worker/bitacross/core-primitives/storage/src/keys.rs b/tee-worker/bitacross/core-primitives/storage/src/keys.rs index c4767097d7..43de4f667e 100644 --- a/tee-worker/bitacross/core-primitives/storage/src/keys.rs +++ b/tee-worker/bitacross/core-primitives/storage/src/keys.rs @@ -17,7 +17,6 @@ use codec::Encode; use frame_metadata::v14::StorageHasher; -use sp_core::crypto::AccountId32 as AccountId; use sp_std::vec::Vec; pub fn storage_value_key(module_prefix: &str, storage_prefix: &str) -> Vec { @@ -70,16 +69,3 @@ fn key_hash(key: &K, hasher: &StorageHasher) -> Vec { StorageHasher::Twox64Concat => sp_core::twox_64(&encoded_key).to_vec(), } } - -/// Extracts the AccountId from a storage key -pub fn key_to_account_id(key: &Vec) -> Option { - if key.len() >= 32 { - let account_id_bytes = &key[key.len() - 32..]; - let mut account_id_32_bytes = [0; 32]; - account_id_32_bytes.copy_from_slice(account_id_bytes); - - Some(AccountId::new(account_id_32_bytes)) - } else { - None - } -} From e098e6b7ca6aa71ef7cfee87ad4bd2fd45c8492a Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Wed, 25 Sep 2024 09:07:50 +0000 Subject: [PATCH 11/14] updating Cargo.lock --- tee-worker/identity/Cargo.lock | 134 ++++++++++++++++----------------- 1 file changed, 67 insertions(+), 67 deletions(-) diff --git a/tee-worker/identity/Cargo.lock b/tee-worker/identity/Cargo.lock index 4ffdf6c929..6852556873 100644 --- a/tee-worker/identity/Cargo.lock +++ b/tee-worker/identity/Cargo.lock @@ -384,7 +384,7 @@ dependencies = [ [[package]] name = "binary-merkle-tree" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -886,7 +886,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "strum 0.26.1", @@ -1837,7 +1837,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -1855,7 +1855,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-runtime-interface", "sp-std 5.0.0", @@ -1900,7 +1900,7 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "frame-benchmarking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-support-procedural", @@ -1914,7 +1914,7 @@ dependencies = [ "sp-api", "sp-application-crypto", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-runtime-interface", "sp-std 5.0.0", @@ -1925,14 +1925,14 @@ dependencies = [ [[package]] name = "frame-executive" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-tracing", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "frame-support" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bitflags 1.3.2", "environmental 1.1.4", @@ -1973,7 +1973,7 @@ dependencies = [ "sp-core", "sp-core-hashing-proc-macro", "sp-inherents", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-staking", "sp-state-machine", @@ -1986,7 +1986,7 @@ dependencies = [ [[package]] name = "frame-support-procedural" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "cfg-expr", @@ -2002,7 +2002,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support-procedural-tools-derive", "proc-macro-crate", @@ -2014,7 +2014,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools-derive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "frame-system" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "log 0.4.20", @@ -2032,7 +2032,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-version", @@ -5036,7 +5036,7 @@ dependencies = [ "serde 1.0.204", "sgx_tstd", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -5919,7 +5919,7 @@ checksum = "4d5d9eb14b174ee9aa2ef96dc2b94637a2d4b6e7cb873c7e171f0c20c6cf3eac" [[package]] name = "pallet-assets" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -5934,7 +5934,7 @@ dependencies = [ [[package]] name = "pallet-authorship" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -5948,7 +5948,7 @@ dependencies = [ [[package]] name = "pallet-balances" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -5979,7 +5979,7 @@ dependencies = [ "rlp", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6004,7 +6004,7 @@ dependencies = [ "rlp", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6022,7 +6022,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6056,14 +6056,14 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", ] [[package]] name = "pallet-session" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -6073,7 +6073,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-session", "sp-staking", @@ -6083,13 +6083,13 @@ dependencies = [ [[package]] name = "pallet-sudo" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", "parity-scale-codec", "scale-info", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6116,7 +6116,7 @@ dependencies = [ "serde 1.0.204", "serde_json 1.0.103", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "x509-cert", @@ -6125,7 +6125,7 @@ dependencies = [ [[package]] name = "pallet-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -6134,7 +6134,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-inherents", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-timestamp", @@ -6143,7 +6143,7 @@ dependencies = [ [[package]] name = "pallet-transaction-payment" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -6151,7 +6151,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -7325,7 +7325,7 @@ dependencies = [ [[package]] name = "sc-keystore" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "array-bytes 4.2.0", "async-trait", @@ -8088,7 +8088,7 @@ dependencies = [ [[package]] name = "sp-api" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -8108,7 +8108,7 @@ dependencies = [ [[package]] name = "sp-api-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "blake2", @@ -8122,20 +8122,20 @@ dependencies = [ [[package]] name = "sp-application-crypto" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-std 5.0.0", ] [[package]] name = "sp-arithmetic" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "integer-sqrt", "num-traits 0.2.16", @@ -8149,7 +8149,7 @@ dependencies = [ [[package]] name = "sp-consensus-grandpa" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "finality-grandpa", "log 0.4.20", @@ -8167,7 +8167,7 @@ dependencies = [ [[package]] name = "sp-consensus-slots" version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8179,7 +8179,7 @@ dependencies = [ [[package]] name = "sp-core" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "array-bytes 4.2.0", "bitflags 1.3.2", @@ -8223,7 +8223,7 @@ dependencies = [ [[package]] name = "sp-core-hashing" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "blake2b_simd", "byteorder 1.4.3", @@ -8252,7 +8252,7 @@ dependencies = [ [[package]] name = "sp-core-hashing-proc-macro" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -8263,7 +8263,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -8273,7 +8273,7 @@ dependencies = [ [[package]] name = "sp-externalities" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "environmental 1.1.4", "parity-scale-codec", @@ -8284,7 +8284,7 @@ dependencies = [ [[package]] name = "sp-inherents" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "impl-trait-for-tuples", @@ -8311,7 +8311,7 @@ dependencies = [ [[package]] name = "sp-io" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bytes 1.4.0", "ed25519", @@ -8337,7 +8337,7 @@ dependencies = [ [[package]] name = "sp-keyring" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "lazy_static", "sp-core", @@ -8348,7 +8348,7 @@ dependencies = [ [[package]] name = "sp-keystore" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "futures 0.3.28", "parity-scale-codec", @@ -8362,7 +8362,7 @@ dependencies = [ [[package]] name = "sp-metadata-ir" version = "0.1.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-metadata", "parity-scale-codec", @@ -8373,7 +8373,7 @@ dependencies = [ [[package]] name = "sp-panic-handler" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "backtrace", "lazy_static", @@ -8383,7 +8383,7 @@ dependencies = [ [[package]] name = "sp-runtime" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "either", "hash256-std-hasher", @@ -8397,7 +8397,7 @@ dependencies = [ "sp-application-crypto", "sp-arithmetic", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", "sp-std 5.0.0", "sp-weights", ] @@ -8405,7 +8405,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bytes 1.4.0", "impl-trait-for-tuples", @@ -8423,7 +8423,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "proc-macro-crate", @@ -8435,7 +8435,7 @@ dependencies = [ [[package]] name = "sp-session" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8448,7 +8448,7 @@ dependencies = [ [[package]] name = "sp-staking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8461,7 +8461,7 @@ dependencies = [ [[package]] name = "sp-state-machine" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -8481,7 +8481,7 @@ dependencies = [ [[package]] name = "sp-std" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" [[package]] name = "sp-std" @@ -8492,7 +8492,7 @@ checksum = "af0ee286f98455272f64ac5bb1384ff21ac029fbb669afbaf48477faff12760e" [[package]] name = "sp-storage" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "impl-serde", "parity-scale-codec", @@ -8505,7 +8505,7 @@ dependencies = [ [[package]] name = "sp-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "futures-timer", @@ -8520,7 +8520,7 @@ dependencies = [ [[package]] name = "sp-tracing" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "sp-std 5.0.0", @@ -8532,7 +8532,7 @@ dependencies = [ [[package]] name = "sp-trie" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "ahash 0.8.3", "hash-db 0.16.0", @@ -8555,7 +8555,7 @@ dependencies = [ [[package]] name = "sp-version" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "impl-serde", "parity-scale-codec", @@ -8572,7 +8572,7 @@ dependencies = [ [[package]] name = "sp-version-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "proc-macro2", @@ -8583,7 +8583,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "anyhow", "impl-trait-for-tuples", @@ -8597,7 +8597,7 @@ dependencies = [ [[package]] name = "sp-weights" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", From 4944b372c34e3f2206a1af715b3154bc1e4c282e Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 27 Sep 2024 12:18:08 +0000 Subject: [PATCH 12/14] refactoring rewards distribution once more --- parachain/pallets/score-staking/src/lib.rs | 143 +++--- parachain/pallets/score-staking/src/tests.rs | 438 ++++++++++++------ parachain/pallets/score-staking/src/types.rs | 2 +- .../precompiles/score-staking/src/tests.rs | 34 +- 4 files changed, 407 insertions(+), 210 deletions(-) diff --git a/parachain/pallets/score-staking/src/lib.rs b/parachain/pallets/score-staking/src/lib.rs index e077e9d1d1..52c92af750 100644 --- a/parachain/pallets/score-staking/src/lib.rs +++ b/parachain/pallets/score-staking/src/lib.rs @@ -47,10 +47,7 @@ use frame_support::{ }; use pallet_parachain_staking as ParaStaking; use sp_core::crypto::AccountId32; -use sp_runtime::{ - traits::{CheckedSub, Zero}, - Perbill, SaturatedConversion, -}; +use sp_runtime::{traits::CheckedSub, Perbill, SaturatedConversion}; pub use pallet::*; @@ -91,7 +88,6 @@ pub mod pallet { if let Some(mut s) = Scores::::get(delegator) { let _ = Self::update_total_score(s.score, 0); s.score = 0; - s.total_staking_amount = BalanceOf::::zero(); Scores::::insert(delegator, s); } @@ -157,24 +153,48 @@ pub mod pallet { MaxScoreUserCountReached, // when the token staking amount has been updated already for the round TotalStakingAmountAlreadyUpdated, - // the token staking amount has been updated already for the round + // the rewards have been distributed for the round RoundRewardsAlreadyDistributed, } #[pallet::event] #[pallet::generate_deposit(pub (crate) fn deposit_event)] pub enum Event { - PoolStarted { start_block: BlockNumberFor }, + PoolStarted { + start_block: BlockNumberFor, + }, PoolStopped {}, - ScoreFeederSet { new_score_feeder: Option }, - RoundConfigSet { new_config: RoundSetting }, - ScoreUpdated { who: Identity, new_score: Score }, - ScoreRemoved { who: Identity }, + ScoreFeederSet { + new_score_feeder: Option, + }, + RoundConfigSet { + new_config: RoundSetting, + }, + ScoreUpdated { + who: Identity, + new_score: Score, + }, + ScoreRemoved { + who: Identity, + }, ScoreCleared {}, - RewardDistributionStarted { round_index: RoundIndex }, - TotalStakingAmountUpdated { account_id: T::AccountId, amount: BalanceOf }, - RewardDistributionCompleted { round_index: RoundIndex }, - RewardClaimed { who: T::AccountId, amount: BalanceOf }, + RewardDistributionStarted { + round_index: RoundIndex, + total_stake: BalanceOf, + total_score: Score, + }, + RewardDistributed { + who: T::AccountId, + amount: BalanceOf, + round_index: RoundIndex, + }, + RewardDistributionCompleted { + round_index: RoundIndex, + }, + RewardClaimed { + who: T::AccountId, + amount: BalanceOf, + }, } #[pallet::storage] @@ -215,11 +235,6 @@ pub mod pallet { #[pallet::getter(fn state)] pub type State = StorageValue<_, PoolState, ValueQuery>; - /// The round index of the last token distribution - #[pallet::storage] - #[pallet::getter(fn last_rewards_distribution_round)] - pub type LastTokenDistributionRound = StorageValue<_, RoundIndex, ValueQuery>; - #[pallet::genesis_config] pub struct GenesisConfig { pub state: PoolState, @@ -242,14 +257,14 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { fn on_initialize(now: BlockNumberFor) -> Weight { - let mut weight = T::DbWeight::get().reads_writes(1, 0); // Self::state() + let mut weight = T::DbWeight::get().reads(1); // Self::state() if Self::state() == PoolState::Stopped { return weight; } let mut r = Round::::get(); - weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 0)); + weight = weight.saturating_add(T::DbWeight::get().reads(1)); if !is_modulo(now - r.start_block, Self::round_config().interval.into()) { // nothing to do there @@ -264,7 +279,15 @@ pub mod pallet { Round::::put(r); weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1)); - Self::deposit_event(Event::::RewardDistributionStarted { round_index }); + let total_stake_u128 = ParaStaking::Pallet::::total().saturated_into::(); + let total_score = Self::total_score(); + weight = weight.saturating_add(T::DbWeight::get().reads(2)); + + Self::deposit_event(Event::::RewardDistributionStarted { + round_index, + total_stake: total_stake_u128.saturated_into::>(), + total_score, + }); weight } @@ -430,21 +453,51 @@ pub mod pallet { #[pallet::call_index(9)] #[pallet::weight((195_000_000, DispatchClass::Normal))] - pub fn update_total_staking_amount( + pub fn distribute_rewards( origin: OriginFor, account_id: T::AccountId, - amount: BalanceOf, + user_stake: BalanceOf, + round_index: RoundIndex, + total_stake: BalanceOf, + total_score: Score, ) -> DispatchResultWithPostInfo { let _ = T::TEECallOrigin::ensure_origin(origin)?; match Scores::::get(&account_id) { Some(mut s) => { - s.total_staking_amount = amount; - Scores::::insert(account_id.clone(), s); - Self::deposit_event(Event::TotalStakingAmountUpdated { - account_id: account_id.clone(), - amount, + if round_index <= s.last_token_distribution_round { + return Err(Error::::RoundRewardsAlreadyDistributed.into()); + } + let round_reward: BalanceOf = + (T::YearlyInflation::get() * T::YearlyIssuance::get() / YEARS.into()) + * Self::round_config().interval.into(); + let round_reward_u128 = round_reward.saturated_into::(); + + let n = Self::round_config().stake_coef_n; + let m = Self::round_config().stake_coef_m; + + let total_stake_u128 = total_stake.saturated_into::(); + let user_stake_u128 = user_stake.saturated_into::(); + + let user_reward_u128 = round_reward_u128 + .saturating_mul(s.score.into()) + .saturating_div(total_score.into()) + .saturating_mul(num_integer::Roots::nth_root(&user_stake_u128.pow(n), m)) + .saturating_div(num_integer::Roots::nth_root(&total_stake_u128.pow(n), m)); + let user_reward = user_reward_u128.saturated_into::>(); + + s.last_round_reward = user_reward; + s.total_reward += user_reward; + s.unpaid_reward += user_reward; + s.last_token_distribution_round = round_index; + Scores::::insert(&account_id, s); + + Self::deposit_event(Event::RewardDistributed { + who: account_id, + amount: user_reward, + round_index, }); + Ok(Pays::No.into()) }, None => Err(Error::::UserNotExist.into()), @@ -453,39 +506,11 @@ pub mod pallet { #[pallet::call_index(10)] #[pallet::weight((195_000_000, DispatchClass::Normal))] - pub fn distribute_rewards( + pub fn complete_rewards_distribution( origin: OriginFor, round_index: RoundIndex, ) -> DispatchResultWithPostInfo { let _ = T::TEECallOrigin::ensure_origin(origin)?; - ensure!( - round_index > LastTokenDistributionRound::::get(), - Error::::RoundRewardsAlreadyDistributed - ); - let round_reward: BalanceOf = (T::YearlyInflation::get() * T::YearlyIssuance::get() - / YEARS.into()) * Self::round_config().interval.into(); - let round_reward_u128 = round_reward.saturated_into::(); - let total_stake_u128 = ParaStaking::Pallet::::total().saturated_into::(); - let total_score = Self::total_score(); - let n = Self::round_config().stake_coef_n; - let m = Self::round_config().stake_coef_m; - - for (a, mut p) in Scores::::iter() { - let user_stake_u128 = p.total_staking_amount.saturated_into::(); - let user_reward_u128 = round_reward_u128 - .saturating_mul(p.score.into()) - .saturating_div(total_score.into()) - .saturating_mul(num_integer::Roots::nth_root(&user_stake_u128.pow(n), m)) - .saturating_div(num_integer::Roots::nth_root(&total_stake_u128.pow(n), m)); - let user_reward = user_reward_u128.saturated_into::>(); - - p.last_round_reward = user_reward; - p.total_reward += user_reward; - p.unpaid_reward += user_reward; - Scores::::insert(&a, p); - } - - LastTokenDistributionRound::::put(round_index); Self::deposit_event(Event::RewardDistributionCompleted { round_index }); diff --git a/parachain/pallets/score-staking/src/tests.rs b/parachain/pallets/score-staking/src/tests.rs index 5ae3094ab8..2e31c00c96 100644 --- a/parachain/pallets/score-staking/src/tests.rs +++ b/parachain/pallets/score-staking/src/tests.rs @@ -130,7 +130,11 @@ fn default_mint_works() { // run to next reward distribution round run_to_block(7); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 2 }, + Event::::RewardDistributionStarted { + round_index: 2, + total_stake: 0, + total_score: 0, + }, )); }); } @@ -181,7 +185,7 @@ fn score_staking_works() { total_reward: 0, last_round_reward: 0, unpaid_reward: 0, - total_staking_amount: 0 + last_token_distribution_round: 0, } ); @@ -202,7 +206,11 @@ fn score_staking_works() { // run to next reward distribution round, alice should win all rewards run_to_block(7); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 2 }, + Event::::RewardDistributionStarted { + round_index: 2, + total_stake: alice_staking, + total_score: alice_score, + }, )); // total reward first distribution let mut alice_total_reward = 0; @@ -216,18 +224,17 @@ fn score_staking_works() { ); alice_total_reward += round_reward; - assert_ok!(ScoreStaking::update_total_staking_amount( + assert_ok!(ScoreStaking::distribute_rewards( RuntimeOrigin::signed(alice()), alice(), - alice_staking + alice_staking, + 2, + total_staking, + total_score )); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account_id: alice(), - amount: alice_staking, - })); - - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: round_reward, round_index: 2, })); @@ -238,18 +245,22 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, - total_staking_amount: alice_staking + last_token_distribution_round: 2, } ); // alice's winning should accumulate run_to_block(12); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 3 }, + Event::::RewardDistributionStarted { + round_index: 3, + total_stake: total_staking, + total_score, + }, )); // total reward second distribution - let total_staking = pallet_parachain_staking::Total::::get(); - let total_score = ScoreStaking::total_score(); let round_reward = calculate_round_reward( alice_score.into(), total_score.into(), @@ -258,8 +269,17 @@ fn score_staking_works() { ); alice_total_reward += round_reward; - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 3)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + alice(), + alice_staking, + 3, + total_staking, + total_score + )); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: round_reward, round_index: 3, })); @@ -270,7 +290,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, - total_staking_amount: alice_staking + last_token_distribution_round: 3, } ); @@ -281,23 +301,37 @@ fn score_staking_works() { pallet_parachain_staking::Total::::put(alice_staking + other_staking); run_to_block(17); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 4 }, + Event::::RewardDistributionStarted { + round_index: 4, + total_stake: total_staking, + total_score, + }, )); - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 4)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { - round_index: 4, - })); - - let total_staking = pallet_parachain_staking::Total::::get(); - let total_score = ScoreStaking::total_score(); let round_reward = calculate_round_reward( alice_score.into(), total_score.into(), alice_staking, total_staking, ); + + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + alice(), + alice_staking, + 4, + total_staking, + total_score + )); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: round_reward, + round_index: 4, + })); + // total reward third distribution alice_total_reward += round_reward; @@ -308,7 +342,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, - total_staking_amount: alice_staking + last_token_distribution_round: 4, } ); @@ -332,43 +366,59 @@ fn score_staking_works() { assert_eq!(ScoreStaking::score_user_count(), 2); run_to_block(22); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); + System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 5 }, + Event::::RewardDistributionStarted { + round_index: 5, + total_stake: total_staking, + total_score, + }, )); - assert_ok!(ScoreStaking::update_total_staking_amount( + + assert_ok!(ScoreStaking::distribute_rewards( RuntimeOrigin::signed(alice()), - bob(), - bob_staking + alice(), + alice_staking, + 5, + total_staking, + total_score )); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account_id: bob(), - amount: bob_staking, - })); - - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 5)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { - round_index: 5, - })); - - // total rewards fourth distribution - let total_staking = pallet_parachain_staking::Total::::get(); - let total_score = ScoreStaking::total_score(); - let alice_round_reward = calculate_round_reward( alice_score.into(), total_score.into(), alice_staking, total_staking, ); - alice_total_reward += alice_round_reward; + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: alice_round_reward, + round_index: 5, + })); - let mut bob_total_reward = 0; + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + bob(), + bob_staking, + 5, + total_staking, + total_score + )); let bob_round_reward = calculate_round_reward( bob_score.into(), total_score.into(), bob_staking, total_staking, ); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: bob(), + amount: bob_round_reward, + round_index: 5, + })); + + alice_total_reward += alice_round_reward; + let mut bob_total_reward = 0; bob_total_reward += bob_round_reward; assert_eq!( @@ -378,7 +428,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, - total_staking_amount: alice_staking + last_token_distribution_round: 5, } ); assert_eq!( @@ -388,7 +438,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: bob_round_reward, unpaid_reward: bob_total_reward, - total_staking_amount: bob_staking + last_token_distribution_round: 5, } ); @@ -411,32 +461,58 @@ fn score_staking_works() { run_to_block(27); - System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 6 }, - )); - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 6)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { - round_index: 6, - })); - - // total rewards fifth distribution let total_staking = pallet_parachain_staking::Total::::get(); let total_score = ScoreStaking::total_score(); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + round_index: 6, + total_stake: total_staking, + total_score, + }, + )); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + alice(), + alice_staking, + 6, + total_staking, + total_score + )); let alice_round_reward = calculate_round_reward( alice_score.into(), total_score.into(), alice_staking, total_staking, ); - alice_total_reward += alice_round_reward; + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: alice_round_reward, + round_index: 6, + })); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + bob(), + bob_staking, + 6, + total_staking, + total_score + )); let bob_round_reward = calculate_round_reward( bob_score.into(), total_score.into(), bob_staking, total_staking, ); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: bob(), + amount: bob_round_reward, + round_index: 6, + })); + + // total rewards fifth distribution + alice_total_reward += alice_round_reward; bob_total_reward += bob_round_reward; assert_eq!( @@ -446,7 +522,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, - total_staking_amount: alice_staking + last_token_distribution_round: 6, } ); assert_eq!( @@ -456,7 +532,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: bob_round_reward, unpaid_reward: bob_total_reward, - total_staking_amount: bob_staking + last_token_distribution_round: 6, } ); @@ -471,32 +547,54 @@ fn score_staking_works() { run_to_block(33); - System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 7 }, - )); - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 7)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { - round_index: 7, - })); - - // total reward sixth distribution let total_staking = pallet_parachain_staking::Total::::get(); let total_score = ScoreStaking::total_score(); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + round_index: 7, + total_stake: total_staking, + total_score, + }, + )); + + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + alice(), + alice_staking, + 7, + total_staking, + total_score + )); let alice_round_reward = calculate_round_reward( alice_score.into(), total_score.into(), alice_staking, total_staking, ); - alice_total_reward += alice_round_reward; + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: round_reward, + round_index: 7, + })); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + bob(), + bob_staking, + 7, + total_staking, + total_score + )); let bob_round_reward = calculate_round_reward( bob_score.into(), total_score.into(), bob_staking, total_staking, ); + + // total reward sixth distribution + alice_total_reward += alice_round_reward; bob_total_reward += bob_round_reward; assert_eq!( @@ -506,7 +604,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, - total_staking_amount: alice_staking + last_token_distribution_round: 7, } ); assert_eq!( @@ -516,7 +614,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: bob_round_reward, unpaid_reward: bob_total_reward, - total_staking_amount: bob_staking + last_token_distribution_round: 7, } ); @@ -525,24 +623,51 @@ fn score_staking_works() { run_to_block(37); - System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 8 }, - )); - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 8)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { - round_index: 8, - })); - - // total reward sixth distribution let total_staking = pallet_parachain_staking::Total::::get(); let total_score = ScoreStaking::total_score(); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + round_index: 8, + total_stake: total_staking, + total_score, + }, + )); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + alice(), + alice_staking, + 8, + total_staking, + total_score + )); let alice_round_reward = calculate_round_reward( alice_score.into(), total_score.into(), alice_staking, total_staking, ); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: alice_round_reward, + round_index: 8, + })); + + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + bob(), + bob_staking, + 8, + total_staking, + total_score + )); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: bob(), + amount: 0, + round_index: 8, + })); + + // total reward sixth distribution alice_total_reward += alice_round_reward; assert_eq!( @@ -552,7 +677,7 @@ fn score_staking_works() { total_reward: alice_total_reward, last_round_reward: alice_round_reward, unpaid_reward: alice_total_reward, - total_staking_amount: alice_staking + last_token_distribution_round: 8, } ); // bob should not participate in the reward calculation @@ -563,7 +688,7 @@ fn score_staking_works() { total_reward: bob_total_reward, last_round_reward: 0, unpaid_reward: bob_total_reward, - total_staking_amount: bob_staking + last_token_distribution_round: 8, } ); assert_eq!(ScoreStaking::total_score(), alice_score); @@ -601,9 +726,16 @@ fn claim_works() { // run to next reward distribution round, alice should win all rewards run_to_block(7); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 2 }, + Event::::RewardDistributionStarted { + round_index: 2, + total_stake: total_staking, + total_score, + }, )); + assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -611,23 +743,24 @@ fn claim_works() { total_reward: 0, last_round_reward: 0, unpaid_reward: 0, - total_staking_amount: 0 + last_token_distribution_round: 0, } ); - assert_ok!(ScoreStaking::update_total_staking_amount( + + assert_ok!(ScoreStaking::distribute_rewards( RuntimeOrigin::signed(alice()), alice(), - alice_staking + alice_staking, + 2, + total_staking, + total_score )); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account_id: alice(), - amount: alice_staking, - })); - - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: round_reward(), round_index: 2, })); + assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -635,7 +768,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), - total_staking_amount: alice_staking + last_token_distribution_round: 2, } ); @@ -651,7 +784,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, - total_staking_amount: alice_staking + last_token_distribution_round: 2, } ); @@ -667,7 +800,7 @@ fn claim_works() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, - total_staking_amount: alice_staking + last_token_distribution_round: 2, } ); @@ -706,37 +839,40 @@ fn distribute_rewards_works() { // run to next reward distribution round, alice should win all rewards run_to_block(7); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 2 }, + Event::::RewardDistributionStarted { + round_index: 2, + total_stake: total_staking, + total_score, + }, )); let alice_id_graph_staking = 1900; + alice_staking = alice_id_graph_staking; - assert_ok!(ScoreStaking::update_total_staking_amount( + assert_ok!(ScoreStaking::distribute_rewards( RuntimeOrigin::signed(alice()), alice(), - alice_id_graph_staking + alice_staking, + 2, + total_staking, + total_score )); - alice_staking = alice_id_graph_staking; - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account_id: alice(), - amount: alice_staking, - })); - - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { - round_index: 2, - })); - - let mut alice_total_reward = 0; - let total_staking = pallet_parachain_staking::Total::::get(); - let total_score = ScoreStaking::total_score(); let round_reward = calculate_round_reward( alice_score.into(), total_score.into(), alice_staking, total_staking, ); + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: round_reward, + round_index: 2, + })); + + let mut alice_total_reward = 0; alice_total_reward += round_reward; assert_eq!( @@ -746,35 +882,43 @@ fn distribute_rewards_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, - total_staking_amount: alice_staking + last_token_distribution_round: 2, } ); run_to_block(12); - System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 3 }, - )); - - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 3)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { - round_index: 3, - })); - let total_staking = pallet_parachain_staking::Total::::get(); let total_score = ScoreStaking::total_score(); + System::assert_last_event(RuntimeEvent::ScoreStaking( + Event::::RewardDistributionStarted { + round_index: 3, + total_stake: total_staking, + total_score, + }, + )); + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + alice(), + alice_staking, + 3, + total_staking, + total_score + )); let round_reward = calculate_round_reward( alice_score.into(), total_score.into(), alice_staking, total_staking, ); - alice_total_reward += round_reward; - - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: round_reward, round_index: 3, })); + alice_total_reward += round_reward; + assert_eq!( ScoreStaking::scores(alice()).unwrap(), ScorePayment { @@ -782,7 +926,7 @@ fn distribute_rewards_works() { total_reward: alice_total_reward, last_round_reward: round_reward, unpaid_reward: alice_total_reward, - total_staking_amount: alice_staking + last_token_distribution_round: 3, } ); }) @@ -814,17 +958,39 @@ fn distribute_rewards_round_rewards_already_distributed_works() { // run to next reward distribution round, alice should win all rewards run_to_block(7); - + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 2 }, + Event::::RewardDistributionStarted { + round_index: 2, + total_stake: total_staking, + total_score, + }, + )); + + assert_ok!(ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + alice(), + alice_staking, + 2, + total_staking, + total_score )); - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: round_reward(), round_index: 2, })); assert_noop!( - ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2), + ScoreStaking::distribute_rewards( + RuntimeOrigin::signed(alice()), + alice(), + alice_staking, + 2, + total_staking, + total_score + ), Error::::RoundRewardsAlreadyDistributed ); }) @@ -834,7 +1000,7 @@ fn distribute_rewards_round_rewards_already_distributed_works() { fn distribute_rewards_origin_check_works() { new_test_ext(false).execute_with(|| { assert_noop!( - ScoreStaking::distribute_rewards(RuntimeOrigin::signed(bob()), 1), + ScoreStaking::distribute_rewards(RuntimeOrigin::signed(bob()), alice(), 10, 1, 10, 10), sp_runtime::DispatchError::BadOrigin ); }) diff --git a/parachain/pallets/score-staking/src/types.rs b/parachain/pallets/score-staking/src/types.rs index eb7dfa6236..680c457299 100644 --- a/parachain/pallets/score-staking/src/types.rs +++ b/parachain/pallets/score-staking/src/types.rs @@ -83,5 +83,5 @@ pub struct ScorePayment { pub total_reward: Balance, pub last_round_reward: Balance, pub unpaid_reward: Balance, - pub total_staking_amount: Balance, + pub last_token_distribution_round: RoundIndex, } diff --git a/parachain/precompiles/score-staking/src/tests.rs b/parachain/precompiles/score-staking/src/tests.rs index d0c0db241a..fe4fb09f24 100644 --- a/parachain/precompiles/score-staking/src/tests.rs +++ b/parachain/precompiles/score-staking/src/tests.rs @@ -57,22 +57,28 @@ fn claim_is_ok() { // run to next reward distribution round, alice should win all rewards run_to_block(7); + let total_staking = pallet_parachain_staking::Total::::get(); + let total_score = ScoreStaking::total_score(); System::assert_last_event(RuntimeEvent::ScoreStaking( - Event::::RewardDistributionStarted { round_index: 2 }, + Event::::RewardDistributionStarted { + round_index: 2, + total_stake: total_staking, + total_score, + }, )); - assert_ok!(ScoreStaking::update_total_staking_amount( + + // calculates the rewards + assert_ok!(ScoreStaking::distribute_rewards( RuntimeOrigin::signed(alice()), alice(), - alice_staking + alice_staking, + 2, + total_staking, + total_score )); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::TotalStakingAmountUpdated { - account_id: alice(), - amount: alice_staking, - })); - - // calculates the rewards - assert_ok!(ScoreStaking::distribute_rewards(RuntimeOrigin::signed(alice()), 2)); - System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributionCompleted { + System::assert_last_event(RuntimeEvent::ScoreStaking(Event::RewardDistributed { + who: alice(), + amount: round_reward(), round_index: 2, })); @@ -83,7 +89,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward(), - total_staking_amount: alice_staking, + last_token_distribution_round: 2, } ); @@ -107,7 +113,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: round_reward() - 200, - total_staking_amount: alice_staking, + last_token_distribution_round: 2, } ); @@ -131,7 +137,7 @@ fn claim_is_ok() { total_reward: round_reward(), last_round_reward: round_reward(), unpaid_reward: 0, - total_staking_amount: alice_staking, + last_token_distribution_round: 2, } ); From 9fc88713c73035a4aaeb7832536c8b814a5ab39e Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 27 Sep 2024 12:44:02 +0000 Subject: [PATCH 13/14] refactoring worker to distribute rewards one by one --- tee-worker/identity/Cargo.lock | 134 +++++++++--------- .../src/integritee/event_handler.rs | 39 ++--- .../node-api/metadata/src/metadata_mocks.rs | 8 +- .../metadata/src/pallet_score_staking.rs | 12 +- .../types/src/parentchain/events.rs | 11 +- 5 files changed, 107 insertions(+), 97 deletions(-) diff --git a/tee-worker/identity/Cargo.lock b/tee-worker/identity/Cargo.lock index 6852556873..4ffdf6c929 100644 --- a/tee-worker/identity/Cargo.lock +++ b/tee-worker/identity/Cargo.lock @@ -384,7 +384,7 @@ dependencies = [ [[package]] name = "binary-merkle-tree" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -886,7 +886,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "strum 0.26.1", @@ -1837,7 +1837,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -1855,7 +1855,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-runtime-interface", "sp-std 5.0.0", @@ -1900,7 +1900,7 @@ checksum = "6c2141d6d6c8512188a7891b4b01590a45f6dac67afb4f255c4124dbb86d4eaa" [[package]] name = "frame-benchmarking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-support-procedural", @@ -1914,7 +1914,7 @@ dependencies = [ "sp-api", "sp-application-crypto", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-runtime-interface", "sp-std 5.0.0", @@ -1925,14 +1925,14 @@ dependencies = [ [[package]] name = "frame-executive" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-tracing", @@ -1953,7 +1953,7 @@ dependencies = [ [[package]] name = "frame-support" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bitflags 1.3.2", "environmental 1.1.4", @@ -1973,7 +1973,7 @@ dependencies = [ "sp-core", "sp-core-hashing-proc-macro", "sp-inherents", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-staking", "sp-state-machine", @@ -1986,7 +1986,7 @@ dependencies = [ [[package]] name = "frame-support-procedural" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "cfg-expr", @@ -2002,7 +2002,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support-procedural-tools-derive", "proc-macro-crate", @@ -2014,7 +2014,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools-derive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -2024,7 +2024,7 @@ dependencies = [ [[package]] name = "frame-system" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "log 0.4.20", @@ -2032,7 +2032,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-version", @@ -5036,7 +5036,7 @@ dependencies = [ "serde 1.0.204", "sgx_tstd", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -5919,7 +5919,7 @@ checksum = "4d5d9eb14b174ee9aa2ef96dc2b94637a2d4b6e7cb873c7e171f0c20c6cf3eac" [[package]] name = "pallet-assets" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -5934,7 +5934,7 @@ dependencies = [ [[package]] name = "pallet-authorship" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -5948,7 +5948,7 @@ dependencies = [ [[package]] name = "pallet-balances" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -5979,7 +5979,7 @@ dependencies = [ "rlp", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6004,7 +6004,7 @@ dependencies = [ "rlp", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6022,7 +6022,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6056,14 +6056,14 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", ] [[package]] name = "pallet-session" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -6073,7 +6073,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-session", "sp-staking", @@ -6083,13 +6083,13 @@ dependencies = [ [[package]] name = "pallet-sudo" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", "parity-scale-codec", "scale-info", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -6116,7 +6116,7 @@ dependencies = [ "serde 1.0.204", "serde_json 1.0.103", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "x509-cert", @@ -6125,7 +6125,7 @@ dependencies = [ [[package]] name = "pallet-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-benchmarking", "frame-support", @@ -6134,7 +6134,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-inherents", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", "sp-timestamp", @@ -6143,7 +6143,7 @@ dependencies = [ [[package]] name = "pallet-transaction-payment" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-support", "frame-system", @@ -6151,7 +6151,7 @@ dependencies = [ "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-runtime", "sp-std 5.0.0", ] @@ -7325,7 +7325,7 @@ dependencies = [ [[package]] name = "sc-keystore" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "array-bytes 4.2.0", "async-trait", @@ -8088,7 +8088,7 @@ dependencies = [ [[package]] name = "sp-api" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -8108,7 +8108,7 @@ dependencies = [ [[package]] name = "sp-api-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "blake2", @@ -8122,20 +8122,20 @@ dependencies = [ [[package]] name = "sp-application-crypto" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", "serde 1.0.204", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-std 5.0.0", ] [[package]] name = "sp-arithmetic" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "integer-sqrt", "num-traits 0.2.16", @@ -8149,7 +8149,7 @@ dependencies = [ [[package]] name = "sp-consensus-grandpa" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "finality-grandpa", "log 0.4.20", @@ -8167,7 +8167,7 @@ dependencies = [ [[package]] name = "sp-consensus-slots" version = "0.10.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8179,7 +8179,7 @@ dependencies = [ [[package]] name = "sp-core" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "array-bytes 4.2.0", "bitflags 1.3.2", @@ -8223,7 +8223,7 @@ dependencies = [ [[package]] name = "sp-core-hashing" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "blake2b_simd", "byteorder 1.4.3", @@ -8252,7 +8252,7 @@ dependencies = [ [[package]] name = "sp-core-hashing-proc-macro" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -8263,7 +8263,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "proc-macro2", "quote", @@ -8273,7 +8273,7 @@ dependencies = [ [[package]] name = "sp-externalities" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "environmental 1.1.4", "parity-scale-codec", @@ -8284,7 +8284,7 @@ dependencies = [ [[package]] name = "sp-inherents" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "impl-trait-for-tuples", @@ -8311,7 +8311,7 @@ dependencies = [ [[package]] name = "sp-io" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bytes 1.4.0", "ed25519", @@ -8337,7 +8337,7 @@ dependencies = [ [[package]] name = "sp-keyring" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "lazy_static", "sp-core", @@ -8348,7 +8348,7 @@ dependencies = [ [[package]] name = "sp-keystore" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "futures 0.3.28", "parity-scale-codec", @@ -8362,7 +8362,7 @@ dependencies = [ [[package]] name = "sp-metadata-ir" version = "0.1.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "frame-metadata", "parity-scale-codec", @@ -8373,7 +8373,7 @@ dependencies = [ [[package]] name = "sp-panic-handler" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "backtrace", "lazy_static", @@ -8383,7 +8383,7 @@ dependencies = [ [[package]] name = "sp-runtime" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "either", "hash256-std-hasher", @@ -8397,7 +8397,7 @@ dependencies = [ "sp-application-crypto", "sp-arithmetic", "sp-core", - "sp-io 7.0.0 (git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42)", + "sp-io 7.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42)", "sp-std 5.0.0", "sp-weights", ] @@ -8405,7 +8405,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "bytes 1.4.0", "impl-trait-for-tuples", @@ -8423,7 +8423,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "Inflector", "proc-macro-crate", @@ -8435,7 +8435,7 @@ dependencies = [ [[package]] name = "sp-session" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8448,7 +8448,7 @@ dependencies = [ [[package]] name = "sp-staking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", @@ -8461,7 +8461,7 @@ dependencies = [ [[package]] name = "sp-state-machine" version = "0.13.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "hash-db 0.16.0", "log 0.4.20", @@ -8481,7 +8481,7 @@ dependencies = [ [[package]] name = "sp-std" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" [[package]] name = "sp-std" @@ -8492,7 +8492,7 @@ checksum = "af0ee286f98455272f64ac5bb1384ff21ac029fbb669afbaf48477faff12760e" [[package]] name = "sp-storage" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "impl-serde", "parity-scale-codec", @@ -8505,7 +8505,7 @@ dependencies = [ [[package]] name = "sp-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "async-trait", "futures-timer", @@ -8520,7 +8520,7 @@ dependencies = [ [[package]] name = "sp-tracing" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "sp-std 5.0.0", @@ -8532,7 +8532,7 @@ dependencies = [ [[package]] name = "sp-trie" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "ahash 0.8.3", "hash-db 0.16.0", @@ -8555,7 +8555,7 @@ dependencies = [ [[package]] name = "sp-version" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "impl-serde", "parity-scale-codec", @@ -8572,7 +8572,7 @@ dependencies = [ [[package]] name = "sp-version-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "proc-macro2", @@ -8583,7 +8583,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" version = "7.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "anyhow", "impl-trait-for-tuples", @@ -8597,7 +8597,7 @@ dependencies = [ [[package]] name = "sp-weights" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate.git?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.42#ff24c60ac7d9f87727ecdd0ded9a80c56e4f4b65" dependencies = [ "parity-scale-codec", "scale-info", diff --git a/tee-worker/identity/app-libs/parentchain-interface/src/integritee/event_handler.rs b/tee-worker/identity/app-libs/parentchain-interface/src/integritee/event_handler.rs index 17a2b276e6..684dd6ebbb 100644 --- a/tee-worker/identity/app-libs/parentchain-interface/src/integritee/event_handler.rs +++ b/tee-worker/identity/app-libs/parentchain-interface/src/integritee/event_handler.rs @@ -32,8 +32,9 @@ use itp_stf_state_handler::handle_state::HandleState; use itp_storage::{key_to_account_id, storage_map_key, StorageHasher}; use itp_types::{ parentchain::{ - events::ParentchainBlockProcessed, AccountId, FilterEvents, HandleParentchainEvents, - ParentchainEventProcessingError, ParentchainId, ProcessedEventsArtifacts, + events::{ParentchainBlockProcessed, RewardDistributionStarted}, + AccountId, FilterEvents, HandleParentchainEvents, ParentchainEventProcessingError, + ParentchainId, ProcessedEventsArtifacts, }, Delegator, OpaqueCall, RsaRequest, H256, }; @@ -236,7 +237,7 @@ where &self, executor: &Executor, block_header: impl Header, - round_index: u32, + event: &RewardDistributionStarted, ) -> Result<(), Error> { let scores_key_prefix = storage_prefix(b"ScoreStaking", b"Scores"); let scores_storage_keys_response = self @@ -315,13 +316,11 @@ where let extrinsic_sender = ParachainExtrinsicSender::new(); - let update_total_staking_amount_call_index = self + let distribute_rewards_call_index = self .node_metadata_repository - .get_from_metadata(|m| m.update_total_staking_amount_call_indexes()) + .get_from_metadata(|m| m.distribute_rewards_call_indexes()) .map_err(|_| { - Error::Other( - "Metadata retrieval for update_token_staking_amount_call_indexes failed".into(), - ) + Error::Other("Metadata retrieval for distribute_rewards_call_indexes failed".into()) })? .map_err(|_| Error::Other("Invalid metadata".into()))?; @@ -340,23 +339,30 @@ where }, }; let call = OpaqueCall::from_tuple(&( - update_total_staking_amount_call_index, + distribute_rewards_call_index, account_id, staking_amount, + event.round_index, + event.total_stake, + event.total_score, )); extrinsic_sender .send(call) .map_err(|_| Error::Other("Failed to send extrinsic".into()))?; } - let distribute_rewards_call_index = self + let complete_rewards_distribution_call_index = self .node_metadata_repository - .get_from_metadata(|m| m.distribute_rewards_call_indexes()) + .get_from_metadata(|m| m.complete_rewards_distribution_call_indexes()) .map_err(|_| { - Error::Other("Metadata retrieval for distribute_rewards_call_indexes failed".into()) + Error::Other( + "Metadata retrieval for complete_rewards_distribution_call_indexes failed" + .into(), + ) })? .map_err(|_| Error::Other("Invalid metadata".into()))?; - let call = OpaqueCall::from_tuple(&(distribute_rewards_call_index, round_index)); + let call = + OpaqueCall::from_tuple(&(complete_rewards_distribution_call_index, event.round_index)); extrinsic_sender .send(call) .map_err(|_| Error::Other("Failed to send extrinsic".into()))?; @@ -508,11 +514,8 @@ where .iter() .try_for_each(|event| { let event_hash = hash_of(&event); - let result = self.distribute_staking_rewards( - executor, - block_header.clone(), - event.round_index, - ); + let result = + self.distribute_staking_rewards(executor, block_header.clone(), event); handled_events.push(event_hash); result diff --git a/tee-worker/identity/core-primitives/node-api/metadata/src/metadata_mocks.rs b/tee-worker/identity/core-primitives/node-api/metadata/src/metadata_mocks.rs index e376bccc71..850c14caf9 100644 --- a/tee-worker/identity/core-primitives/node-api/metadata/src/metadata_mocks.rs +++ b/tee-worker/identity/core-primitives/node-api/metadata/src/metadata_mocks.rs @@ -92,8 +92,8 @@ pub struct NodeMetadataMock { //ScoreStaking score_staking_module: u8, - update_total_staking_amount: u8, distribute_rewards: u8, + complete_rewards_distribution: u8, } impl NodeMetadataMock { @@ -151,8 +151,8 @@ impl NodeMetadataMock { runtime_transaction_version: 4, score_staking_module: 100u8, - update_total_staking_amount: 9u8, distribute_rewards: 10u8, + complete_rewards_distribution: 11u8, } } } @@ -192,8 +192,8 @@ impl ScoreStakingCallIndexes for NodeMetadataMock { Ok([self.score_staking_module, self.distribute_rewards]) } - fn update_total_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { - Ok([self.score_staking_module, self.update_total_staking_amount]) + fn complete_rewards_distribution_call_indexes(&self) -> Result<[u8; 2]> { + Ok([self.score_staking_module, self.complete_rewards_distribution]) } } diff --git a/tee-worker/identity/core-primitives/node-api/metadata/src/pallet_score_staking.rs b/tee-worker/identity/core-primitives/node-api/metadata/src/pallet_score_staking.rs index b4772f979f..6a3f934237 100644 --- a/tee-worker/identity/core-primitives/node-api/metadata/src/pallet_score_staking.rs +++ b/tee-worker/identity/core-primitives/node-api/metadata/src/pallet_score_staking.rs @@ -21,17 +21,17 @@ pub const SCORE_STAKING: &str = "ScoreStaking"; // we only list the extrinsics that we care pub trait ScoreStakingCallIndexes { - fn update_total_staking_amount_call_indexes(&self) -> Result<[u8; 2]>; - fn distribute_rewards_call_indexes(&self) -> Result<[u8; 2]>; + + fn complete_rewards_distribution_call_indexes(&self) -> Result<[u8; 2]>; } impl ScoreStakingCallIndexes for NodeMetadata { - fn update_total_staking_amount_call_indexes(&self) -> Result<[u8; 2]> { - self.call_indexes(SCORE_STAKING, "update_total_staking_amount") - } - fn distribute_rewards_call_indexes(&self) -> Result<[u8; 2]> { self.call_indexes(SCORE_STAKING, "distribute_rewards") } + + fn complete_rewards_distribution_call_indexes(&self) -> Result<[u8; 2]> { + self.call_indexes(SCORE_STAKING, "complete_rewards_distribution") + } } diff --git a/tee-worker/identity/core-primitives/types/src/parentchain/events.rs b/tee-worker/identity/core-primitives/types/src/parentchain/events.rs index 45b2838604..fed033d2f6 100644 --- a/tee-worker/identity/core-primitives/types/src/parentchain/events.rs +++ b/tee-worker/identity/core-primitives/types/src/parentchain/events.rs @@ -248,12 +248,19 @@ impl StaticEvent for AssertionCreated { #[derive(Encode, Decode, Debug)] pub struct RewardDistributionStarted { pub round_index: u32, + pub total_stake: Balance, + pub total_score: Balance, } impl core::fmt::Display for RewardDistributionStarted { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - let message = - format!("{:?} :: round_index: {}", RewardDistributionStarted::EVENT, self.round_index); + let message = format!( + "{:?} :: round_index: {}, total_stake: {}, total_score: {}", + RewardDistributionStarted::EVENT, + self.round_index, + self.total_stake, + self.total_score + ); write!(f, "{}", message) } } From 13a1fb1b2bf2574e12472200acd6dd66d031c760 Mon Sep 17 00:00:00 2001 From: Francisco Silva Date: Fri, 27 Sep 2024 15:14:32 +0000 Subject: [PATCH 14/14] fixing fmt --- .../identity/app-libs/parentchain-interface/Cargo.toml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tee-worker/identity/app-libs/parentchain-interface/Cargo.toml b/tee-worker/identity/app-libs/parentchain-interface/Cargo.toml index dfef363f61..a34e16af47 100644 --- a/tee-worker/identity/app-libs/parentchain-interface/Cargo.toml +++ b/tee-worker/identity/app-libs/parentchain-interface/Cargo.toml @@ -14,11 +14,11 @@ itp-api-client-types = { workspace = true } itp-enclave-metrics = { workspace = true } itp-node-api = { workspace = true } itp-ocall-api = { workspace = true } -itp-stf-primitives = { workspace = true } -itp-types = { workspace = true } -itp-storage = { workspace = true } itp-sgx-externalities = { workspace = true } +itp-stf-primitives = { workspace = true } itp-stf-state-handler = { workspace = true } +itp-storage = { workspace = true } +itp-types = { workspace = true } codec = { package = "parity-scale-codec", workspace = true } log = { workspace = true } @@ -32,8 +32,8 @@ lc-dynamic-assertion = { workspace = true } lc-evm-dynamic-assertions = { workspace = true } lc-parachain-extrinsic-task-sender = { workspace = true } -litentry-primitives = { workspace = true } litentry-hex-utils = { workspace = true } +litentry-primitives = { workspace = true } frame-support = { workspace = true } pallet-identity-management-tee = { workspace = true }