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 NextCalculatedRecord<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(20) 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,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 NextCalculatedRecord::<T>::set(None);599600 {601 let last_id = RefCell::new(None);602 let income_acc = RefCell::new(BalanceOf::<T>::default());603 let amount_acc = RefCell::new(BalanceOf::<T>::default());604605 606 607 let flush_stake = || -> DispatchResult {608 if let Some(last_id) = &*last_id.borrow() {609 if !income_acc.borrow().is_zero() {610 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(611 &T::TreasuryAccountId::get(),612 last_id,613 *income_acc.borrow(),614 ExistenceRequirement::KeepAlive,615 )?;616617 Self::add_lock_balance(last_id, *income_acc.borrow())?;618 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {619 *staked = staked620 .checked_add(&*income_acc.borrow())621 .ok_or(ArithmeticError::Overflow)?;622 Ok(())623 })?;624625 Self::deposit_event(Event::StakingRecalculation(626 last_id.clone(),627 *amount_acc.borrow(),628 *income_acc.borrow(),629 ));630 }631632 *income_acc.borrow_mut() = BalanceOf::<T>::default();633 *amount_acc.borrow_mut() = BalanceOf::<T>::default();634 }635 Ok(())636 };637638 while let Some((639 (current_id, staked_block),640 (amount, next_recalc_block_for_stake),641 )) = storage_iterator.next()642 {643 if stakers_number == 0 {644 NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));645 break;646 }647 if last_id.borrow().as_ref() != Some(¤t_id) {648 flush_stake()?;649 *last_id.borrow_mut() = Some(current_id.clone());650 stakers_number -= 1;651 };652 if current_recalc_block >= next_recalc_block_for_stake {653 *amount_acc.borrow_mut() += amount;654 Self::recalculate_and_insert_stake(655 ¤t_id,656 staked_block,657 next_recalc_block,658 amount,659 ((current_recalc_block - next_recalc_block_for_stake)660 / config.recalculation_interval)661 .into() + 1,662 &mut *income_acc.borrow_mut(),663 );664 }665 }666 flush_stake()?;667 }668669 Ok(())670 }671 }672}673674impl<T: Config> Pallet<T> {675 676 677 678 679 pub fn account_id() -> T::AccountId {680 T::PalletId::get().into_account_truncating()681 }682683 684 685 686 687 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {688 let locked_balance = Self::get_locked_balance(staker)689 .map(|l| l.amount)690 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;691692 693 694 Self::set_lock_unchecked(695 staker,696 locked_balance697 .checked_sub(&amount)698 .ok_or(ArithmeticError::Underflow)?,699 );700 Ok(())701 }702703 704 705 706 707 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {708 Self::get_locked_balance(staker)709 .map_or(<BalanceOf<T>>::default(), |l| l.amount)710 .checked_add(&amount)711 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))712 .ok_or(ArithmeticError::Overflow.into())713 }714715 716 717 718 719 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {720 if amount.is_zero() {721 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(722 LOCK_IDENTIFIER,723 &staker,724 );725 } else {726 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(727 LOCK_IDENTIFIER,728 staker,729 amount,730 WithdrawReasons::all(),731 )732 }733 }734735 736 737 738 pub fn get_locked_balance(739 staker: impl EncodeLike<T::AccountId>,740 ) -> Option<BalanceLock<BalanceOf<T>>> {741 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)742 .into_iter()743 .find(|l| l.id == LOCK_IDENTIFIER)744 }745746 747 748 749 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {750 let staked = Staked::<T>::iter_prefix((staker,))751 .into_iter()752 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {753 acc + amount754 });755 if staked != <BalanceOf<T>>::default() {756 Some(staked)757 } else {758 None759 }760 }761762 763 764 765 766 pub fn total_staked_by_id_per_block(767 staker: impl EncodeLike<T::AccountId>,768 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {769 let mut staked = Staked::<T>::iter_prefix((staker,))770 .into_iter()771 .map(|(block, (amount, _))| (block, amount))772 .collect::<Vec<_>>();773 staked.sort_by_key(|(block, _)| *block);774 if !staked.is_empty() {775 Some(staked)776 } else {777 None778 }779 }780781 782 783 784 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {785 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {786 Self::total_staked_by_id(s.as_sub())787 })788 }789790 791 792 793 794 795796 797 798 799 800 pub fn cross_id_total_staked_per_block(801 staker: T::CrossAccountId,802 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {803 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()804 }805806 fn recalculate_and_insert_stake(807 staker: &T::AccountId,808 staked_block: T::BlockNumber,809 next_recalc_block: T::BlockNumber,810 base: BalanceOf<T>,811 iters: u32,812 income_acc: &mut BalanceOf<T>,813 ) {814 let income = Self::calculate_income(base, iters);815816 base.checked_add(&income).map(|res| {817 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));818 *income_acc += income;819 });820 }821822 fn calculate_income<I>(base: I, iters: u32) -> I823 where824 I: EncodeLike<BalanceOf<T>> + Balance,825 {826 let config = <PalletConfiguration<T>>::get();827 let mut income = base;828829 (0..iters).for_each(|_| income += config.interval_income * income);830831 income - base832 }833834 fn get_current_recalc_block(835 current_relay_block: T::BlockNumber,836 config: &PalletConfiguration<T>,837 ) -> T::BlockNumber {838 (current_relay_block / config.recalculation_interval) * config.recalculation_interval839 }840841 fn get_next_calculated_key() -> Option<Vec<u8>> {842 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))843 }844}845846impl<T: Config> Pallet<T>847where848 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,849{850 851 852 853 854 855 856 857 858 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {859 staker.map_or(860 PendingUnstake::<T>::iter_values()861 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))862 .sum(),863 |s| {864 PendingUnstake::<T>::iter_values()865 .flatten()866 .filter_map(|(id, amount)| {867 if id == *s.as_sub() {868 Some(amount)869 } else {870 None871 }872 })873 .sum()874 },875 )876 }877878 879 880 881 882 pub fn cross_id_pending_unstake_per_block(883 staker: T::CrossAccountId,884 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {885 let mut unsorted_res = vec![];886 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {887 pendings.into_iter().for_each(|(id, amount)| {888 if id == *staker.as_sub() {889 unsorted_res.push((block, amount));890 };891 })892 });893894 unsorted_res.sort_by_key(|(block, _)| *block);895 unsorted_res896 }897}