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::account::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 Event: IsType<<Self as frame_system::Config>::Event> + 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::Currency as ReservableCurrency<T::AccountId>>::unreserve(&staker, amount);278 });279 }280281 T::WeightInfo::on_initialize(counter)282 }283 }284285 #[pallet::call]286 impl<T: Config> Pallet<T>287 where288 T::BlockNumber: From<u32> + Into<u32>,289 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,290 {291 292 293 294 295 296 297 298 299 300 #[pallet::weight(T::WeightInfo::set_admin_address())]301 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {302 ensure_root(origin)?;303304 <Admin<T>>::set(Some(admin.as_sub().to_owned()));305306 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));307308 Ok(())309 }310311 312 313 314 315 316 317 318 #[pallet::weight(T::WeightInfo::stake())]319 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {320 let staker_id = ensure_signed(staker)?;321322 ensure!(323 StakesPerAccount::<T>::get(&staker_id) < 10,324 Error::<T>::NoPermission325 );326327 ensure!(328 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),329 ArithmeticError::Underflow330 );331332 let balance =333 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);334335 336 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(337 &staker_id,338 amount,339 WithdrawReasons::all(),340 balance341 .checked_sub(&amount)342 .ok_or(ArithmeticError::Underflow)?,343 )?;344345 Self::add_lock_balance(&staker_id, amount)?;346347 let block_number = T::RelayBlockNumberProvider::current_block_number();348349 350 351 let recalculate_after_interval: T::BlockNumber =352 if block_number % T::RecalculationInterval::get() == 0u32.into() {353 1u32.into()354 } else {355 2u32.into()356 };357358 359 360 let recalc_block = (block_number / T::RecalculationInterval::get()361 + recalculate_after_interval)362 * T::RecalculationInterval::get();363364 <Staked<T>>::insert((&staker_id, block_number), {365 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));366 balance_and_recalc_block.0 = balance_and_recalc_block367 .0368 .checked_add(&amount)369 .ok_or(ArithmeticError::Overflow)?;370 balance_and_recalc_block.1 = recalc_block;371 balance_and_recalc_block372 });373374 <TotalStaked<T>>::set(375 <TotalStaked<T>>::get()376 .checked_add(&amount)377 .ok_or(ArithmeticError::Overflow)?,378 );379380 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);381382 Self::deposit_event(Event::Stake(staker_id, amount));383384 Ok(())385 }386387 388 389 390 391 #[pallet::weight(T::WeightInfo::unstake())]392 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {393 let staker_id = ensure_signed(staker)?;394395 396 let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();397398 let mut pendings = <PendingUnstake<T>>::get(block);399400 401 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);402403 let mut total_stakes = 0u64;404405 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))406 .map(|(_, (amount, _))| {407 total_stakes += 1;408 amount409 })410 .sum();411412 if total_staked.is_zero() {413 return Ok(None.into()); 414 }415416 pendings417 .try_push((staker_id.clone(), total_staked))418 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;419420 <PendingUnstake<T>>::insert(block, pendings);421422 Self::unlock_balance(&staker_id, total_staked)?;423424 <T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;425426 TotalStaked::<T>::set(427 TotalStaked::<T>::get()428 .checked_sub(&total_staked)429 .ok_or(ArithmeticError::Underflow)?,430 );431432 StakesPerAccount::<T>::remove(&staker_id);433434 Self::deposit_event(Event::Unstake(staker_id, total_staked));435436 Ok(None.into())437 }438439 440 441 442 443 444 445 446 447 448 #[pallet::weight(T::WeightInfo::sponsor_collection())]449 pub fn sponsor_collection(450 admin: OriginFor<T>,451 collection_id: CollectionId,452 ) -> DispatchResult {453 let admin_id = ensure_signed(admin)?;454 ensure!(455 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,456 Error::<T>::NoPermission457 );458459 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)460 }461462 463 464 465 466 467 468 469 470 471 472 473 #[pallet::weight(T::WeightInfo::stop_sponsoring_collection())]474 pub fn stop_sponsoring_collection(475 admin: OriginFor<T>,476 collection_id: CollectionId,477 ) -> DispatchResult {478 let admin_id = ensure_signed(admin)?;479480 ensure!(481 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,482 Error::<T>::NoPermission483 );484485 ensure!(486 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?487 == Self::account_id(),488 <Error<T>>::NoPermission489 );490 T::CollectionHandler::remove_collection_sponsor(collection_id)491 }492493 494 495 496 497 498 499 500 501 502 #[pallet::weight(T::WeightInfo::sponsor_contract())]503 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {504 let admin_id = ensure_signed(admin)?;505506 ensure!(507 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,508 Error::<T>::NoPermission509 );510511 T::ContractHandler::set_sponsor(512 T::CrossAccountId::from_sub(Self::account_id()),513 contract_id,514 )515 }516517 518 519 520 521 522 523 524 525 526 527 528 #[pallet::weight(T::WeightInfo::stop_sponsoring_contract())]529 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {530 let admin_id = ensure_signed(admin)?;531532 ensure!(533 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,534 Error::<T>::NoPermission535 );536537 ensure!(538 T::ContractHandler::sponsor(contract_id)?539 .ok_or(<Error<T>>::SponsorNotSet)?540 .as_sub() == &Self::account_id(),541 <Error<T>>::NoPermission542 );543 T::ContractHandler::remove_contract_sponsor(contract_id)544 }545546 547 548 549 550 551 552 553 554 555 556 557 558 #[pallet::weight(T::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]559 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {560 let admin_id = ensure_signed(admin)?;561562 ensure!(563 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,564 Error::<T>::NoPermission565 );566567 568 569 let current_recalc_block =570 Self::get_current_recalc_block(T::RelayBlockNumberProvider::current_block_number());571572 573 574 let next_recalc_block = current_recalc_block + T::RecalculationInterval::get();575576 let mut storage_iterator = Self::get_next_calculated_key()577 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));578579 NextCalculatedRecord::<T>::set(None);580581 {582 let mut stakers_number = stakers_number.unwrap_or(20);583 let last_id = RefCell::new(None);584 let income_acc = RefCell::new(BalanceOf::<T>::default());585 let amount_acc = RefCell::new(BalanceOf::<T>::default());586587 588 589 let flush_stake = || -> DispatchResult {590 if let Some(last_id) = &*last_id.borrow() {591 if !income_acc.borrow().is_zero() {592 <T::Currency as Currency<T::AccountId>>::transfer(593 &T::TreasuryAccountId::get(),594 last_id,595 *income_acc.borrow(),596 ExistenceRequirement::KeepAlive,597 )?;598599 Self::add_lock_balance(last_id, *income_acc.borrow())?;600 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {601 *staked = staked602 .checked_add(&*income_acc.borrow())603 .ok_or(ArithmeticError::Overflow)?;604 Ok(())605 })?;606607 Self::deposit_event(Event::StakingRecalculation(608 last_id.clone(),609 *amount_acc.borrow(),610 *income_acc.borrow(),611 ));612 }613614 *income_acc.borrow_mut() = BalanceOf::<T>::default();615 *amount_acc.borrow_mut() = BalanceOf::<T>::default();616 }617 Ok(())618 };619620 while let Some((621 (current_id, staked_block),622 (amount, next_recalc_block_for_stake),623 )) = storage_iterator.next()624 {625 if stakers_number == 0 {626 NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));627 break;628 }629 if last_id.borrow().as_ref() != Some(¤t_id) {630 flush_stake()?;631 *last_id.borrow_mut() = Some(current_id.clone());632 stakers_number -= 1;633 };634 if current_recalc_block >= next_recalc_block_for_stake {635 *amount_acc.borrow_mut() += amount;636 Self::recalculate_and_insert_stake(637 ¤t_id,638 staked_block,639 next_recalc_block,640 amount,641 ((current_recalc_block - next_recalc_block_for_stake)642 / T::RecalculationInterval::get())643 .into() + 1,644 &mut *income_acc.borrow_mut(),645 );646 }647 }648 flush_stake()?;649 }650651 Ok(())652 }653 }654}655656impl<T: Config> Pallet<T> {657 658 659 660 661 pub fn account_id() -> T::AccountId {662 T::PalletId::get().into_account_truncating()663 }664665 666 667 668 669 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {670 let locked_balance = Self::get_locked_balance(staker)671 .map(|l| l.amount)672 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;673674 675 676 Self::set_lock_unchecked(677 staker,678 locked_balance679 .checked_sub(&amount)680 .ok_or(ArithmeticError::Underflow)?,681 );682 Ok(())683 }684685 686 687 688 689 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {690 Self::get_locked_balance(staker)691 .map_or(<BalanceOf<T>>::default(), |l| l.amount)692 .checked_add(&amount)693 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))694 .ok_or(ArithmeticError::Overflow.into())695 }696697 698 699 700 701 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {702 if amount.is_zero() {703 <T::Currency as LockableCurrency<T::AccountId>>::remove_lock(LOCK_IDENTIFIER, &staker);704 } else {705 <T::Currency as LockableCurrency<T::AccountId>>::set_lock(706 LOCK_IDENTIFIER,707 staker,708 amount,709 WithdrawReasons::all(),710 )711 }712 }713714 715 716 717 pub fn get_locked_balance(718 staker: impl EncodeLike<T::AccountId>,719 ) -> Option<BalanceLock<BalanceOf<T>>> {720 <T::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)721 .into_iter()722 .find(|l| l.id == LOCK_IDENTIFIER)723 }724725 726 727 728 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {729 let staked = Staked::<T>::iter_prefix((staker,))730 .into_iter()731 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {732 acc + amount733 });734 if staked != <BalanceOf<T>>::default() {735 Some(staked)736 } else {737 None738 }739 }740741 742 743 744 745 pub fn total_staked_by_id_per_block(746 staker: impl EncodeLike<T::AccountId>,747 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {748 let mut staked = Staked::<T>::iter_prefix((staker,))749 .into_iter()750 .map(|(block, (amount, _))| (block, amount))751 .collect::<Vec<_>>();752 staked.sort_by_key(|(block, _)| *block);753 if !staked.is_empty() {754 Some(staked)755 } else {756 None757 }758 }759760 761 762 763 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {764 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {765 Self::total_staked_by_id(s.as_sub())766 })767 }768769 770 771 772 773 774775 776 777 778 779 pub fn cross_id_total_staked_per_block(780 staker: T::CrossAccountId,781 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {782 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()783 }784785 fn recalculate_and_insert_stake(786 staker: &T::AccountId,787 staked_block: T::BlockNumber,788 next_recalc_block: T::BlockNumber,789 base: BalanceOf<T>,790 iters: u32,791 income_acc: &mut BalanceOf<T>,792 ) {793 let income = Self::calculate_income(base, iters);794795 base.checked_add(&income).map(|res| {796 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));797 *income_acc += income;798 });799 }800801 fn calculate_income<I>(base: I, iters: u32) -> I802 where803 I: EncodeLike<BalanceOf<T>> + Balance,804 {805 let mut income = base;806807 (0..iters).for_each(|_| income += T::IntervalIncome::get() * income);808809 income - base810 }811812 fn get_current_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {813 (current_relay_block / T::RecalculationInterval::get()) * T::RecalculationInterval::get()814 }815816 fn get_next_calculated_key() -> Option<Vec<u8>> {817 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))818 }819}820821impl<T: Config> Pallet<T>822where823 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,824{825 826 827 828 829 830 831 832 833 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {834 staker.map_or(835 PendingUnstake::<T>::iter_values()836 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))837 .sum(),838 |s| {839 PendingUnstake::<T>::iter_values()840 .flatten()841 .filter_map(|(id, amount)| {842 if id == *s.as_sub() {843 Some(amount)844 } else {845 None846 }847 })848 .sum()849 },850 )851 }852853 854 855 856 857 pub fn cross_id_pending_unstake_per_block(858 staker: T::CrossAccountId,859 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {860 let mut unsorted_res = vec![];861 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {862 pendings.into_iter().for_each(|(id, amount)| {863 if id == *staker.as_sub() {864 unsorted_res.push((block, amount));865 };866 })867 });868869 unsorted_res.sort_by_key(|(block, _)| *block);870 unsorted_res871 }872}