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: frame_system::Config + pallet_evm::Config {106 107 type Currency: ExtendedLockableCurrency<Self::AccountId>108 + ReservableCurrency<Self::AccountId>;109110 111 type CollectionHandler: CollectionHandler<112 AccountId = Self::AccountId,113 CollectionId = CollectionId,114 >;115116 117 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;118119 120 type TreasuryAccountId: Get<Self::AccountId>;121122 123 #[pallet::constant]124 type PalletId: Get<PalletId>;125126 127 #[pallet::constant]128 type RecalculationInterval: Get<Self::BlockNumber>;129130 131 #[pallet::constant]132 type PendingInterval: Get<Self::BlockNumber>;133134 135 #[pallet::constant]136 type IntervalIncome: Get<Perbill>;137138 139 #[pallet::constant]140 type Nominal: Get<BalanceOf<Self>>;141142 143 type WeightInfo: WeightInfo;144145 146 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;147148 149 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;150 }151152 #[pallet::pallet]153 #[pallet::generate_store(pub(super) trait Store)]154 pub struct Pallet<T>(_);155156 #[pallet::event]157 #[pallet::generate_deposit(fn deposit_event)]158 pub enum Event<T: Config> {159 160 161 162 163 164 165 StakingRecalculation(166 167 T::AccountId,168 169 BalanceOf<T>,170 171 BalanceOf<T>,172 ),173174 175 176 177 178 179 Stake(T::AccountId, BalanceOf<T>),180181 182 183 184 185 186 Unstake(T::AccountId, BalanceOf<T>),187188 189 190 191 192 SetAdmin(T::AccountId),193 }194195 #[pallet::error]196 pub enum Error<T> {197 198 AdminNotSet,199 200 NoPermission,201 202 NotSufficientFunds,203 204 PendingForBlockOverflow,205 206 SponsorNotSet,207 208 IncorrectLockedBalanceOperation,209 }210211 212 #[pallet::storage]213 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;214215 216 #[pallet::storage]217 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;218219 220 221 222 223 224 225 #[pallet::storage]226 pub type Staked<T: Config> = StorageNMap<227 Key = (228 Key<Blake2_128Concat, T::AccountId>,229 Key<Twox64Concat, T::BlockNumber>,230 ),231 Value = (BalanceOf<T>, T::BlockNumber),232 QueryKind = ValueQuery,233 >;234235 236 237 238 239 #[pallet::storage]240 pub type StakesPerAccount<T: Config> =241 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;242243 244 245 246 247 #[pallet::storage]248 pub type PendingUnstake<T: Config> = StorageMap<249 _,250 Twox64Concat,251 T::BlockNumber,252 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,253 ValueQuery,254 >;255256 257 258 #[pallet::storage]259 #[pallet::getter(fn get_next_calculated_record)]260 pub type NextCalculatedRecord<T: Config> =261 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;262263 #[pallet::hooks]264 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {265 266 267 268 fn on_initialize(current_block_number: T::BlockNumber) -> Weight269 where270 <T as frame_system::Config>::BlockNumber: From<u32>,271 {272 let block_pending = PendingUnstake::<T>::take(current_block_number);273 let counter = block_pending.len() as u32;274275 if !block_pending.is_empty() {276 block_pending.into_iter().for_each(|(staker, amount)| {277 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(278 &staker, amount,279 );280 });281 }282283 <T as Config>::WeightInfo::on_initialize(counter)284 }285 }286287 #[pallet::call]288 impl<T: Config> Pallet<T>289 where290 T::BlockNumber: From<u32> + Into<u32>,291 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,292 {293 294 295 296 297 298 299 300 301 302 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]303 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {304 ensure_root(origin)?;305306 <Admin<T>>::set(Some(admin.as_sub().to_owned()));307308 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));309310 Ok(())311 }312313 314 315 316 317 318 319 320 #[pallet::weight(<T as Config>::WeightInfo::stake())]321 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {322 let staker_id = ensure_signed(staker)?;323324 ensure!(325 StakesPerAccount::<T>::get(&staker_id) < 10,326 Error::<T>::NoPermission327 );328329 ensure!(330 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),331 ArithmeticError::Underflow332 );333334 let balance =335 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);336337 338 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(339 &staker_id,340 amount,341 WithdrawReasons::all(),342 balance343 .checked_sub(&amount)344 .ok_or(ArithmeticError::Underflow)?,345 )?;346347 Self::add_lock_balance(&staker_id, amount)?;348349 let block_number = T::RelayBlockNumberProvider::current_block_number();350351 352 353 let recalculate_after_interval: T::BlockNumber =354 if block_number % T::RecalculationInterval::get() == 0u32.into() {355 1u32.into()356 } else {357 2u32.into()358 };359360 361 362 let recalc_block = (block_number / T::RecalculationInterval::get()363 + recalculate_after_interval)364 * T::RecalculationInterval::get();365366 <Staked<T>>::insert((&staker_id, block_number), {367 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));368 balance_and_recalc_block.0 = balance_and_recalc_block369 .0370 .checked_add(&amount)371 .ok_or(ArithmeticError::Overflow)?;372 balance_and_recalc_block.1 = recalc_block;373 balance_and_recalc_block374 });375376 <TotalStaked<T>>::set(377 <TotalStaked<T>>::get()378 .checked_add(&amount)379 .ok_or(ArithmeticError::Overflow)?,380 );381382 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);383384 Self::deposit_event(Event::Stake(staker_id, amount));385386 Ok(())387 }388389 390 391 392 393 #[pallet::weight(<T as Config>::WeightInfo::unstake())]394 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {395 let staker_id = ensure_signed(staker)?;396397 398 let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();399400 let mut pendings = <PendingUnstake<T>>::get(block);401402 403 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);404405 let mut total_stakes = 0u64;406407 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))408 .map(|(_, (amount, _))| {409 total_stakes += 1;410 amount411 })412 .sum();413414 if total_staked.is_zero() {415 return Ok(None::<Weight>.into()); 416 }417418 pendings419 .try_push((staker_id.clone(), total_staked))420 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;421422 <PendingUnstake<T>>::insert(block, pendings);423424 Self::unlock_balance(&staker_id, total_staked)?;425426 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::reserve(427 &staker_id,428 total_staked,429 )?;430431 TotalStaked::<T>::set(432 TotalStaked::<T>::get()433 .checked_sub(&total_staked)434 .ok_or(ArithmeticError::Underflow)?,435 );436437 StakesPerAccount::<T>::remove(&staker_id);438439 Self::deposit_event(Event::Unstake(staker_id, total_staked));440441 Ok(None::<Weight>.into())442 }443444 445 446 447 448 449 450 451 452 453 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]454 pub fn sponsor_collection(455 admin: OriginFor<T>,456 collection_id: CollectionId,457 ) -> DispatchResult {458 let admin_id = ensure_signed(admin)?;459 ensure!(460 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,461 Error::<T>::NoPermission462 );463464 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)465 }466467 468 469 470 471 472 473 474 475 476 477 478 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]479 pub fn stop_sponsoring_collection(480 admin: OriginFor<T>,481 collection_id: CollectionId,482 ) -> DispatchResult {483 let admin_id = ensure_signed(admin)?;484485 ensure!(486 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,487 Error::<T>::NoPermission488 );489490 ensure!(491 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?492 == Self::account_id(),493 <Error<T>>::NoPermission494 );495 T::CollectionHandler::remove_collection_sponsor(collection_id)496 }497498 499 500 501 502 503 504 505 506 507 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]508 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {509 let admin_id = ensure_signed(admin)?;510511 ensure!(512 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,513 Error::<T>::NoPermission514 );515516 T::ContractHandler::set_sponsor(517 T::CrossAccountId::from_sub(Self::account_id()),518 contract_id,519 )520 }521522 523 524 525 526 527 528 529 530 531 532 533 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]534 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {535 let admin_id = ensure_signed(admin)?;536537 ensure!(538 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,539 Error::<T>::NoPermission540 );541542 ensure!(543 T::ContractHandler::sponsor(contract_id)?544 .ok_or(<Error<T>>::SponsorNotSet)?545 .as_sub() == &Self::account_id(),546 <Error<T>>::NoPermission547 );548 T::ContractHandler::remove_contract_sponsor(contract_id)549 }550551 552 553 554 555 556 557 558 559 560 561 562 563 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]564 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {565 let admin_id = ensure_signed(admin)?;566567 ensure!(568 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,569 Error::<T>::NoPermission570 );571572 573 574 let current_recalc_block =575 Self::get_current_recalc_block(T::RelayBlockNumberProvider::current_block_number());576577 578 579 let next_recalc_block = current_recalc_block + T::RecalculationInterval::get();580581 let mut storage_iterator = Self::get_next_calculated_key()582 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));583584 NextCalculatedRecord::<T>::set(None);585586 {587 let mut stakers_number = stakers_number.unwrap_or(20);588 let last_id = RefCell::new(None);589 let income_acc = RefCell::new(BalanceOf::<T>::default());590 let amount_acc = RefCell::new(BalanceOf::<T>::default());591592 593 594 let flush_stake = || -> DispatchResult {595 if let Some(last_id) = &*last_id.borrow() {596 if !income_acc.borrow().is_zero() {597 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(598 &T::TreasuryAccountId::get(),599 last_id,600 *income_acc.borrow(),601 ExistenceRequirement::KeepAlive,602 )?;603604 Self::add_lock_balance(last_id, *income_acc.borrow())?;605 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {606 *staked = staked607 .checked_add(&*income_acc.borrow())608 .ok_or(ArithmeticError::Overflow)?;609 Ok(())610 })?;611612 Self::deposit_event(Event::StakingRecalculation(613 last_id.clone(),614 *amount_acc.borrow(),615 *income_acc.borrow(),616 ));617 }618619 *income_acc.borrow_mut() = BalanceOf::<T>::default();620 *amount_acc.borrow_mut() = BalanceOf::<T>::default();621 }622 Ok(())623 };624625 while let Some((626 (current_id, staked_block),627 (amount, next_recalc_block_for_stake),628 )) = storage_iterator.next()629 {630 if stakers_number == 0 {631 NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));632 break;633 }634 if last_id.borrow().as_ref() != Some(¤t_id) {635 flush_stake()?;636 *last_id.borrow_mut() = Some(current_id.clone());637 stakers_number -= 1;638 };639 if current_recalc_block >= next_recalc_block_for_stake {640 *amount_acc.borrow_mut() += amount;641 Self::recalculate_and_insert_stake(642 ¤t_id,643 staked_block,644 next_recalc_block,645 amount,646 ((current_recalc_block - next_recalc_block_for_stake)647 / T::RecalculationInterval::get())648 .into() + 1,649 &mut *income_acc.borrow_mut(),650 );651 }652 }653 flush_stake()?;654 }655656 Ok(())657 }658 }659}660661impl<T: Config> Pallet<T> {662 663 664 665 666 pub fn account_id() -> T::AccountId {667 T::PalletId::get().into_account_truncating()668 }669670 671 672 673 674 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {675 let locked_balance = Self::get_locked_balance(staker)676 .map(|l| l.amount)677 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;678679 680 681 Self::set_lock_unchecked(682 staker,683 locked_balance684 .checked_sub(&amount)685 .ok_or(ArithmeticError::Underflow)?,686 );687 Ok(())688 }689690 691 692 693 694 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {695 Self::get_locked_balance(staker)696 .map_or(<BalanceOf<T>>::default(), |l| l.amount)697 .checked_add(&amount)698 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))699 .ok_or(ArithmeticError::Overflow.into())700 }701702 703 704 705 706 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {707 if amount.is_zero() {708 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(709 LOCK_IDENTIFIER,710 &staker,711 );712 } else {713 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(714 LOCK_IDENTIFIER,715 staker,716 amount,717 WithdrawReasons::all(),718 )719 }720 }721722 723 724 725 pub fn get_locked_balance(726 staker: impl EncodeLike<T::AccountId>,727 ) -> Option<BalanceLock<BalanceOf<T>>> {728 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)729 .into_iter()730 .find(|l| l.id == LOCK_IDENTIFIER)731 }732733 734 735 736 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {737 let staked = Staked::<T>::iter_prefix((staker,))738 .into_iter()739 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {740 acc + amount741 });742 if staked != <BalanceOf<T>>::default() {743 Some(staked)744 } else {745 None746 }747 }748749 750 751 752 753 pub fn total_staked_by_id_per_block(754 staker: impl EncodeLike<T::AccountId>,755 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {756 let mut staked = Staked::<T>::iter_prefix((staker,))757 .into_iter()758 .map(|(block, (amount, _))| (block, amount))759 .collect::<Vec<_>>();760 staked.sort_by_key(|(block, _)| *block);761 if !staked.is_empty() {762 Some(staked)763 } else {764 None765 }766 }767768 769 770 771 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {772 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {773 Self::total_staked_by_id(s.as_sub())774 })775 }776777 778 779 780 781 782783 784 785 786 787 pub fn cross_id_total_staked_per_block(788 staker: T::CrossAccountId,789 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {790 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()791 }792793 fn recalculate_and_insert_stake(794 staker: &T::AccountId,795 staked_block: T::BlockNumber,796 next_recalc_block: T::BlockNumber,797 base: BalanceOf<T>,798 iters: u32,799 income_acc: &mut BalanceOf<T>,800 ) {801 let income = Self::calculate_income(base, iters);802803 base.checked_add(&income).map(|res| {804 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));805 *income_acc += income;806 });807 }808809 fn calculate_income<I>(base: I, iters: u32) -> I810 where811 I: EncodeLike<BalanceOf<T>> + Balance,812 {813 let mut income = base;814815 (0..iters).for_each(|_| income += T::IntervalIncome::get() * income);816817 income - base818 }819820 fn get_current_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {821 (current_relay_block / T::RecalculationInterval::get()) * T::RecalculationInterval::get()822 }823824 fn get_next_calculated_key() -> Option<Vec<u8>> {825 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))826 }827}828829impl<T: Config> Pallet<T>830where831 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,832{833 834 835 836 837 838 839 840 841 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {842 staker.map_or(843 PendingUnstake::<T>::iter_values()844 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))845 .sum(),846 |s| {847 PendingUnstake::<T>::iter_values()848 .flatten()849 .filter_map(|(id, amount)| {850 if id == *s.as_sub() {851 Some(amount)852 } else {853 None854 }855 })856 .sum()857 },858 )859 }860861 862 863 864 865 pub fn cross_id_pending_unstake_per_block(866 staker: T::CrossAccountId,867 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {868 let mut unsorted_res = vec![];869 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {870 pendings.into_iter().for_each(|(id, amount)| {871 if id == *staker.as_sub() {872 unsorted_res.push((block, amount));873 };874 })875 });876877 unsorted_res.sort_by_key(|(block, _)| *block);878 unsorted_res879 }880}