referrerpolicy=no-referrer-when-downgrade

pallet_tips/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Tipping Pallet ( pallet-tips )
19//!
20//! > NOTE: This pallet is tightly coupled with pallet-treasury.
21//!
22//! A subsystem to allow for an agile "tipping" process, whereby a reward may be given without first
23//! having a pre-determined stakeholder group come to consensus on how much should be paid.
24//!
25//! A group of `Tippers` is determined through the config `Config`. After half of these have
26//! declared some amount that they believe a particular reported reason deserves, then a countdown
27//! period is entered where any remaining members can declare their tip amounts also. After the
28//! close of the countdown period, the median of all declared tips is paid to the reported
29//! beneficiary, along with any finders fee, in case of a public (and bonded) original report.
30//!
31//!
32//! ### Terminology
33//!
34//! Tipping protocol:
35//! - **Tipping:** The process of gathering declarations of amounts to tip and taking the median
36//!   amount to be transferred from the treasury to a beneficiary account.
37//! - **Tip Reason:** The reason for a tip; generally a URL which embodies or explains why a
38//!   particular individual (identified by an account ID) is worthy of a recognition by the
39//!   treasury.
40//! - **Finder:** The original public reporter of some reason for tipping.
41//! - **Finders Fee:** Some proportion of the tip amount that is paid to the reporter of the tip,
42//!   rather than the main beneficiary.
43//!
44//! ## Interface
45//!
46//! ### Dispatchable Functions
47//!
48//! Tipping protocol:
49//! - `report_awesome` - Report something worthy of a tip and register for a finders fee.
50//! - `retract_tip` - Retract a previous (finders fee registered) report.
51//! - `tip_new` - Report an item worthy of a tip and declare a specific amount to tip.
52//! - `tip` - Declare or redeclare an amount to tip for a particular reason.
53//! - `close_tip` - Close and pay out a tip.
54
55#![cfg_attr(not(feature = "std"), no_std)]
56
57mod benchmarking;
58mod tests;
59
60pub mod migrations;
61pub mod weights;
62
63extern crate alloc;
64
65use sp_runtime::{
66	traits::{AccountIdConversion, BadOrigin, Hash, StaticLookup, TrailingZeroInput, Zero},
67	Percent, RuntimeDebug,
68};
69
70use alloc::{vec, vec::Vec};
71use codec::{Decode, Encode};
72use frame_support::{
73	ensure,
74	traits::{
75		ContainsLengthBound, Currency, EnsureOrigin, ExistenceRequirement::KeepAlive, Get,
76		OnUnbalanced, ReservableCurrency, SortedMembers,
77	},
78	Parameter,
79};
80use frame_system::pallet_prelude::BlockNumberFor;
81
82#[cfg(any(feature = "try-runtime", test))]
83use sp_runtime::TryRuntimeError;
84
85pub use pallet::*;
86pub use weights::WeightInfo;
87
88const LOG_TARGET: &str = "runtime::tips";
89
90pub type BalanceOf<T, I = ()> = pallet_treasury::BalanceOf<T, I>;
91pub type NegativeImbalanceOf<T, I = ()> = pallet_treasury::NegativeImbalanceOf<T, I>;
92type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
93
94/// An open tipping "motion". Retains all details of a tip including information on the finder
95/// and the members who have voted.
96#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, scale_info::TypeInfo)]
97pub struct OpenTip<
98	AccountId: Parameter,
99	Balance: Parameter,
100	BlockNumber: Parameter,
101	Hash: Parameter,
102> {
103	/// The hash of the reason for the tip. The reason should be a human-readable UTF-8 encoded
104	/// string. A URL would be sensible.
105	reason: Hash,
106	/// The account to be tipped.
107	who: AccountId,
108	/// The account who began this tip.
109	finder: AccountId,
110	/// The amount held on deposit for this tip.
111	deposit: Balance,
112	/// The block number at which this tip will close if `Some`. If `None`, then no closing is
113	/// scheduled.
114	closes: Option<BlockNumber>,
115	/// The members who have voted for this tip. Sorted by AccountId.
116	tips: Vec<(AccountId, Balance)>,
117	/// Whether this tip should result in the finder taking a fee.
118	finders_fee: bool,
119}
120
121#[frame_support::pallet]
122pub mod pallet {
123	use super::*;
124	use frame_support::pallet_prelude::*;
125	use frame_system::pallet_prelude::*;
126
127	/// The in-code storage version.
128	const STORAGE_VERSION: StorageVersion = StorageVersion::new(4);
129
130	#[pallet::pallet]
131	#[pallet::storage_version(STORAGE_VERSION)]
132	#[pallet::without_storage_info]
133	pub struct Pallet<T, I = ()>(_);
134
135	#[pallet::config]
136	pub trait Config<I: 'static = ()>: frame_system::Config + pallet_treasury::Config<I> {
137		/// The overarching event type.
138		#[allow(deprecated)]
139		type RuntimeEvent: From<Event<Self, I>>
140			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
141
142		/// Maximum acceptable reason length.
143		///
144		/// Benchmarks depend on this value, be sure to update weights file when changing this value
145		#[pallet::constant]
146		type MaximumReasonLength: Get<u32>;
147
148		/// The amount held on deposit per byte within the tip report reason or bounty description.
149		#[pallet::constant]
150		type DataDepositPerByte: Get<BalanceOf<Self, I>>;
151
152		/// The period for which a tip remains open after is has achieved threshold tippers.
153		#[pallet::constant]
154		type TipCountdown: Get<BlockNumberFor<Self>>;
155
156		/// The percent of the final tip which goes to the original reporter of the tip.
157		#[pallet::constant]
158		type TipFindersFee: Get<Percent>;
159
160		/// The non-zero amount held on deposit for placing a tip report.
161		#[pallet::constant]
162		type TipReportDepositBase: Get<BalanceOf<Self, I>>;
163
164		/// The maximum amount for a single tip.
165		#[pallet::constant]
166		type MaxTipAmount: Get<BalanceOf<Self, I>>;
167
168		/// Origin from which tippers must come.
169		///
170		/// `ContainsLengthBound::max_len` must be cost free (i.e. no storage read or heavy
171		/// operation). Benchmarks depend on the value of `ContainsLengthBound::max_len` be sure to
172		/// update weights file when altering this method.
173		type Tippers: SortedMembers<Self::AccountId> + ContainsLengthBound;
174
175		/// Handler for the unbalanced decrease when slashing for a removed tip.
176		type OnSlash: OnUnbalanced<NegativeImbalanceOf<Self, I>>;
177
178		/// Weight information for extrinsics in this pallet.
179		type WeightInfo: WeightInfo;
180	}
181
182	/// TipsMap that are not yet completed. Keyed by the hash of `(reason, who)` from the value.
183	/// This has the insecure enumerable hash function since the key itself is already
184	/// guaranteed to be a secure hash.
185	#[pallet::storage]
186	pub type Tips<T: Config<I>, I: 'static = ()> = StorageMap<
187		_,
188		Twox64Concat,
189		T::Hash,
190		OpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>,
191		OptionQuery,
192	>;
193
194	/// Simple preimage lookup from the reason's hash to the original data. Again, has an
195	/// insecure enumerable hash since the key is guaranteed to be the result of a secure hash.
196	#[pallet::storage]
197	pub type Reasons<T: Config<I>, I: 'static = ()> =
198		StorageMap<_, Identity, T::Hash, Vec<u8>, OptionQuery>;
199
200	#[pallet::event]
201	#[pallet::generate_deposit(pub(super) fn deposit_event)]
202	pub enum Event<T: Config<I>, I: 'static = ()> {
203		/// A new tip suggestion has been opened.
204		NewTip { tip_hash: T::Hash },
205		/// A tip suggestion has reached threshold and is closing.
206		TipClosing { tip_hash: T::Hash },
207		/// A tip suggestion has been closed.
208		TipClosed { tip_hash: T::Hash, who: T::AccountId, payout: BalanceOf<T, I> },
209		/// A tip suggestion has been retracted.
210		TipRetracted { tip_hash: T::Hash },
211		/// A tip suggestion has been slashed.
212		TipSlashed { tip_hash: T::Hash, finder: T::AccountId, deposit: BalanceOf<T, I> },
213	}
214
215	#[pallet::error]
216	pub enum Error<T, I = ()> {
217		/// The reason given is just too big.
218		ReasonTooBig,
219		/// The tip was already found/started.
220		AlreadyKnown,
221		/// The tip hash is unknown.
222		UnknownTip,
223		/// The tip given was too generous.
224		MaxTipAmountExceeded,
225		/// The account attempting to retract the tip is not the finder of the tip.
226		NotFinder,
227		/// The tip cannot be claimed/closed because there are not enough tippers yet.
228		StillOpen,
229		/// The tip cannot be claimed/closed because it's still in the countdown period.
230		Premature,
231	}
232
233	#[pallet::call]
234	impl<T: Config<I>, I: 'static> Pallet<T, I> {
235		/// Report something `reason` that deserves a tip and claim any eventual the finder's fee.
236		///
237		/// The dispatch origin for this call must be _Signed_.
238		///
239		/// Payment: `TipReportDepositBase` will be reserved from the origin account, as well as
240		/// `DataDepositPerByte` for each byte in `reason`.
241		///
242		/// - `reason`: The reason for, or the thing that deserves, the tip; generally this will be
243		///   a UTF-8-encoded URL.
244		/// - `who`: The account which should be credited for the tip.
245		///
246		/// Emits `NewTip` if successful.
247		///
248		/// ## Complexity
249		/// - `O(R)` where `R` length of `reason`.
250		///   - encoding and hashing of 'reason'
251		#[pallet::call_index(0)]
252		#[pallet::weight(<T as Config<I>>::WeightInfo::report_awesome(reason.len() as u32))]
253		pub fn report_awesome(
254			origin: OriginFor<T>,
255			reason: Vec<u8>,
256			who: AccountIdLookupOf<T>,
257		) -> DispatchResult {
258			let finder = ensure_signed(origin)?;
259			let who = T::Lookup::lookup(who)?;
260
261			ensure!(
262				reason.len() <= T::MaximumReasonLength::get() as usize,
263				Error::<T, I>::ReasonTooBig
264			);
265
266			let reason_hash = T::Hashing::hash(&reason[..]);
267			ensure!(!Reasons::<T, I>::contains_key(&reason_hash), Error::<T, I>::AlreadyKnown);
268			let hash = T::Hashing::hash_of(&(&reason_hash, &who));
269			ensure!(!Tips::<T, I>::contains_key(&hash), Error::<T, I>::AlreadyKnown);
270
271			let deposit = T::TipReportDepositBase::get() +
272				T::DataDepositPerByte::get() * (reason.len() as u32).into();
273			T::Currency::reserve(&finder, deposit)?;
274
275			Reasons::<T, I>::insert(&reason_hash, &reason);
276			let tip = OpenTip {
277				reason: reason_hash,
278				who,
279				finder,
280				deposit,
281				closes: None,
282				tips: vec![],
283				finders_fee: true,
284			};
285			Tips::<T, I>::insert(&hash, tip);
286			Self::deposit_event(Event::NewTip { tip_hash: hash });
287			Ok(())
288		}
289
290		/// Retract a prior tip-report from `report_awesome`, and cancel the process of tipping.
291		///
292		/// If successful, the original deposit will be unreserved.
293		///
294		/// The dispatch origin for this call must be _Signed_ and the tip identified by `hash`
295		/// must have been reported by the signing account through `report_awesome` (and not
296		/// through `tip_new`).
297		///
298		/// - `hash`: The identity of the open tip for which a tip value is declared. This is formed
299		///   as the hash of the tuple of the original tip `reason` and the beneficiary account ID.
300		///
301		/// Emits `TipRetracted` if successful.
302		///
303		/// ## Complexity
304		/// - `O(1)`
305		///   - Depends on the length of `T::Hash` which is fixed.
306		#[pallet::call_index(1)]
307		#[pallet::weight(<T as Config<I>>::WeightInfo::retract_tip())]
308		pub fn retract_tip(origin: OriginFor<T>, hash: T::Hash) -> DispatchResult {
309			let who = ensure_signed(origin)?;
310			let tip = Tips::<T, I>::get(&hash).ok_or(Error::<T, I>::UnknownTip)?;
311			ensure!(tip.finder == who, Error::<T, I>::NotFinder);
312
313			Reasons::<T, I>::remove(&tip.reason);
314			Tips::<T, I>::remove(&hash);
315			if !tip.deposit.is_zero() {
316				let err_amount = T::Currency::unreserve(&who, tip.deposit);
317				debug_assert!(err_amount.is_zero());
318			}
319			Self::deposit_event(Event::TipRetracted { tip_hash: hash });
320			Ok(())
321		}
322
323		/// Give a tip for something new; no finder's fee will be taken.
324		///
325		/// The dispatch origin for this call must be _Signed_ and the signing account must be a
326		/// member of the `Tippers` set.
327		///
328		/// - `reason`: The reason for, or the thing that deserves, the tip; generally this will be
329		///   a UTF-8-encoded URL.
330		/// - `who`: The account which should be credited for the tip.
331		/// - `tip_value`: The amount of tip that the sender would like to give. The median tip
332		///   value of active tippers will be given to the `who`.
333		///
334		/// Emits `NewTip` if successful.
335		///
336		/// ## Complexity
337		/// - `O(R + T)` where `R` length of `reason`, `T` is the number of tippers.
338		///   - `O(T)`: decoding `Tipper` vec of length `T`. `T` is charged as upper bound given by
339		///     `ContainsLengthBound`. The actual cost depends on the implementation of
340		///     `T::Tippers`.
341		///   - `O(R)`: hashing and encoding of reason of length `R`
342		#[pallet::call_index(2)]
343		#[pallet::weight(<T as Config<I>>::WeightInfo::tip_new(reason.len() as u32, T::Tippers::max_len() as u32))]
344		pub fn tip_new(
345			origin: OriginFor<T>,
346			reason: Vec<u8>,
347			who: AccountIdLookupOf<T>,
348			#[pallet::compact] tip_value: BalanceOf<T, I>,
349		) -> DispatchResult {
350			let tipper = ensure_signed(origin)?;
351			let who = T::Lookup::lookup(who)?;
352			ensure!(T::Tippers::contains(&tipper), BadOrigin);
353
354			ensure!(T::MaxTipAmount::get() >= tip_value, Error::<T, I>::MaxTipAmountExceeded);
355
356			let reason_hash = T::Hashing::hash(&reason[..]);
357			ensure!(!Reasons::<T, I>::contains_key(&reason_hash), Error::<T, I>::AlreadyKnown);
358
359			let hash = T::Hashing::hash_of(&(&reason_hash, &who));
360			Reasons::<T, I>::insert(&reason_hash, &reason);
361			Self::deposit_event(Event::NewTip { tip_hash: hash });
362			let tips = vec![(tipper.clone(), tip_value)];
363			let tip = OpenTip {
364				reason: reason_hash,
365				who,
366				finder: tipper,
367				deposit: Zero::zero(),
368				closes: None,
369				tips,
370				finders_fee: false,
371			};
372			Tips::<T, I>::insert(&hash, tip);
373			Ok(())
374		}
375
376		/// Declare a tip value for an already-open tip.
377		///
378		/// The dispatch origin for this call must be _Signed_ and the signing account must be a
379		/// member of the `Tippers` set.
380		///
381		/// - `hash`: The identity of the open tip for which a tip value is declared. This is formed
382		///   as the hash of the tuple of the hash of the original tip `reason` and the beneficiary
383		///   account ID.
384		/// - `tip_value`: The amount of tip that the sender would like to give. The median tip
385		///   value of active tippers will be given to the `who`.
386		///
387		/// Emits `TipClosing` if the threshold of tippers has been reached and the countdown period
388		/// has started.
389		///
390		/// ## Complexity
391		/// - `O(T)` where `T` is the number of tippers. decoding `Tipper` vec of length `T`, insert
392		///   tip and check closing, `T` is charged as upper bound given by `ContainsLengthBound`.
393		///   The actual cost depends on the implementation of `T::Tippers`.
394		///
395		///   Actually weight could be lower as it depends on how many tips are in `OpenTip` but it
396		///   is weighted as if almost full i.e of length `T-1`.
397		#[pallet::call_index(3)]
398		#[pallet::weight(<T as Config<I>>::WeightInfo::tip(T::Tippers::max_len() as u32))]
399		pub fn tip(
400			origin: OriginFor<T>,
401			hash: T::Hash,
402			#[pallet::compact] tip_value: BalanceOf<T, I>,
403		) -> DispatchResult {
404			let tipper = ensure_signed(origin)?;
405			ensure!(T::Tippers::contains(&tipper), BadOrigin);
406
407			ensure!(T::MaxTipAmount::get() >= tip_value, Error::<T, I>::MaxTipAmountExceeded);
408
409			let mut tip = Tips::<T, I>::get(hash).ok_or(Error::<T, I>::UnknownTip)?;
410
411			if Self::insert_tip_and_check_closing(&mut tip, tipper, tip_value) {
412				Self::deposit_event(Event::TipClosing { tip_hash: hash });
413			}
414			Tips::<T, I>::insert(&hash, tip);
415			Ok(())
416		}
417
418		/// Close and payout a tip.
419		///
420		/// The dispatch origin for this call must be _Signed_.
421		///
422		/// The tip identified by `hash` must have finished its countdown period.
423		///
424		/// - `hash`: The identity of the open tip for which a tip value is declared. This is formed
425		///   as the hash of the tuple of the original tip `reason` and the beneficiary account ID.
426		///
427		/// ## Complexity
428		/// - : `O(T)` where `T` is the number of tippers. decoding `Tipper` vec of length `T`. `T`
429		///   is charged as upper bound given by `ContainsLengthBound`. The actual cost depends on
430		///   the implementation of `T::Tippers`.
431		#[pallet::call_index(4)]
432		#[pallet::weight(<T as Config<I>>::WeightInfo::close_tip(T::Tippers::max_len() as u32))]
433		pub fn close_tip(origin: OriginFor<T>, hash: T::Hash) -> DispatchResult {
434			ensure_signed(origin)?;
435
436			let tip = Tips::<T, I>::get(hash).ok_or(Error::<T, I>::UnknownTip)?;
437			let n = tip.closes.as_ref().ok_or(Error::<T, I>::StillOpen)?;
438			ensure!(frame_system::Pallet::<T>::block_number() >= *n, Error::<T, I>::Premature);
439			// closed.
440			Reasons::<T, I>::remove(&tip.reason);
441			Tips::<T, I>::remove(hash);
442			Self::payout_tip(hash, tip);
443			Ok(())
444		}
445
446		/// Remove and slash an already-open tip.
447		///
448		/// May only be called from `T::RejectOrigin`.
449		///
450		/// As a result, the finder is slashed and the deposits are lost.
451		///
452		/// Emits `TipSlashed` if successful.
453		///
454		/// ## Complexity
455		/// - O(1).
456		#[pallet::call_index(5)]
457		#[pallet::weight(<T as Config<I>>::WeightInfo::slash_tip(T::Tippers::max_len() as u32))]
458		pub fn slash_tip(origin: OriginFor<T>, hash: T::Hash) -> DispatchResult {
459			T::RejectOrigin::ensure_origin(origin)?;
460
461			let tip = Tips::<T, I>::take(hash).ok_or(Error::<T, I>::UnknownTip)?;
462
463			if !tip.deposit.is_zero() {
464				let imbalance = T::Currency::slash_reserved(&tip.finder, tip.deposit).0;
465				T::OnSlash::on_unbalanced(imbalance);
466			}
467			Reasons::<T, I>::remove(&tip.reason);
468			Self::deposit_event(Event::TipSlashed {
469				tip_hash: hash,
470				finder: tip.finder,
471				deposit: tip.deposit,
472			});
473			Ok(())
474		}
475	}
476
477	#[pallet::hooks]
478	impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
479		fn integrity_test() {
480			assert!(
481				!T::TipReportDepositBase::get().is_zero(),
482				"`TipReportDepositBase` should not be zero",
483			);
484		}
485
486		#[cfg(feature = "try-runtime")]
487		fn try_state(_n: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
488			Self::do_try_state()
489		}
490	}
491}
492
493impl<T: Config<I>, I: 'static> Pallet<T, I> {
494	// Add public immutables and private mutables.
495
496	/// Access tips storage from outside
497	pub fn tips(
498		hash: T::Hash,
499	) -> Option<OpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>> {
500		Tips::<T, I>::get(hash)
501	}
502
503	/// Access reasons storage from outside
504	pub fn reasons(hash: T::Hash) -> Option<Vec<u8>> {
505		Reasons::<T, I>::get(hash)
506	}
507
508	/// The account ID of the treasury pot.
509	///
510	/// This actually does computation. If you need to keep using it, then make sure you cache the
511	/// value and only call this once.
512	pub fn account_id() -> T::AccountId {
513		T::PalletId::get().into_account_truncating()
514	}
515
516	/// Given a mutable reference to an `OpenTip`, insert the tip into it and check whether it
517	/// closes, if so, then deposit the relevant event and set closing accordingly.
518	///
519	/// `O(T)` and one storage access.
520	fn insert_tip_and_check_closing(
521		tip: &mut OpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>,
522		tipper: T::AccountId,
523		tip_value: BalanceOf<T, I>,
524	) -> bool {
525		match tip.tips.binary_search_by_key(&&tipper, |x| &x.0) {
526			Ok(pos) => tip.tips[pos] = (tipper, tip_value),
527			Err(pos) => tip.tips.insert(pos, (tipper, tip_value)),
528		}
529		Self::retain_active_tips(&mut tip.tips);
530		let threshold = T::Tippers::count().div_ceil(2);
531		if tip.tips.len() >= threshold && tip.closes.is_none() {
532			tip.closes = Some(frame_system::Pallet::<T>::block_number() + T::TipCountdown::get());
533			true
534		} else {
535			false
536		}
537	}
538
539	/// Remove any non-members of `Tippers` from a `tips` vector. `O(T)`.
540	fn retain_active_tips(tips: &mut Vec<(T::AccountId, BalanceOf<T, I>)>) {
541		let members = T::Tippers::sorted_members();
542		let mut members_iter = members.iter();
543		let mut member = members_iter.next();
544		tips.retain(|(ref a, _)| loop {
545			match member {
546				None => break false,
547				Some(m) if m > a => break false,
548				Some(m) => {
549					member = members_iter.next();
550					if m < a {
551						continue
552					} else {
553						break true
554					}
555				},
556			}
557		});
558	}
559
560	/// Execute the payout of a tip.
561	///
562	/// Up to three balance operations.
563	/// Plus `O(T)` (`T` is Tippers length).
564	fn payout_tip(
565		hash: T::Hash,
566		tip: OpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>,
567	) {
568		let mut tips = tip.tips;
569		Self::retain_active_tips(&mut tips);
570		tips.sort_by_key(|i| i.1);
571
572		let treasury = Self::account_id();
573		let max_payout = pallet_treasury::Pallet::<T, I>::pot();
574
575		let mut payout = tips[tips.len() / 2].1.min(max_payout);
576		if !tip.deposit.is_zero() {
577			let err_amount = T::Currency::unreserve(&tip.finder, tip.deposit);
578			debug_assert!(err_amount.is_zero());
579		}
580
581		if tip.finders_fee && tip.finder != tip.who {
582			// pay out the finder's fee.
583			let finders_fee = T::TipFindersFee::get() * payout;
584			payout -= finders_fee;
585			// this should go through given we checked it's at most the free balance, but still
586			// we only make a best-effort.
587			let res = T::Currency::transfer(&treasury, &tip.finder, finders_fee, KeepAlive);
588			debug_assert!(res.is_ok());
589		}
590
591		// same as above: best-effort only.
592		let res = T::Currency::transfer(&treasury, &tip.who, payout, KeepAlive);
593		debug_assert!(res.is_ok());
594		Self::deposit_event(Event::TipClosed { tip_hash: hash, who: tip.who, payout });
595	}
596
597	pub fn migrate_retract_tip_for_tip_new(module: &[u8], item: &[u8]) {
598		/// An open tipping "motion". Retains all details of a tip including information on the
599		/// finder and the members who have voted.
600		#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug)]
601		pub struct OldOpenTip<
602			AccountId: Parameter,
603			Balance: Parameter,
604			BlockNumber: Parameter,
605			Hash: Parameter,
606		> {
607			/// The hash of the reason for the tip. The reason should be a human-readable UTF-8
608			/// encoded string. A URL would be sensible.
609			reason: Hash,
610			/// The account to be tipped.
611			who: AccountId,
612			/// The account who began this tip and the amount held on deposit.
613			finder: Option<(AccountId, Balance)>,
614			/// The block number at which this tip will close if `Some`. If `None`, then no closing
615			/// is scheduled.
616			closes: Option<BlockNumber>,
617			/// The members who have voted for this tip. Sorted by AccountId.
618			tips: Vec<(AccountId, Balance)>,
619		}
620
621		use frame_support::{migration::storage_key_iter, Twox64Concat};
622
623		let zero_account = T::AccountId::decode(&mut TrailingZeroInput::new(&[][..]))
624			.expect("infinite input; qed");
625
626		for (hash, old_tip) in storage_key_iter::<
627			T::Hash,
628			OldOpenTip<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T>, T::Hash>,
629			Twox64Concat,
630		>(module, item)
631		.drain()
632		{
633			let (finder, deposit, finders_fee) = match old_tip.finder {
634				Some((finder, deposit)) => (finder, deposit, true),
635				None => (zero_account.clone(), Zero::zero(), false),
636			};
637			let new_tip = OpenTip {
638				reason: old_tip.reason,
639				who: old_tip.who,
640				finder,
641				deposit,
642				closes: old_tip.closes,
643				tips: old_tip.tips,
644				finders_fee,
645			};
646			Tips::<T, I>::insert(hash, new_tip)
647		}
648	}
649
650	/// Ensure the correctness of the state of this pallet.
651	///
652	/// This should be valid before and after each state transition of this pallet.
653	///
654	/// ## Invariants:
655	/// 1. The number of entries in `Tips` should be equal to `Reasons`.
656	/// 2. Reasons exists for each Tip[`OpenTip.reason`].
657	/// 3. If `OpenTip.finders_fee` is true, then OpenTip.deposit should be greater than zero.
658	#[cfg(any(feature = "try-runtime", test))]
659	pub fn do_try_state() -> Result<(), TryRuntimeError> {
660		let reasons = Reasons::<T, I>::iter_keys().collect::<Vec<_>>();
661		let tips = Tips::<T, I>::iter_keys().collect::<Vec<_>>();
662
663		ensure!(
664			reasons.len() == tips.len(),
665			TryRuntimeError::Other("Equal length of entries in `Tips` and `Reasons` Storage")
666		);
667
668		for tip in Tips::<T, I>::iter_keys() {
669			let open_tip = Tips::<T, I>::get(&tip).expect("All map keys are valid; qed");
670
671			if open_tip.finders_fee {
672				ensure!(
673					!open_tip.deposit.is_zero(),
674					TryRuntimeError::Other(
675						"Tips with `finders_fee` should have non-zero `deposit`."
676					)
677				)
678			}
679
680			ensure!(
681				reasons.contains(&open_tip.reason),
682				TryRuntimeError::Other("no reason for this tip")
683			);
684		}
685		Ok(())
686	}
687}