123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57 vec::{Vec},58 vec,59 iter::Sum,60 borrow::ToOwned,61 cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71 dispatch::{DispatchResult},72 traits::{73 Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,74 },75 ensure,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83 Perbill,84 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85 ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97 use super::*;98 use frame_support::{99 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100 traits::ReservableCurrency, weights::Weight,101 };102 use frame_system::pallet_prelude::*;103104 #[pallet::config]105 pub trait Config:106 frame_system::Config + pallet_evm::Config + pallet_configuration::Config107 {108 109 type Currency: ExtendedLockableCurrency<Self::AccountId>110 + ReservableCurrency<Self::AccountId>;111112 113 type CollectionHandler: CollectionHandler<114 AccountId = Self::AccountId,115 CollectionId = CollectionId,116 >;117118 119 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121 122 type TreasuryAccountId: Get<Self::AccountId>;123124 125 #[pallet::constant]126 type PalletId: Get<PalletId>;127128 129 #[pallet::constant]130 type RecalculationInterval: Get<Self::BlockNumber>;131132 133 #[pallet::constant]134 type PendingInterval: Get<Self::BlockNumber>;135136 137 #[pallet::constant]138 type IntervalIncome: Get<Perbill>;139140 141 #[pallet::constant]142 type Nominal: Get<BalanceOf<Self>>;143144 145 type WeightInfo: WeightInfo;146147 148 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150 151 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152 }153154 #[pallet::pallet]155 #[pallet::generate_store(pub(super) trait Store)]156 pub struct Pallet<T>(_);157158 #[pallet::event]159 #[pallet::generate_deposit(fn deposit_event)]160 pub enum Event<T: Config> {161 162 163 164 165 166 167 StakingRecalculation(168 169 T::AccountId,170 171 BalanceOf<T>,172 173 BalanceOf<T>,174 ),175176 177 178 179 180 181 Stake(T::AccountId, BalanceOf<T>),182183 184 185 186 187 188 Unstake(T::AccountId, BalanceOf<T>),189190 191 192 193 194 SetAdmin(T::AccountId),195 }196197 #[pallet::error]198 pub enum Error<T> {199 200 AdminNotSet,201 202 NoPermission,203 204 NotSufficientFunds,205 206 PendingForBlockOverflow,207 208 SponsorNotSet,209 210 IncorrectLockedBalanceOperation,211 }212213 214 #[pallet::storage]215 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;216217 218 #[pallet::storage]219 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;220221 222 223 224 225 226 227 #[pallet::storage]228 pub type Staked<T: Config> = StorageNMap<229 Key = (230 Key<Blake2_128Concat, T::AccountId>,231 Key<Twox64Concat, T::BlockNumber>,232 ),233 Value = (BalanceOf<T>, T::BlockNumber),234 QueryKind = ValueQuery,235 >;236237 238 239 240 241 #[pallet::storage]242 pub type StakesPerAccount<T: Config> =243 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;244245 246 247 248 249 #[pallet::storage]250 pub type PendingUnstake<T: Config> = StorageMap<251 _,252 Twox64Concat,253 T::BlockNumber,254 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,255 ValueQuery,256 >;257258 259 260 #[pallet::storage]261 #[pallet::getter(fn get_next_calculated_record)]262 pub type PreviousCalculatedRecord<T: Config> =263 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;264265 #[pallet::storage]266 pub(crate) type UpgradedToReserves<T: Config> =267 StorageValue<Value = bool, QueryKind = ValueQuery>;268269 #[pallet::hooks]270 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {271 272 273 274 fn on_initialize(current_block_number: T::BlockNumber) -> Weight275 where276 <T as frame_system::Config>::BlockNumber: From<u32>,277 {278 let block_pending = PendingUnstake::<T>::take(current_block_number);279 let counter = block_pending.len() as u32;280281 if !block_pending.is_empty() {282 block_pending.into_iter().for_each(|(staker, amount)| {283 Self::get_locked_balance(&staker).map(|b| {284 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();285 Self::set_lock_unchecked(&staker, new_state);286 });287 });288 }289290 <T as Config>::WeightInfo::on_initialize(counter)291 }292293 fn on_runtime_upgrade() -> Weight {294 <UpgradedToReserves<T>>::kill();295296 T::DbWeight::get().reads_writes(0, 1)297 }298 }299300 #[pallet::call]301 impl<T: Config> Pallet<T>302 where303 T::BlockNumber: From<u32> + Into<u32>,304 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,305 {306 307 308 309 310 311 312 313 314 315 #[pallet::call_index(0)]316 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]317 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {318 ensure_root(origin)?;319320 <Admin<T>>::set(Some(admin.as_sub().to_owned()));321322 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));323324 Ok(())325 }326327 328 329 330 331 332 333 334 #[pallet::call_index(1)]335 #[pallet::weight(<T as Config>::WeightInfo::stake())]336 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {337 let staker_id = ensure_signed(staker)?;338339 ensure!(340 StakesPerAccount::<T>::get(&staker_id) < 10,341 Error::<T>::NoPermission342 );343344 ensure!(345 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),346 ArithmeticError::Underflow347 );348 let config = <PalletConfiguration<T>>::get();349350 let balance =351 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);352353 354 ensure!(355 amount356 <= match Self::get_locked_balance(&staker_id) {357 Some(lock) => balance358 .checked_sub(&lock.amount)359 .ok_or(ArithmeticError::Underflow)?,360 None => balance,361 },362 ArithmeticError::Underflow363 );364365 Self::add_lock_balance(&staker_id, amount)?;366367 let block_number = T::RelayBlockNumberProvider::current_block_number();368369 370 371 let recalculate_after_interval: T::BlockNumber =372 if block_number % config.recalculation_interval == 0u32.into() {373 1u32.into()374 } else {375 2u32.into()376 };377378 379 380 let recalc_block = (block_number / config.recalculation_interval381 + recalculate_after_interval)382 * config.recalculation_interval;383384 <Staked<T>>::insert((&staker_id, block_number), {385 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));386 balance_and_recalc_block.0 = balance_and_recalc_block387 .0388 .checked_add(&amount)389 .ok_or(ArithmeticError::Overflow)?;390 balance_and_recalc_block.1 = recalc_block;391 balance_and_recalc_block392 });393394 <TotalStaked<T>>::set(395 <TotalStaked<T>>::get()396 .checked_add(&amount)397 .ok_or(ArithmeticError::Overflow)?,398 );399400 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);401402 Self::deposit_event(Event::Stake(staker_id, amount));403404 Ok(())405 }406407 408 409 410 411 #[pallet::call_index(2)]412 #[pallet::weight(<T as Config>::WeightInfo::unstake())]413 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {414 let staker_id = ensure_signed(staker)?;415 let config = <PalletConfiguration<T>>::get();416417 418 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;419420 let mut pendings = <PendingUnstake<T>>::get(block);421422 423 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);424425 let mut total_stakes = 0u64;426427 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))428 .map(|(_, (amount, _))| {429 total_stakes += 1;430 amount431 })432 .sum();433434 if total_staked.is_zero() {435 return Ok(None::<Weight>.into()); 436 }437438 pendings439 .try_push((staker_id.clone(), total_staked))440 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;441442 <PendingUnstake<T>>::insert(block, pendings);443444 TotalStaked::<T>::set(445 TotalStaked::<T>::get()446 .checked_sub(&total_staked)447 .ok_or(ArithmeticError::Underflow)?,448 );449450 StakesPerAccount::<T>::remove(&staker_id);451452 Self::deposit_event(Event::Unstake(staker_id, total_staked));453454 Ok(None::<Weight>.into())455 }456457 458 459 460 461 462 463 464 465 466 #[pallet::call_index(3)]467 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]468 pub fn sponsor_collection(469 admin: OriginFor<T>,470 collection_id: CollectionId,471 ) -> DispatchResult {472 let admin_id = ensure_signed(admin)?;473 ensure!(474 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,475 Error::<T>::NoPermission476 );477478 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)479 }480481 482 483 484 485 486 487 488 489 490 491 492 #[pallet::call_index(4)]493 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]494 pub fn stop_sponsoring_collection(495 admin: OriginFor<T>,496 collection_id: CollectionId,497 ) -> DispatchResult {498 let admin_id = ensure_signed(admin)?;499500 ensure!(501 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,502 Error::<T>::NoPermission503 );504505 ensure!(506 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?507 == Self::account_id(),508 <Error<T>>::NoPermission509 );510 T::CollectionHandler::remove_collection_sponsor(collection_id)511 }512513 514 515 516 517 518 519 520 521 522 #[pallet::call_index(5)]523 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]524 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {525 let admin_id = ensure_signed(admin)?;526527 ensure!(528 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,529 Error::<T>::NoPermission530 );531532 T::ContractHandler::set_sponsor(533 T::CrossAccountId::from_sub(Self::account_id()),534 contract_id,535 )536 }537538 539 540 541 542 543 544 545 546 547 548 549 #[pallet::call_index(6)]550 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]551 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {552 let admin_id = ensure_signed(admin)?;553554 ensure!(555 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,556 Error::<T>::NoPermission557 );558559 ensure!(560 T::ContractHandler::sponsor(contract_id)?561 .ok_or(<Error<T>>::SponsorNotSet)?562 .as_sub() == &Self::account_id(),563 <Error<T>>::NoPermission564 );565 T::ContractHandler::remove_contract_sponsor(contract_id)566 }567568 569 570 571 572 573 574 575 576 577 578 579 580 #[pallet::call_index(7)]581 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]582 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {583 let admin_id = ensure_signed(admin)?;584585 ensure!(586 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,587 Error::<T>::NoPermission588 );589 let config = <PalletConfiguration<T>>::get();590591 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);592593 ensure!(594 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,595 Error::<T>::NoPermission596 );597598 599 600 let current_recalc_block = Self::get_current_recalc_block(601 T::RelayBlockNumberProvider::current_block_number(),602 &config,603 );604605 606 607 let next_recalc_block = current_recalc_block + config.recalculation_interval;608609 let mut storage_iterator = Self::get_next_calculated_key()610 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));611612 PreviousCalculatedRecord::<T>::set(None);613614 {615 616 let last_id = RefCell::new(None);617 618 let mut last_staked_calculated_block = Default::default();619 620 let income_acc = RefCell::new(BalanceOf::<T>::default());621 622 let amount_acc = RefCell::new(BalanceOf::<T>::default());623624 625 626 627 628 629 630 631 let flush_stake = || -> DispatchResult {632 if let Some(last_id) = &*last_id.borrow() {633 if !income_acc.borrow().is_zero() {634 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(635 &T::TreasuryAccountId::get(),636 last_id,637 *income_acc.borrow(),638 ExistenceRequirement::KeepAlive,639 )?;640641 Self::add_lock_balance(last_id, *income_acc.borrow())?;642 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {643 *staked = staked644 .checked_add(&*income_acc.borrow())645 .ok_or(ArithmeticError::Overflow)?;646 Ok(())647 })?;648649 Self::deposit_event(Event::StakingRecalculation(650 last_id.clone(),651 *amount_acc.borrow(),652 *income_acc.borrow(),653 ));654 }655656 *income_acc.borrow_mut() = BalanceOf::<T>::default();657 *amount_acc.borrow_mut() = BalanceOf::<T>::default();658 }659 Ok(())660 };661662 663 664 665 666 667 668 while let Some((669 (current_id, staked_block),670 (amount, next_recalc_block_for_stake),671 )) = storage_iterator.next()672 {673 674 675 676 if last_id.borrow().as_ref() != Some(¤t_id) {677 if stakers_number > 0 {678 flush_stake()?;679 *last_id.borrow_mut() = Some(current_id.clone());680 stakers_number -= 1;681 }682 683 else {684 if let Some(staker) = &*last_id.borrow() {685 686 PreviousCalculatedRecord::<T>::set(Some((687 staker.clone(),688 last_staked_calculated_block,689 )));690 }691 break;692 };693 };694695 696 if current_recalc_block >= next_recalc_block_for_stake {697 *amount_acc.borrow_mut() += amount;698 Self::recalculate_and_insert_stake(699 ¤t_id,700 staked_block,701 next_recalc_block,702 amount,703 ((current_recalc_block - next_recalc_block_for_stake)704 / config.recalculation_interval)705 .into() + 1,706 &mut *income_acc.borrow_mut(),707 );708 }709 last_staked_calculated_block = staked_block;710 }711 flush_stake()?;712 }713714 Ok(())715 }716 }717}718719impl<T: Config> Pallet<T> {720 721 722 723 724 pub fn account_id() -> T::AccountId {725 T::PalletId::get().into_account_truncating()726 }727728 729 730 731 732 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {733 Self::get_locked_balance(staker)734 .map_or(<BalanceOf<T>>::default(), |l| l.amount)735 .checked_add(&amount)736 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))737 .ok_or(ArithmeticError::Overflow.into())738 }739740 741 742 743 744 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {745 if amount.is_zero() {746 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(747 LOCK_IDENTIFIER,748 &staker,749 );750 } else {751 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(752 LOCK_IDENTIFIER,753 staker,754 amount,755 WithdrawReasons::all(),756 )757 }758 }759760 761 762 763 pub fn get_locked_balance(764 staker: impl EncodeLike<T::AccountId>,765 ) -> Option<BalanceLock<BalanceOf<T>>> {766 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)767 .into_iter()768 .find(|l| l.id == LOCK_IDENTIFIER)769 }770771 772 773 774 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {775 let staked = Staked::<T>::iter_prefix((staker,))776 .into_iter()777 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {778 acc + amount779 });780 if staked != <BalanceOf<T>>::default() {781 Some(staked)782 } else {783 None784 }785 }786787 788 789 790 791 pub fn total_staked_by_id_per_block(792 staker: impl EncodeLike<T::AccountId>,793 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {794 let mut staked = Staked::<T>::iter_prefix((staker,))795 .into_iter()796 .map(|(block, (amount, _))| (block, amount))797 .collect::<Vec<_>>();798 staked.sort_by_key(|(block, _)| *block);799 if !staked.is_empty() {800 Some(staked)801 } else {802 None803 }804 }805806 807 808 809 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {810 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {811 Self::total_staked_by_id(s.as_sub())812 })813 }814815 816 817 818 819 820821 822 823 824 825 pub fn cross_id_total_staked_per_block(826 staker: T::CrossAccountId,827 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {828 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()829 }830831 fn recalculate_and_insert_stake(832 staker: &T::AccountId,833 staked_block: T::BlockNumber,834 next_recalc_block: T::BlockNumber,835 base: BalanceOf<T>,836 iters: u32,837 income_acc: &mut BalanceOf<T>,838 ) {839 let income = Self::calculate_income(base, iters);840841 base.checked_add(&income).map(|res| {842 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));843 *income_acc += income;844 });845 }846847 fn calculate_income<I>(base: I, iters: u32) -> I848 where849 I: EncodeLike<BalanceOf<T>> + Balance,850 {851 let config = <PalletConfiguration<T>>::get();852 let mut income = base;853854 (0..iters).for_each(|_| income += config.interval_income * income);855856 income - base857 }858859 860 861 fn get_current_recalc_block(862 current_relay_block: T::BlockNumber,863 config: &PalletConfiguration<T>,864 ) -> T::BlockNumber {865 (current_relay_block / config.recalculation_interval) * config.recalculation_interval866 }867868 fn get_next_calculated_key() -> Option<Vec<u8>> {869 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))870 }871}872873impl<T: Config> Pallet<T>874where875 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,876{877 878 879 880 881 882 883 884 885 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {886 staker.map_or(887 PendingUnstake::<T>::iter_values()888 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))889 .sum(),890 |s| {891 PendingUnstake::<T>::iter_values()892 .flatten()893 .filter_map(|(id, amount)| {894 if id == *s.as_sub() {895 Some(amount)896 } else {897 None898 }899 })900 .sum()901 },902 )903 }904905 906 907 908 909 pub fn cross_id_pending_unstake_per_block(910 staker: T::CrossAccountId,911 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {912 let mut unsorted_res = vec![];913 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {914 pendings.into_iter().for_each(|(id, amount)| {915 if id == *staker.as_sub() {916 unsorted_res.push((block, amount));917 };918 })919 });920921 unsorted_res.sort_by_key(|(block, _)| *block);922 unsorted_res923 }924}