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,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::hooks]266 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {267 268 269 270 fn on_initialize(current_block_number: T::BlockNumber) -> Weight271 where272 <T as frame_system::Config>::BlockNumber: From<u32>,273 {274 let block_pending = PendingUnstake::<T>::take(current_block_number);275 let counter = block_pending.len() as u32;276277 if !block_pending.is_empty() {278 block_pending.into_iter().for_each(|(staker, amount)| {279 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(280 &staker, amount,281 );282 });283 }284285 <T as Config>::WeightInfo::on_initialize(counter)286 }287 }288289 #[pallet::call]290 impl<T: Config> Pallet<T>291 where292 T::BlockNumber: From<u32> + Into<u32>,293 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,294 {295 296 297 298 299 300 301 302 303 304 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]305 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {306 ensure_root(origin)?;307308 <Admin<T>>::set(Some(admin.as_sub().to_owned()));309310 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));311312 Ok(())313 }314315 316 317 318 319 320 321 322 #[pallet::weight(<T as Config>::WeightInfo::stake())]323 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {324 let staker_id = ensure_signed(staker)?;325326 ensure!(327 StakesPerAccount::<T>::get(&staker_id) < 10,328 Error::<T>::NoPermission329 );330331 ensure!(332 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),333 ArithmeticError::Underflow334 );335 let config = <PalletConfiguration<T>>::get();336337 let balance =338 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);339340 341 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(342 &staker_id,343 amount,344 WithdrawReasons::all(),345 balance346 .checked_sub(&amount)347 .ok_or(ArithmeticError::Underflow)?,348 )?;349350 Self::add_lock_balance(&staker_id, amount)?;351352 let block_number = T::RelayBlockNumberProvider::current_block_number();353354 355 356 let recalculate_after_interval: T::BlockNumber =357 if block_number % config.recalculation_interval == 0u32.into() {358 1u32.into()359 } else {360 2u32.into()361 };362363 364 365 let recalc_block = (block_number / config.recalculation_interval366 + recalculate_after_interval)367 * config.recalculation_interval;368369 <Staked<T>>::insert((&staker_id, block_number), {370 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));371 balance_and_recalc_block.0 = balance_and_recalc_block372 .0373 .checked_add(&amount)374 .ok_or(ArithmeticError::Overflow)?;375 balance_and_recalc_block.1 = recalc_block;376 balance_and_recalc_block377 });378379 <TotalStaked<T>>::set(380 <TotalStaked<T>>::get()381 .checked_add(&amount)382 .ok_or(ArithmeticError::Overflow)?,383 );384385 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);386387 Self::deposit_event(Event::Stake(staker_id, amount));388389 Ok(())390 }391392 393 394 395 396 #[pallet::weight(<T as Config>::WeightInfo::unstake())]397 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {398 let staker_id = ensure_signed(staker)?;399 let config = <PalletConfiguration<T>>::get();400401 402 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;403404 let mut pendings = <PendingUnstake<T>>::get(block);405406 407 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);408409 let mut total_stakes = 0u64;410411 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))412 .map(|(_, (amount, _))| {413 total_stakes += 1;414 amount415 })416 .sum();417418 if total_staked.is_zero() {419 return Ok(None::<Weight>.into()); 420 }421422 pendings423 .try_push((staker_id.clone(), total_staked))424 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;425426 <PendingUnstake<T>>::insert(block, pendings);427428 Self::unlock_balance(&staker_id, total_staked)?;429430 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::reserve(431 &staker_id,432 total_staked,433 )?;434435 TotalStaked::<T>::set(436 TotalStaked::<T>::get()437 .checked_sub(&total_staked)438 .ok_or(ArithmeticError::Underflow)?,439 );440441 StakesPerAccount::<T>::remove(&staker_id);442443 Self::deposit_event(Event::Unstake(staker_id, total_staked));444445 Ok(None::<Weight>.into())446 }447448 449 450 451 452 453 454 455 456 457 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]458 pub fn sponsor_collection(459 admin: OriginFor<T>,460 collection_id: CollectionId,461 ) -> DispatchResult {462 let admin_id = ensure_signed(admin)?;463 ensure!(464 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,465 Error::<T>::NoPermission466 );467468 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)469 }470471 472 473 474 475 476 477 478 479 480 481 482 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]483 pub fn stop_sponsoring_collection(484 admin: OriginFor<T>,485 collection_id: CollectionId,486 ) -> DispatchResult {487 let admin_id = ensure_signed(admin)?;488489 ensure!(490 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,491 Error::<T>::NoPermission492 );493494 ensure!(495 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?496 == Self::account_id(),497 <Error<T>>::NoPermission498 );499 T::CollectionHandler::remove_collection_sponsor(collection_id)500 }501502 503 504 505 506 507 508 509 510 511 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]512 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {513 let admin_id = ensure_signed(admin)?;514515 ensure!(516 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,517 Error::<T>::NoPermission518 );519520 T::ContractHandler::set_sponsor(521 T::CrossAccountId::from_sub(Self::account_id()),522 contract_id,523 )524 }525526 527 528 529 530 531 532 533 534 535 536 537 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]538 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {539 let admin_id = ensure_signed(admin)?;540541 ensure!(542 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,543 Error::<T>::NoPermission544 );545546 ensure!(547 T::ContractHandler::sponsor(contract_id)?548 .ok_or(<Error<T>>::SponsorNotSet)?549 .as_sub() == &Self::account_id(),550 <Error<T>>::NoPermission551 );552 T::ContractHandler::remove_contract_sponsor(contract_id)553 }554555 556 557 558 559 560 561 562 563 564 565 566 567 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]568 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {569 let admin_id = ensure_signed(admin)?;570571 ensure!(572 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,573 Error::<T>::NoPermission574 );575 let config = <PalletConfiguration<T>>::get();576577 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);578579 ensure!(580 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,581 Error::<T>::NoPermission582 );583584 585 586 let current_recalc_block = Self::get_current_recalc_block(587 T::RelayBlockNumberProvider::current_block_number(),588 &config,589 );590591 592 593 let next_recalc_block = current_recalc_block + config.recalculation_interval;594595 let mut storage_iterator = Self::get_next_calculated_key()596 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));597598 PreviousCalculatedRecord::<T>::set(None);599600 {601 602 let last_id = RefCell::new(None);603 604 let income_acc = RefCell::new(BalanceOf::<T>::default());605 606 let amount_acc = RefCell::new(BalanceOf::<T>::default());607608 609 610 611 612 613 614 615 let flush_stake = || -> DispatchResult {616 if let Some(last_id) = &*last_id.borrow() {617 if !income_acc.borrow().is_zero() {618 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(619 &T::TreasuryAccountId::get(),620 last_id,621 *income_acc.borrow(),622 ExistenceRequirement::KeepAlive,623 )?;624625 Self::add_lock_balance(last_id, *income_acc.borrow())?;626 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {627 *staked = staked628 .checked_add(&*income_acc.borrow())629 .ok_or(ArithmeticError::Overflow)?;630 Ok(())631 })?;632633 Self::deposit_event(Event::StakingRecalculation(634 last_id.clone(),635 *amount_acc.borrow(),636 *income_acc.borrow(),637 ));638 }639640 *income_acc.borrow_mut() = BalanceOf::<T>::default();641 *amount_acc.borrow_mut() = BalanceOf::<T>::default();642 }643 Ok(())644 };645646 647 648 649 650 651 652 while let Some((653 (current_id, staked_block),654 (amount, next_recalc_block_for_stake),655 )) = storage_iterator.next()656 {657 658 659 660 if last_id.borrow().as_ref() != Some(¤t_id) {661 flush_stake()?;662 *last_id.borrow_mut() = Some(current_id.clone());663 stakers_number -= 1;664 };665666 667 if current_recalc_block >= next_recalc_block_for_stake {668 *amount_acc.borrow_mut() += amount;669 Self::recalculate_and_insert_stake(670 ¤t_id,671 staked_block,672 next_recalc_block,673 amount,674 ((current_recalc_block - next_recalc_block_for_stake)675 / config.recalculation_interval)676 .into() + 1,677 &mut *income_acc.borrow_mut(),678 );679 }680681 682 if stakers_number == 0 {683 if storage_iterator.next().is_some() {684 685 PreviousCalculatedRecord::<T>::set(Some((current_id, staked_block)));686 }687 break;688 }689 }690 flush_stake()?;691 }692693 Ok(())694 }695 }696}697698impl<T: Config> Pallet<T> {699 700 701 702 703 pub fn account_id() -> T::AccountId {704 T::PalletId::get().into_account_truncating()705 }706707 708 709 710 711 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {712 let locked_balance = Self::get_locked_balance(staker)713 .map(|l| l.amount)714 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;715716 717 718 Self::set_lock_unchecked(719 staker,720 locked_balance721 .checked_sub(&amount)722 .ok_or(ArithmeticError::Underflow)?,723 );724 Ok(())725 }726727 728 729 730 731 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {732 Self::get_locked_balance(staker)733 .map_or(<BalanceOf<T>>::default(), |l| l.amount)734 .checked_add(&amount)735 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))736 .ok_or(ArithmeticError::Overflow.into())737 }738739 740 741 742 743 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {744 if amount.is_zero() {745 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(746 LOCK_IDENTIFIER,747 &staker,748 );749 } else {750 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(751 LOCK_IDENTIFIER,752 staker,753 amount,754 WithdrawReasons::all(),755 )756 }757 }758759 760 761 762 pub fn get_locked_balance(763 staker: impl EncodeLike<T::AccountId>,764 ) -> Option<BalanceLock<BalanceOf<T>>> {765 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)766 .into_iter()767 .find(|l| l.id == LOCK_IDENTIFIER)768 }769770 771 772 773 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {774 let staked = Staked::<T>::iter_prefix((staker,))775 .into_iter()776 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {777 acc + amount778 });779 if staked != <BalanceOf<T>>::default() {780 Some(staked)781 } else {782 None783 }784 }785786 787 788 789 790 pub fn total_staked_by_id_per_block(791 staker: impl EncodeLike<T::AccountId>,792 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {793 let mut staked = Staked::<T>::iter_prefix((staker,))794 .into_iter()795 .map(|(block, (amount, _))| (block, amount))796 .collect::<Vec<_>>();797 staked.sort_by_key(|(block, _)| *block);798 if !staked.is_empty() {799 Some(staked)800 } else {801 None802 }803 }804805 806 807 808 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {809 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {810 Self::total_staked_by_id(s.as_sub())811 })812 }813814 815 816 817 818 819820 821 822 823 824 pub fn cross_id_total_staked_per_block(825 staker: T::CrossAccountId,826 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {827 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()828 }829830 fn recalculate_and_insert_stake(831 staker: &T::AccountId,832 staked_block: T::BlockNumber,833 next_recalc_block: T::BlockNumber,834 base: BalanceOf<T>,835 iters: u32,836 income_acc: &mut BalanceOf<T>,837 ) {838 let income = Self::calculate_income(base, iters);839840 base.checked_add(&income).map(|res| {841 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));842 *income_acc += income;843 });844 }845846 fn calculate_income<I>(base: I, iters: u32) -> I847 where848 I: EncodeLike<BalanceOf<T>> + Balance,849 {850 let config = <PalletConfiguration<T>>::get();851 let mut income = base;852853 (0..iters).for_each(|_| income += config.interval_income * income);854855 income - base856 }857858 859 860 fn get_current_recalc_block(861 current_relay_block: T::BlockNumber,862 config: &PalletConfiguration<T>,863 ) -> T::BlockNumber {864 (current_relay_block / config.recalculation_interval) * config.recalculation_interval865 }866867 fn get_next_calculated_key() -> Option<Vec<u8>> {868 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))869 }870}871872impl<T: Config> Pallet<T>873where874 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,875{876 877 878 879 880 881 882 883 884 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {885 staker.map_or(886 PendingUnstake::<T>::iter_values()887 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))888 .sum(),889 |s| {890 PendingUnstake::<T>::iter_values()891 .flatten()892 .filter_map(|(id, amount)| {893 if id == *s.as_sub() {894 Some(amount)895 } else {896 None897 }898 })899 .sum()900 },901 )902 }903904 905 906 907 908 pub fn cross_id_pending_unstake_per_block(909 staker: T::CrossAccountId,910 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {911 let mut unsorted_res = vec![];912 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {913 pendings.into_iter().for_each(|(id, amount)| {914 if id == *staker.as_sub() {915 unsorted_res.push((block, amount));916 };917 })918 });919920 unsorted_res.sort_by_key(|(block, _)| *block);921 unsorted_res922 }923}