#![cfg_attr(not(feature = "std"), no_std)]
mod benchmarking;
mod tests;
pub mod migrations;
pub mod weights;
extern crate alloc;
use sp_runtime::{
traits::{AccountIdConversion, BadOrigin, Hash, StaticLookup, TrailingZeroInput, Zero},
Debug, Percent,
};
use alloc::{vec, vec::Vec};
use codec::{Decode, Encode};
use frame_support::{
ensure,
traits::{
ContainsLengthBound, Currency, EnsureOrigin, ExistenceRequirement::KeepAlive, Get,
OnUnbalanced, ReservableCurrency, SortedMembers,
},
Parameter,
};
use frame_system::pallet_prelude::BlockNumberFor;
#[cfg(any(feature = "try-runtime", test))]
use sp_runtime::TryRuntimeError;
pub use pallet::*;
pub use weights::WeightInfo;
const LOG_TARGET: &str = "runtime::tips";
pub type BalanceOf<T, I = ()> = pallet_treasury::BalanceOf<T, I>;
pub type NegativeImbalanceOf<T, I = ()> = pallet_treasury::NegativeImbalanceOf<T, I>;
type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, scale_info::TypeInfo)]
pub struct OpenTip<
AccountId: Parameter,
Balance: Parameter,
BlockNumber: Parameter,
Hash: Parameter,
> {
reason: Hash,
who: AccountId,
finder: AccountId,
deposit: Balance,
closes: Option<BlockNumber>,
tips: Vec<(AccountId, Balance)>,
finders_fee: bool,
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
const STORAGE_VERSION: StorageVersion = StorageVersion::new(4);
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::without_storage_info]
pub struct Pallet<T, I = ()>(_);
#[pallet::config]
pub trait Config<I: 'static = ()>: frame_system::Config + pallet_treasury::Config<I> {
#[allow(deprecated)]
type RuntimeEvent: From<Event<Self, I>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
#[pallet::constant]
type MaximumReasonLength: Get<u32>;
#[pallet::constant]
type DataDepositPerByte: Get<BalanceOf<Self, I>>;
#[pallet::constant]
type TipCountdown: Get<BlockNumberFor<Self>>;
#[pallet::constant]
type TipFindersFee: Get<Percent>;
#[pallet::constant]
type TipReportDepositBase: Get<BalanceOf<Self, I>>;
#[pallet::constant]
type MaxTipAmount: Get<BalanceOf<Self, I>>;
type Tippers: SortedMembers<Self::AccountId> + ContainsLengthBound;
type OnSlash: OnUnbalanced<NegativeImbalanceOf<Self, I>>;
type WeightInfo: WeightInfo;
}
#[pallet::storage]
pub type Tips<T: Config<I>, I: 'static = ()> = StorageMap<
_,
Twox64Concat,
T::Hash,
OpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>,
OptionQuery,
>;
#[pallet::storage]
pub type Reasons<T: Config<I>, I: 'static = ()> =
StorageMap<_, Identity, T::Hash, Vec<u8>, OptionQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config<I>, I: 'static = ()> {
NewTip { tip_hash: T::Hash },
TipClosing { tip_hash: T::Hash },
TipClosed { tip_hash: T::Hash, who: T::AccountId, payout: BalanceOf<T, I> },
TipRetracted { tip_hash: T::Hash },
TipSlashed { tip_hash: T::Hash, finder: T::AccountId, deposit: BalanceOf<T, I> },
}
#[pallet::error]
pub enum Error<T, I = ()> {
ReasonTooBig,
AlreadyKnown,
UnknownTip,
MaxTipAmountExceeded,
NotFinder,
StillOpen,
Premature,
}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config<I>>::WeightInfo::report_awesome(reason.len() as u32))]
pub fn report_awesome(
origin: OriginFor<T>,
reason: Vec<u8>,
who: AccountIdLookupOf<T>,
) -> DispatchResult {
let finder = ensure_signed(origin)?;
let who = T::Lookup::lookup(who)?;
ensure!(
reason.len() <= T::MaximumReasonLength::get() as usize,
Error::<T, I>::ReasonTooBig
);
let reason_hash = T::Hashing::hash(&reason[..]);
ensure!(!Reasons::<T, I>::contains_key(&reason_hash), Error::<T, I>::AlreadyKnown);
let hash = T::Hashing::hash_of(&(&reason_hash, &who));
ensure!(!Tips::<T, I>::contains_key(&hash), Error::<T, I>::AlreadyKnown);
let deposit = T::TipReportDepositBase::get() +
T::DataDepositPerByte::get() * (reason.len() as u32).into();
T::Currency::reserve(&finder, deposit)?;
Reasons::<T, I>::insert(&reason_hash, &reason);
let tip = OpenTip {
reason: reason_hash,
who,
finder,
deposit,
closes: None,
tips: vec![],
finders_fee: true,
};
Tips::<T, I>::insert(&hash, tip);
Self::deposit_event(Event::NewTip { tip_hash: hash });
Ok(())
}
#[pallet::call_index(1)]
#[pallet::weight(<T as Config<I>>::WeightInfo::retract_tip())]
pub fn retract_tip(origin: OriginFor<T>, hash: T::Hash) -> DispatchResult {
let who = ensure_signed(origin)?;
let tip = Tips::<T, I>::get(&hash).ok_or(Error::<T, I>::UnknownTip)?;
ensure!(tip.finder == who, Error::<T, I>::NotFinder);
Reasons::<T, I>::remove(&tip.reason);
Tips::<T, I>::remove(&hash);
if !tip.deposit.is_zero() {
let err_amount = T::Currency::unreserve(&who, tip.deposit);
debug_assert!(err_amount.is_zero());
}
Self::deposit_event(Event::TipRetracted { tip_hash: hash });
Ok(())
}
#[pallet::call_index(2)]
#[pallet::weight(<T as Config<I>>::WeightInfo::tip_new(reason.len() as u32, T::Tippers::max_len() as u32))]
pub fn tip_new(
origin: OriginFor<T>,
reason: Vec<u8>,
who: AccountIdLookupOf<T>,
#[pallet::compact] tip_value: BalanceOf<T, I>,
) -> DispatchResult {
let tipper = ensure_signed(origin)?;
let who = T::Lookup::lookup(who)?;
ensure!(T::Tippers::contains(&tipper), BadOrigin);
ensure!(T::MaxTipAmount::get() >= tip_value, Error::<T, I>::MaxTipAmountExceeded);
let reason_hash = T::Hashing::hash(&reason[..]);
ensure!(!Reasons::<T, I>::contains_key(&reason_hash), Error::<T, I>::AlreadyKnown);
let hash = T::Hashing::hash_of(&(&reason_hash, &who));
Reasons::<T, I>::insert(&reason_hash, &reason);
Self::deposit_event(Event::NewTip { tip_hash: hash });
let tips = vec![(tipper.clone(), tip_value)];
let tip = OpenTip {
reason: reason_hash,
who,
finder: tipper,
deposit: Zero::zero(),
closes: None,
tips,
finders_fee: false,
};
Tips::<T, I>::insert(&hash, tip);
Ok(())
}
#[pallet::call_index(3)]
#[pallet::weight(<T as Config<I>>::WeightInfo::tip(T::Tippers::max_len() as u32))]
pub fn tip(
origin: OriginFor<T>,
hash: T::Hash,
#[pallet::compact] tip_value: BalanceOf<T, I>,
) -> DispatchResult {
let tipper = ensure_signed(origin)?;
ensure!(T::Tippers::contains(&tipper), BadOrigin);
ensure!(T::MaxTipAmount::get() >= tip_value, Error::<T, I>::MaxTipAmountExceeded);
let mut tip = Tips::<T, I>::get(hash).ok_or(Error::<T, I>::UnknownTip)?;
if Self::insert_tip_and_check_closing(&mut tip, tipper, tip_value) {
Self::deposit_event(Event::TipClosing { tip_hash: hash });
}
Tips::<T, I>::insert(&hash, tip);
Ok(())
}
#[pallet::call_index(4)]
#[pallet::weight(<T as Config<I>>::WeightInfo::close_tip(T::Tippers::max_len() as u32))]
pub fn close_tip(origin: OriginFor<T>, hash: T::Hash) -> DispatchResult {
ensure_signed(origin)?;
let tip = Tips::<T, I>::get(hash).ok_or(Error::<T, I>::UnknownTip)?;
let n = tip.closes.as_ref().ok_or(Error::<T, I>::StillOpen)?;
ensure!(frame_system::Pallet::<T>::block_number() >= *n, Error::<T, I>::Premature);
Reasons::<T, I>::remove(&tip.reason);
Tips::<T, I>::remove(hash);
Self::payout_tip(hash, tip);
Ok(())
}
#[pallet::call_index(5)]
#[pallet::weight(<T as Config<I>>::WeightInfo::slash_tip(T::Tippers::max_len() as u32))]
pub fn slash_tip(origin: OriginFor<T>, hash: T::Hash) -> DispatchResult {
T::RejectOrigin::ensure_origin(origin)?;
let tip = Tips::<T, I>::take(hash).ok_or(Error::<T, I>::UnknownTip)?;
if !tip.deposit.is_zero() {
let imbalance = T::Currency::slash_reserved(&tip.finder, tip.deposit).0;
T::OnSlash::on_unbalanced(imbalance);
}
Reasons::<T, I>::remove(&tip.reason);
Self::deposit_event(Event::TipSlashed {
tip_hash: hash,
finder: tip.finder,
deposit: tip.deposit,
});
Ok(())
}
}
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
fn integrity_test() {
assert!(
!T::TipReportDepositBase::get().is_zero(),
"`TipReportDepositBase` should not be zero",
);
}
#[cfg(feature = "try-runtime")]
fn try_state(_n: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
Self::do_try_state()
}
}
}
impl<T: Config<I>, I: 'static> Pallet<T, I> {
pub fn tips(
hash: T::Hash,
) -> Option<OpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>> {
Tips::<T, I>::get(hash)
}
pub fn reasons(hash: T::Hash) -> Option<Vec<u8>> {
Reasons::<T, I>::get(hash)
}
pub fn account_id() -> T::AccountId {
T::PalletId::get().into_account_truncating()
}
fn insert_tip_and_check_closing(
tip: &mut OpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>,
tipper: T::AccountId,
tip_value: BalanceOf<T, I>,
) -> bool {
match tip.tips.binary_search_by_key(&&tipper, |x| &x.0) {
Ok(pos) => tip.tips[pos] = (tipper, tip_value),
Err(pos) => tip.tips.insert(pos, (tipper, tip_value)),
}
Self::retain_active_tips(&mut tip.tips);
let threshold = T::Tippers::count().div_ceil(2);
if tip.tips.len() >= threshold && tip.closes.is_none() {
tip.closes = Some(frame_system::Pallet::<T>::block_number() + T::TipCountdown::get());
true
} else {
false
}
}
fn retain_active_tips(tips: &mut Vec<(T::AccountId, BalanceOf<T, I>)>) {
let members = T::Tippers::sorted_members();
let mut members_iter = members.iter();
let mut member = members_iter.next();
tips.retain(|(ref a, _)| loop {
match member {
None => break false,
Some(m) if m > a => break false,
Some(m) => {
member = members_iter.next();
if m < a {
continue;
} else {
break true;
}
},
}
});
}
fn payout_tip(
hash: T::Hash,
tip: OpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>,
) {
let mut tips = tip.tips;
Self::retain_active_tips(&mut tips);
tips.sort_by_key(|i| i.1);
let treasury = Self::account_id();
let max_payout = pallet_treasury::Pallet::<T, I>::pot();
let mut payout = tips[tips.len() / 2].1.min(max_payout);
if !tip.deposit.is_zero() {
let err_amount = T::Currency::unreserve(&tip.finder, tip.deposit);
debug_assert!(err_amount.is_zero());
}
if tip.finders_fee && tip.finder != tip.who {
let finders_fee = T::TipFindersFee::get() * payout;
payout -= finders_fee;
let res = T::Currency::transfer(&treasury, &tip.finder, finders_fee, KeepAlive);
debug_assert!(res.is_ok());
}
let res = T::Currency::transfer(&treasury, &tip.who, payout, KeepAlive);
debug_assert!(res.is_ok());
Self::deposit_event(Event::TipClosed { tip_hash: hash, who: tip.who, payout });
}
pub fn migrate_retract_tip_for_tip_new(module: &[u8], item: &[u8]) {
#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug)]
pub struct OldOpenTip<
AccountId: Parameter,
Balance: Parameter,
BlockNumber: Parameter,
Hash: Parameter,
> {
reason: Hash,
who: AccountId,
finder: Option<(AccountId, Balance)>,
closes: Option<BlockNumber>,
tips: Vec<(AccountId, Balance)>,
}
use frame_support::{migration::storage_key_iter, Twox64Concat};
let zero_account = T::AccountId::decode(&mut TrailingZeroInput::new(&[][..]))
.expect("infinite input; qed");
for (hash, old_tip) in storage_key_iter::<
T::Hash,
OldOpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>,
Twox64Concat,
>(module, item)
.drain()
{
let (finder, deposit, finders_fee) = match old_tip.finder {
Some((finder, deposit)) => (finder, deposit, true),
None => (zero_account.clone(), Zero::zero(), false),
};
let new_tip = OpenTip {
reason: old_tip.reason,
who: old_tip.who,
finder,
deposit,
closes: old_tip.closes,
tips: old_tip.tips,
finders_fee,
};
Tips::<T, I>::insert(hash, new_tip)
}
}
#[cfg(any(feature = "try-runtime", test))]
pub fn do_try_state() -> Result<(), TryRuntimeError> {
let reasons = Reasons::<T, I>::iter_keys().collect::<Vec<_>>();
let tips = Tips::<T, I>::iter_keys().collect::<Vec<_>>();
ensure!(
reasons.len() == tips.len(),
TryRuntimeError::Other("Equal length of entries in `Tips` and `Reasons` Storage")
);
for tip in Tips::<T, I>::iter_keys() {
let open_tip = Tips::<T, I>::get(&tip).expect("All map keys are valid; qed");
if open_tip.finders_fee {
ensure!(
!open_tip.deposit.is_zero(),
TryRuntimeError::Other(
"Tips with `finders_fee` should have non-zero `deposit`."
)
)
}
ensure!(
reasons.contains(&open_tip.reason),
TryRuntimeError::Other("no reason for this tip")
);
}
Ok(())
}
}