referrerpolicy=no-referrer-when-downgrade

pallet_bounties/
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//! # Bounties Module ( pallet-bounties )
19//!
20//! ## Bounty
21//!
22//! > NOTE: This pallet is tightly coupled with pallet-treasury.
23//!
24//! A Bounty Spending is a reward for a specified body of work - or specified set of objectives -
25//! that needs to be executed for a predefined Treasury amount to be paid out. A curator is assigned
26//! after the bounty is approved and funded by Council, to be delegated with the responsibility of
27//! assigning a payout address once the specified set of objectives is completed.
28//!
29//! After the Council has activated a bounty, it delegates the work that requires expertise to a
30//! curator in exchange of a deposit. Once the curator accepts the bounty, they get to close the
31//! active bounty. Closing the active bounty enacts a delayed payout to the payout address, the
32//! curator fee and the return of the curator deposit. The delay allows for intervention through
33//! regular democracy. The Council gets to unassign the curator, resulting in a new curator
34//! election. The Council also gets to cancel the bounty if deemed necessary before assigning a
35//! curator or once the bounty is active or payout is pending, resulting in the slash of the
36//! curator's deposit.
37//!
38//! This pallet may opt into using a [`ChildBountyManager`] that enables bounties to be split into
39//! sub-bounties, as children of an established bounty (called the parent in the context of it's
40//! children).
41//!
42//! > NOTE: The parent bounty cannot be closed if it has a non-zero number of it has active child
43//! > bounties associated with it.
44//!
45//! ### Terminology
46//!
47//! Bounty:
48//!
49//! - **Bounty spending proposal:** A proposal to reward a predefined body of work upon completion
50//!   by the Treasury.
51//! - **Proposer:** An account proposing a bounty spending.
52//! - **Curator:** An account managing the bounty and assigning a payout address receiving the
53//!   reward for the completion of work.
54//! - **Deposit:** The amount held on deposit for placing a bounty proposal plus the amount held on
55//!   deposit per byte within the bounty description.
56//! - **Curator deposit:** The payment from a candidate willing to curate an approved bounty. The
57//!   deposit is returned when/if the bounty is completed.
58//! - **Bounty value:** The total amount that should be paid to the Payout Address if the bounty is
59//!   rewarded.
60//! - **Payout address:** The account to which the total or part of the bounty is assigned to.
61//! - **Payout Delay:** The delay period for which a bounty beneficiary needs to wait before
62//!   claiming.
63//! - **Curator fee:** The reserved upfront payment for a curator for work related to the bounty.
64//!
65//! ## Interface
66//!
67//! ### Dispatchable Functions
68//!
69//! Bounty protocol:
70//!
71//! - `propose_bounty` - Propose a specific treasury amount to be earmarked for a predefined set of
72//!   tasks and stake the required deposit.
73//! - `approve_bounty` - Accept a specific treasury amount to be earmarked for a predefined body of
74//!   work.
75//! - `propose_curator` - Assign an account to a bounty as candidate curator.
76//! - `approve_bounty_with_curator` - Accept a specific treasury amount for a predefined body of
77//!   work with assigned candidate curator account.
78//! - `accept_curator` - Accept a bounty assignment from the Council, setting a curator deposit.
79//! - `extend_bounty_expiry` - Extend the expiry block number of the bounty and stay active.
80//! - `award_bounty` - Close and pay out the specified amount for the completed work.
81//! - `claim_bounty` - Claim a specific bounty amount from the Payout Address.
82//! - `unassign_curator` - Unassign an accepted curator from a specific earmark.
83//! - `close_bounty` - Cancel the earmark for a specific treasury amount and close the bounty.
84
85#![recursion_limit = "512"]
86#![cfg_attr(not(feature = "std"), no_std)]
87
88#[cfg(feature = "runtime-benchmarks")]
89mod benchmarking;
90pub mod migrations;
91mod tests;
92pub mod weights;
93
94extern crate alloc;
95
96use alloc::vec::Vec;
97
98use frame_support::traits::{
99	fungible::{self, Mutate as FungibleMutate},
100	fungibles::{
101		Create as FungiblesCreate, Inspect as FungiblesInspect, Mutate as FungiblesMutate,
102	},
103	tokens::{Fortitude, Preservation},
104	Currency,
105	ExistenceRequirement::AllowDeath,
106	Get, Imbalance, OnUnbalanced, ReservableCurrency,
107};
108
109use sp_runtime::{
110	traits::{AccountIdConversion, BadOrigin, BlockNumberProvider, Saturating, StaticLookup, Zero},
111	Debug, DispatchResult, Permill,
112};
113
114use frame_support::{
115	dispatch::DispatchResultWithPostInfo, pallet_prelude::*, traits::EnsureOrigin,
116};
117use frame_system::pallet_prelude::{
118	ensure_signed, BlockNumberFor as SystemBlockNumberFor, OriginFor,
119};
120use scale_info::TypeInfo;
121pub use weights::WeightInfo;
122
123pub use pallet::*;
124
125type BalanceOf<T, I = ()> = pallet_treasury::BalanceOf<T, I>;
126
127type PositiveImbalanceOf<T, I = ()> = pallet_treasury::PositiveImbalanceOf<T, I>;
128
129/// An index of a bounty. Just a `u32`.
130pub type BountyIndex = u32;
131
132type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
133
134type BlockNumberFor<T, I = ()> =
135	<<T as pallet_treasury::Config<I>>::BlockNumberProvider as BlockNumberProvider>::BlockNumber;
136
137/// A bounty proposal.
138#[derive(
139	Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen,
140)]
141pub struct Bounty<AccountId, Balance, BlockNumber> {
142	/// The account proposing it.
143	pub proposer: AccountId,
144	/// The (total) amount that should be paid if the bounty is rewarded.
145	pub value: Balance,
146	/// The curator fee. Included in value.
147	pub fee: Balance,
148	/// The deposit of curator.
149	pub curator_deposit: Balance,
150	/// The amount held on deposit (reserved) for making this proposal.
151	bond: Balance,
152	/// The status of this bounty.
153	status: BountyStatus<AccountId, BlockNumber>,
154}
155
156impl<AccountId: PartialEq + Clone + Ord, Balance, BlockNumber: Clone>
157	Bounty<AccountId, Balance, BlockNumber>
158{
159	/// Getter for bounty status, to be used for child bounties.
160	pub fn get_status(&self) -> BountyStatus<AccountId, BlockNumber> {
161		self.status.clone()
162	}
163}
164
165/// The status of a bounty proposal.
166#[derive(
167	Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen,
168)]
169pub enum BountyStatus<AccountId, BlockNumber> {
170	/// The bounty is proposed and waiting for approval.
171	Proposed,
172	/// The bounty is approved and waiting to become active at next spend period.
173	Approved,
174	/// The bounty is funded and waiting for curator assignment.
175	Funded,
176	/// A curator has been proposed. Waiting for acceptance from the curator.
177	CuratorProposed {
178		/// The assigned curator of this bounty.
179		curator: AccountId,
180	},
181	/// The bounty is active and waiting to be awarded.
182	Active {
183		/// The curator of this bounty.
184		curator: AccountId,
185		/// An update from the curator is due by this block, else they are considered inactive.
186		update_due: BlockNumber,
187	},
188	/// The bounty is awarded and waiting to released after a delay.
189	PendingPayout {
190		/// The curator of this bounty.
191		curator: AccountId,
192		/// The beneficiary of the bounty.
193		beneficiary: AccountId,
194		/// When the bounty can be claimed.
195		unlock_at: BlockNumber,
196	},
197	/// The bounty is approved with curator assigned.
198	ApprovedWithCurator {
199		/// The assigned curator of this bounty.
200		curator: AccountId,
201	},
202}
203
204/// The child bounty manager.
205pub trait ChildBountyManager<Balance> {
206	/// Get the active child bounties for a parent bounty.
207	fn child_bounties_count(bounty_id: BountyIndex) -> BountyIndex;
208
209	/// Take total curator fees of children-bounty curators.
210	fn children_curator_fees(bounty_id: BountyIndex) -> Balance;
211
212	/// Hook called when a parent bounty is removed.
213	fn bounty_removed(bounty_id: BountyIndex);
214}
215
216/// Transfer all assets held by an account (e.g. a stale bounty sub-account) back to another.
217pub trait TransferAllAssets<AccountId> {
218	/// Transfer all assets from one account to another, possibly reaping `from`.
219	///
220	/// Returns `true` if any balance was actually transferred, `false` if the account was already
221	/// empty.
222	fn force_transfer_all_assets(from: &AccountId, to: &AccountId) -> Result<bool, DispatchError>;
223
224	/// Mint benchmark amounts of each relevant asset into `from`.
225	///
226	/// Called during benchmarking so that `force_transfer_all_assets` exercises real transfers
227	/// instead of being a no-op. The default implementation is a no-op.
228	#[cfg(feature = "runtime-benchmarks")]
229	fn ensure_successful(_from: &AccountId) {}
230}
231
232impl<AccountId> TransferAllAssets<AccountId> for () {
233	fn force_transfer_all_assets(_: &AccountId, _: &AccountId) -> Result<bool, DispatchError> {
234		Ok(false)
235	}
236}
237
238/// Transfer the entire balance of a single `fungible::Mutate` currency from one account to
239/// another.
240///
241/// Suitable for runtimes that expose exactly one relevant currency (e.g. native-only runtimes
242/// without multi-asset support). For runtimes with multi-asset support, prefer
243/// [`TransferAllFungibles`] with all relevant asset IDs in `RelevantAssets`.
244pub struct TransferFungible<AccountId, Currency>(core::marker::PhantomData<(AccountId, Currency)>);
245impl<AccountId, C> TransferAllAssets<AccountId> for TransferFungible<AccountId, C>
246where
247	C: FungibleMutate<AccountId>,
248	AccountId: Eq,
249{
250	fn force_transfer_all_assets(from: &AccountId, to: &AccountId) -> Result<bool, DispatchError> {
251		let balance = C::reducible_balance(from, Preservation::Expendable, Fortitude::Polite);
252		if balance.is_zero() {
253			return Ok(false);
254		}
255		C::transfer(from, to, balance, Preservation::Expendable)?;
256		Ok(true)
257	}
258
259	#[cfg(feature = "runtime-benchmarks")]
260	fn ensure_successful(from: &AccountId) {
261		let _ = C::mint_into(from, 1_000_000u32.into());
262	}
263}
264
265/// Transfer all `RelevantAssets` of the `Fungibles` from one account to another.
266///
267/// The native asset should be the first in the list of `RelevantAssets`, otherwise the transfers
268/// of the other maybe fails.
269pub struct TransferAllFungibles<AccountId, Fungibles, RelevantAssets>(
270	core::marker::PhantomData<(AccountId, Fungibles, RelevantAssets)>,
271);
272impl<AccountId, Fungibles, RelevantAssets> TransferAllAssets<AccountId>
273	for TransferAllFungibles<AccountId, Fungibles, RelevantAssets>
274where
275	Fungibles: FungiblesMutate<AccountId> + FungiblesCreate<AccountId>,
276	RelevantAssets: Get<Vec<<Fungibles as FungiblesInspect<AccountId>>::AssetId>>,
277	AccountId: Eq + Clone,
278{
279	fn force_transfer_all_assets(from: &AccountId, to: &AccountId) -> Result<bool, DispatchError> {
280		// We iterate through all assets twice in case that the Native asset was not last in the
281		// list and ED remained because of an insufficient asset at the end of the list.
282		let assets_twice =
283			RelevantAssets::get().into_iter().chain(RelevantAssets::get().into_iter());
284
285		let mut transferred_any = false;
286		for id in assets_twice {
287			let balance = Fungibles::reducible_balance(
288				id.clone(),
289				from,
290				Preservation::Expendable,
291				Fortitude::Polite,
292			);
293			if balance.is_zero() {
294				continue;
295			}
296
297			// Ignore errors since this can only fail if the receiver does not exist.
298			if Fungibles::transfer(id, from, to, balance, Preservation::Expendable).is_ok() {
299				transferred_any = true;
300			}
301		}
302		Ok(transferred_any)
303	}
304
305	#[cfg(feature = "runtime-benchmarks")]
306	fn ensure_successful(from: &AccountId) {
307		for id in RelevantAssets::get() {
308			if !Fungibles::asset_exists(id.clone()) {
309				// For native assets, Create is a no-op; for fungible assets this ensures the
310				// asset exists before minting so the benchmark exercises real transfers.
311				Fungibles::create(id.clone(), from.clone(), true, 1u32.into())
312					.expect("asset creation should succeed in benchmarks");
313			}
314			let _ = Fungibles::mint_into(id, from, 1_000u32.into());
315		}
316	}
317}
318
319#[frame_support::pallet]
320pub mod pallet {
321	use super::*;
322
323	const STORAGE_VERSION: StorageVersion = StorageVersion::new(4);
324
325	#[pallet::pallet]
326	#[pallet::storage_version(STORAGE_VERSION)]
327	pub struct Pallet<T, I = ()>(_);
328
329	#[pallet::config]
330	pub trait Config<I: 'static = ()>:
331		frame_system::Config
332		+ pallet_treasury::Config<
333			I,
334			Currency: fungible::Inspect<Self::AccountId, Balance = BalanceOf<Self, I>>,
335		>
336	{
337		/// The amount held on deposit for placing a bounty proposal.
338		#[pallet::constant]
339		type BountyDepositBase: Get<BalanceOf<Self, I>>;
340
341		/// The delay period for which a bounty beneficiary need to wait before claim the payout.
342		#[pallet::constant]
343		type BountyDepositPayoutDelay: Get<BlockNumberFor<Self, I>>;
344
345		/// The time limit for a curator to act before a bounty expires.
346		///
347		/// The period that starts when a curator is approved, during which they must execute or
348		/// update the bounty via `extend_bounty_expiry`. If missed, the bounty expires, and the
349		/// curator may be slashed. If `BlockNumberFor::MAX`, bounties stay active indefinitely,
350		/// removing the need for `extend_bounty_expiry`.
351		#[pallet::constant]
352		type BountyUpdatePeriod: Get<BlockNumberFor<Self, I>>;
353
354		/// The curator deposit is calculated as a percentage of the curator fee.
355		///
356		/// This deposit has optional upper and lower bounds with `CuratorDepositMax` and
357		/// `CuratorDepositMin`.
358		#[pallet::constant]
359		type CuratorDepositMultiplier: Get<Permill>;
360
361		/// Maximum amount of funds that should be placed in a deposit for making a proposal.
362		#[pallet::constant]
363		type CuratorDepositMax: Get<Option<BalanceOf<Self, I>>>;
364
365		/// Minimum amount of funds that should be placed in a deposit for making a proposal.
366		#[pallet::constant]
367		type CuratorDepositMin: Get<Option<BalanceOf<Self, I>>>;
368
369		/// Minimum value for a bounty.
370		#[pallet::constant]
371		type BountyValueMinimum: Get<BalanceOf<Self, I>>;
372
373		/// The amount held on deposit per byte within the tip report reason or bounty description.
374		#[pallet::constant]
375		type DataDepositPerByte: Get<BalanceOf<Self, I>>;
376
377		/// The overarching event type.
378		#[allow(deprecated)]
379		type RuntimeEvent: From<Event<Self, I>>
380			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;
381
382		/// Maximum acceptable reason length.
383		///
384		/// Benchmarks depend on this value, be sure to update weights file when changing this value
385		#[pallet::constant]
386		type MaximumReasonLength: Get<u32>;
387
388		/// Weight information for extrinsics in this pallet.
389		type WeightInfo: WeightInfo;
390
391		/// The child bounty manager.
392		type ChildBountyManager: ChildBountyManager<BalanceOf<Self, I>>;
393
394		/// Handler for the unbalanced decrease when slashing for a rejected bounty.
395		type OnSlash: OnUnbalanced<pallet_treasury::NegativeImbalanceOf<Self, I>>;
396
397		/// Means to transfer all assets from one account to another.
398		///
399		/// This is only used for bounty closure to ensure that all assets are returned to the
400		/// treasury.
401		type TransferAllAssets: TransferAllAssets<Self::AccountId>;
402	}
403
404	#[pallet::error]
405	pub enum Error<T, I = ()> {
406		/// Proposer's balance is too low.
407		InsufficientProposersBalance,
408		/// No proposal or bounty at that index.
409		InvalidIndex,
410		/// The reason given is just too big.
411		ReasonTooBig,
412		/// The bounty status is unexpected.
413		UnexpectedStatus,
414		/// Require bounty curator.
415		RequireCurator,
416		/// Invalid bounty value.
417		InvalidValue,
418		/// Invalid bounty fee.
419		InvalidFee,
420		/// A bounty payout is pending.
421		/// To cancel the bounty, you must unassign and slash the curator.
422		PendingPayout,
423		/// The bounties cannot be claimed/closed because it's still in the countdown period.
424		Premature,
425		/// The bounty cannot be closed because it has active child bounties.
426		HasActiveChildBounty,
427		/// Too many approvals are already queued.
428		TooManyQueued,
429		/// User is not the proposer of the bounty.
430		NotProposer,
431		/// The bounty is still active and its account cannot be reclaimed.
432		BountyStillActive,
433	}
434
435	#[pallet::event]
436	#[pallet::generate_deposit(pub(super) fn deposit_event)]
437	pub enum Event<T: Config<I>, I: 'static = ()> {
438		/// New bounty proposal.
439		BountyProposed { index: BountyIndex },
440		/// A bounty proposal was rejected; funds were slashed.
441		BountyRejected { index: BountyIndex, bond: BalanceOf<T, I> },
442		/// A bounty proposal is funded and became active.
443		BountyBecameActive { index: BountyIndex },
444		/// A bounty is awarded to a beneficiary.
445		BountyAwarded { index: BountyIndex, beneficiary: T::AccountId },
446		/// A bounty is claimed by beneficiary.
447		BountyClaimed { index: BountyIndex, payout: BalanceOf<T, I>, beneficiary: T::AccountId },
448		/// A bounty is cancelled.
449		BountyCanceled { index: BountyIndex },
450		/// A bounty expiry is extended.
451		BountyExtended { index: BountyIndex },
452		/// A bounty is approved.
453		BountyApproved { index: BountyIndex },
454		/// A bounty curator is proposed.
455		CuratorProposed { bounty_id: BountyIndex, curator: T::AccountId },
456		/// A bounty curator is unassigned.
457		CuratorUnassigned { bounty_id: BountyIndex },
458		/// A bounty curator is accepted.
459		CuratorAccepted { bounty_id: BountyIndex, curator: T::AccountId },
460		/// A bounty deposit has been poked.
461		DepositPoked {
462			bounty_id: BountyIndex,
463			proposer: T::AccountId,
464			old_deposit: BalanceOf<T, I>,
465			new_deposit: BalanceOf<T, I>,
466		},
467		/// Stranded funds left in a closed bounty's account were reclaimed to the treasury.
468		BountyFundsReclaimed { bounty_id: BountyIndex },
469	}
470
471	/// Number of bounty proposals that have been made.
472	#[pallet::storage]
473	pub type BountyCount<T: Config<I>, I: 'static = ()> = StorageValue<_, BountyIndex, ValueQuery>;
474
475	/// Bounties that have been made.
476	#[pallet::storage]
477	pub type Bounties<T: Config<I>, I: 'static = ()> = StorageMap<
478		_,
479		Twox64Concat,
480		BountyIndex,
481		Bounty<T::AccountId, BalanceOf<T, I>, BlockNumberFor<T, I>>,
482	>;
483
484	/// The description of each bounty.
485	#[pallet::storage]
486	pub type BountyDescriptions<T: Config<I>, I: 'static = ()> =
487		StorageMap<_, Twox64Concat, BountyIndex, BoundedVec<u8, T::MaximumReasonLength>>;
488
489	/// Bounty indices that have been approved but not yet funded.
490	#[pallet::storage]
491	#[allow(deprecated)]
492	pub type BountyApprovals<T: Config<I>, I: 'static = ()> =
493		StorageValue<_, BoundedVec<BountyIndex, T::MaxApprovals>, ValueQuery>;
494
495	#[pallet::call]
496	impl<T: Config<I>, I: 'static> Pallet<T, I> {
497		/// Propose a new bounty.
498		///
499		/// The dispatch origin for this call must be _Signed_.
500		///
501		/// Payment: `TipReportDepositBase` will be reserved from the origin account, as well as
502		/// `DataDepositPerByte` for each byte in `reason`. It will be unreserved upon approval,
503		/// or slashed when rejected.
504		///
505		/// - `curator`: The curator account whom will manage this bounty.
506		/// - `fee`: The curator fee.
507		/// - `value`: The total payment amount of this bounty, curator fee included.
508		/// - `description`: The description of this bounty.
509		#[pallet::call_index(0)]
510		#[pallet::weight(<T as Config<I>>::WeightInfo::propose_bounty(description.len() as u32))]
511		pub fn propose_bounty(
512			origin: OriginFor<T>,
513			#[pallet::compact] value: BalanceOf<T, I>,
514			description: Vec<u8>,
515		) -> DispatchResult {
516			let proposer = ensure_signed(origin)?;
517			Self::create_bounty(proposer, description, value)?;
518			Ok(())
519		}
520
521		/// Approve a bounty proposal. At a later time, the bounty will be funded and become active
522		/// and the original deposit will be returned.
523		///
524		/// May only be called from `T::SpendOrigin`.
525		///
526		/// ## Complexity
527		/// - O(1).
528		#[pallet::call_index(1)]
529		#[pallet::weight(<T as Config<I>>::WeightInfo::approve_bounty())]
530		pub fn approve_bounty(
531			origin: OriginFor<T>,
532			#[pallet::compact] bounty_id: BountyIndex,
533		) -> DispatchResult {
534			let max_amount = T::SpendOrigin::ensure_origin(origin)?;
535			Bounties::<T, I>::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult {
536				let bounty = maybe_bounty.as_mut().ok_or(Error::<T, I>::InvalidIndex)?;
537				ensure!(
538					bounty.value <= max_amount,
539					pallet_treasury::Error::<T, I>::InsufficientPermission
540				);
541				ensure!(bounty.status == BountyStatus::Proposed, Error::<T, I>::UnexpectedStatus);
542
543				bounty.status = BountyStatus::Approved;
544
545				BountyApprovals::<T, I>::try_append(bounty_id)
546					.map_err(|()| Error::<T, I>::TooManyQueued)?;
547
548				Ok(())
549			})?;
550
551			Self::deposit_event(Event::<T, I>::BountyApproved { index: bounty_id });
552			Ok(())
553		}
554
555		/// Propose a curator to a funded bounty.
556		///
557		/// May only be called from `T::SpendOrigin`.
558		///
559		/// ## Complexity
560		/// - O(1).
561		#[pallet::call_index(2)]
562		#[pallet::weight(<T as Config<I>>::WeightInfo::propose_curator())]
563		pub fn propose_curator(
564			origin: OriginFor<T>,
565			#[pallet::compact] bounty_id: BountyIndex,
566			curator: AccountIdLookupOf<T>,
567			#[pallet::compact] fee: BalanceOf<T, I>,
568		) -> DispatchResult {
569			let max_amount = T::SpendOrigin::ensure_origin(origin)?;
570
571			let curator = T::Lookup::lookup(curator)?;
572			Bounties::<T, I>::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult {
573				let bounty = maybe_bounty.as_mut().ok_or(Error::<T, I>::InvalidIndex)?;
574				ensure!(
575					bounty.value <= max_amount,
576					pallet_treasury::Error::<T, I>::InsufficientPermission
577				);
578				match bounty.status {
579					BountyStatus::Funded => {},
580					_ => return Err(Error::<T, I>::UnexpectedStatus.into()),
581				};
582
583				ensure!(fee < bounty.value, Error::<T, I>::InvalidFee);
584
585				bounty.status = BountyStatus::CuratorProposed { curator: curator.clone() };
586				bounty.fee = fee;
587
588				Self::deposit_event(Event::<T, I>::CuratorProposed { bounty_id, curator });
589
590				Ok(())
591			})?;
592			Ok(())
593		}
594
595		/// Unassign curator from a bounty.
596		///
597		/// This function can only be called by the `RejectOrigin` a signed origin.
598		///
599		/// If this function is called by the `RejectOrigin`, we assume that the curator is
600		/// malicious or inactive. As a result, we will slash the curator when possible.
601		///
602		/// If the origin is the curator, we take this as a sign they are unable to do their job and
603		/// they willingly give up. We could slash them, but for now we allow them to recover their
604		/// deposit and exit without issue. (We may want to change this if it is abused.)
605		///
606		/// Finally, the origin can be anyone if and only if the curator is "inactive". This allows
607		/// anyone in the community to call out that a curator is not doing their due diligence, and
608		/// we should pick a new curator. In this case the curator should also be slashed.
609		///
610		/// ## Complexity
611		/// - O(1).
612		#[pallet::call_index(3)]
613		#[pallet::weight(<T as Config<I>>::WeightInfo::unassign_curator())]
614		pub fn unassign_curator(
615			origin: OriginFor<T>,
616			#[pallet::compact] bounty_id: BountyIndex,
617		) -> DispatchResult {
618			let maybe_sender = ensure_signed(origin.clone())
619				.map(Some)
620				.or_else(|_| T::RejectOrigin::ensure_origin(origin).map(|_| None))?;
621
622			Bounties::<T, I>::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult {
623				let bounty = maybe_bounty.as_mut().ok_or(Error::<T, I>::InvalidIndex)?;
624
625				let slash_curator =
626					|curator: &T::AccountId, curator_deposit: &mut BalanceOf<T, I>| {
627						let imbalance = T::Currency::slash_reserved(curator, *curator_deposit).0;
628						T::OnSlash::on_unbalanced(imbalance);
629						*curator_deposit = Zero::zero();
630					};
631
632				match bounty.status {
633					BountyStatus::Proposed | BountyStatus::Approved | BountyStatus::Funded => {
634						// No curator to unassign at this point.
635						return Err(Error::<T, I>::UnexpectedStatus.into());
636					},
637					BountyStatus::ApprovedWithCurator { ref curator } => {
638						// Bounty not yet funded, but bounty was approved with curator.
639						// `RejectOrigin` or curator himself can unassign from this bounty.
640						ensure!(maybe_sender.map_or(true, |sender| sender == *curator), BadOrigin);
641						// This state can only be while the bounty is not yet funded so we return
642						// bounty to the `Approved` state without curator
643						bounty.status = BountyStatus::Approved;
644						return Ok(());
645					},
646					BountyStatus::CuratorProposed { ref curator } => {
647						// A curator has been proposed, but not accepted yet.
648						// Either `RejectOrigin` or the proposed curator can unassign the curator.
649						ensure!(maybe_sender.map_or(true, |sender| sender == *curator), BadOrigin);
650					},
651					BountyStatus::Active { ref curator, ref update_due } => {
652						// The bounty is active.
653						match maybe_sender {
654							// If the `RejectOrigin` is calling this function, slash the curator.
655							None => {
656								slash_curator(curator, &mut bounty.curator_deposit);
657								// Continue to change bounty status below...
658							},
659							Some(sender) => {
660								// If the sender is not the curator, and the curator is inactive,
661								// slash the curator.
662								if sender != *curator {
663									let block_number = Self::treasury_block_number();
664									if *update_due < block_number {
665										slash_curator(curator, &mut bounty.curator_deposit);
666									// Continue to change bounty status below...
667									} else {
668										// Curator has more time to give an update.
669										return Err(Error::<T, I>::Premature.into());
670									}
671								} else {
672									// Else this is the curator, willingly giving up their role.
673									// Give back their deposit.
674									let err_amount =
675										T::Currency::unreserve(curator, bounty.curator_deposit);
676									debug_assert!(err_amount.is_zero());
677									bounty.curator_deposit = Zero::zero();
678									// Continue to change bounty status below...
679								}
680							},
681						}
682					},
683					BountyStatus::PendingPayout { ref curator, .. } => {
684						// The bounty is pending payout, so only council can unassign a curator.
685						// By doing so, they are claiming the curator is acting maliciously, so
686						// we slash the curator.
687						ensure!(maybe_sender.is_none(), BadOrigin);
688						slash_curator(curator, &mut bounty.curator_deposit);
689						// Continue to change bounty status below...
690					},
691				};
692
693				bounty.status = BountyStatus::Funded;
694				Ok(())
695			})?;
696
697			Self::deposit_event(Event::<T, I>::CuratorUnassigned { bounty_id });
698			Ok(())
699		}
700
701		/// Accept the curator role for a bounty.
702		/// A deposit will be reserved from curator and refund upon successful payout.
703		///
704		/// May only be called from the curator.
705		///
706		/// ## Complexity
707		/// - O(1).
708		#[pallet::call_index(4)]
709		#[pallet::weight(<T as Config<I>>::WeightInfo::accept_curator())]
710		pub fn accept_curator(
711			origin: OriginFor<T>,
712			#[pallet::compact] bounty_id: BountyIndex,
713		) -> DispatchResult {
714			let signer = ensure_signed(origin)?;
715
716			Bounties::<T, I>::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult {
717				let bounty = maybe_bounty.as_mut().ok_or(Error::<T, I>::InvalidIndex)?;
718
719				match bounty.status {
720					BountyStatus::CuratorProposed { ref curator } => {
721						ensure!(signer == *curator, Error::<T, I>::RequireCurator);
722
723						let deposit = Self::calculate_curator_deposit(&bounty.fee);
724						T::Currency::reserve(curator, deposit)?;
725						bounty.curator_deposit = deposit;
726
727						let update_due = Self::treasury_block_number()
728							.saturating_add(T::BountyUpdatePeriod::get());
729						bounty.status =
730							BountyStatus::Active { curator: curator.clone(), update_due };
731
732						Self::deposit_event(Event::<T, I>::CuratorAccepted {
733							bounty_id,
734							curator: signer,
735						});
736						Ok(())
737					},
738					_ => Err(Error::<T, I>::UnexpectedStatus.into()),
739				}
740			})?;
741			Ok(())
742		}
743
744		/// Award bounty to a beneficiary account. The beneficiary will be able to claim the funds
745		/// after a delay.
746		///
747		/// The dispatch origin for this call must be the curator of this bounty.
748		///
749		/// - `bounty_id`: Bounty ID to award.
750		/// - `beneficiary`: The beneficiary account whom will receive the payout.
751		///
752		/// ## Complexity
753		/// - O(1).
754		#[pallet::call_index(5)]
755		#[pallet::weight(<T as Config<I>>::WeightInfo::award_bounty())]
756		pub fn award_bounty(
757			origin: OriginFor<T>,
758			#[pallet::compact] bounty_id: BountyIndex,
759			beneficiary: AccountIdLookupOf<T>,
760		) -> DispatchResult {
761			let signer = ensure_signed(origin)?;
762			let beneficiary = T::Lookup::lookup(beneficiary)?;
763
764			Bounties::<T, I>::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult {
765				let bounty = maybe_bounty.as_mut().ok_or(Error::<T, I>::InvalidIndex)?;
766
767				// Ensure no active child bounties before processing the call.
768				ensure!(
769					T::ChildBountyManager::child_bounties_count(bounty_id) == 0,
770					Error::<T, I>::HasActiveChildBounty
771				);
772
773				match &bounty.status {
774					BountyStatus::Active { curator, .. } => {
775						ensure!(signer == *curator, Error::<T, I>::RequireCurator);
776					},
777					_ => return Err(Error::<T, I>::UnexpectedStatus.into()),
778				}
779				bounty.status = BountyStatus::PendingPayout {
780					curator: signer,
781					beneficiary: beneficiary.clone(),
782					unlock_at: Self::treasury_block_number() + T::BountyDepositPayoutDelay::get(),
783				};
784
785				Ok(())
786			})?;
787
788			Self::deposit_event(Event::<T, I>::BountyAwarded { index: bounty_id, beneficiary });
789			Ok(())
790		}
791
792		/// Claim the payout from an awarded bounty after payout delay.
793		///
794		/// The dispatch origin for this call must be the beneficiary of this bounty.
795		///
796		/// - `bounty_id`: Bounty ID to claim.
797		///
798		/// ## Complexity
799		/// - O(1).
800		#[pallet::call_index(6)]
801		#[pallet::weight(<T as Config<I>>::WeightInfo::claim_bounty())]
802		pub fn claim_bounty(
803			origin: OriginFor<T>,
804			#[pallet::compact] bounty_id: BountyIndex,
805		) -> DispatchResult {
806			ensure_signed(origin)?; // anyone can trigger claim
807
808			Bounties::<T, I>::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult {
809				let bounty = maybe_bounty.take().ok_or(Error::<T, I>::InvalidIndex)?;
810				if let BountyStatus::PendingPayout { curator, beneficiary, unlock_at } =
811					bounty.status
812				{
813					ensure!(Self::treasury_block_number() >= unlock_at, Error::<T, I>::Premature);
814					let bounty_account = Self::bounty_account_id(bounty_id);
815					let balance = Self::spendable_balance(&bounty_account);
816					let fee = bounty.fee.min(balance); // just to be safe
817					let payout = balance.saturating_sub(fee);
818					let err_amount = T::Currency::unreserve(&curator, bounty.curator_deposit);
819					debug_assert!(err_amount.is_zero());
820
821					// Get total child bounties curator fees, and subtract it from the parent
822					// curator fee (the fee in present referenced bounty, `self`).
823					let children_fee = T::ChildBountyManager::children_curator_fees(bounty_id);
824					debug_assert!(children_fee <= fee);
825
826					let final_fee = fee.saturating_sub(children_fee);
827					T::Currency::transfer(&bounty_account, &curator, final_fee, AllowDeath)?;
828					T::Currency::transfer(&bounty_account, &beneficiary, payout, AllowDeath)?;
829
830					*maybe_bounty = None;
831
832					BountyDescriptions::<T, I>::remove(bounty_id);
833					T::ChildBountyManager::bounty_removed(bounty_id);
834
835					Self::deposit_event(Event::<T, I>::BountyClaimed {
836						index: bounty_id,
837						payout,
838						beneficiary,
839					});
840					Ok(())
841				} else {
842					Err(Error::<T, I>::UnexpectedStatus.into())
843				}
844			})?;
845			Ok(())
846		}
847
848		/// Cancel a proposed or active bounty. All the funds will be sent to treasury and
849		/// the curator deposit will be unreserved if possible.
850		///
851		/// Only `T::RejectOrigin` is able to cancel a bounty.
852		///
853		/// - `bounty_id`: Bounty ID to cancel.
854		///
855		/// ## Complexity
856		/// - O(1).
857		#[pallet::call_index(7)]
858		#[pallet::weight(<T as Config<I>>::WeightInfo::close_bounty_proposed()
859			.max(<T as Config<I>>::WeightInfo::close_bounty_active()))]
860		pub fn close_bounty(
861			origin: OriginFor<T>,
862			#[pallet::compact] bounty_id: BountyIndex,
863		) -> DispatchResultWithPostInfo {
864			T::RejectOrigin::ensure_origin(origin)?;
865
866			Bounties::<T, I>::try_mutate_exists(
867				bounty_id,
868				|maybe_bounty| -> DispatchResultWithPostInfo {
869					let bounty = maybe_bounty.as_ref().ok_or(Error::<T, I>::InvalidIndex)?;
870
871					// Ensure no active child bounties before processing the call.
872					ensure!(
873						T::ChildBountyManager::child_bounties_count(bounty_id) == 0,
874						Error::<T, I>::HasActiveChildBounty
875					);
876
877					match &bounty.status {
878						BountyStatus::Proposed => {
879							// The reject origin would like to cancel a proposed bounty.
880							BountyDescriptions::<T, I>::remove(bounty_id);
881							let value = bounty.bond;
882							let imbalance = T::Currency::slash_reserved(&bounty.proposer, value).0;
883							T::OnSlash::on_unbalanced(imbalance);
884							*maybe_bounty = None;
885
886							Self::deposit_event(Event::<T, I>::BountyRejected {
887								index: bounty_id,
888								bond: value,
889							});
890							// Return early, nothing else to do.
891							return Ok(
892								Some(<T as Config<I>>::WeightInfo::close_bounty_proposed()).into()
893							);
894						},
895						BountyStatus::Approved | BountyStatus::ApprovedWithCurator { .. } => {
896							// For weight reasons, we don't allow a council to cancel in this phase.
897							// We ask for them to wait until it is funded before they can cancel.
898							return Err(Error::<T, I>::UnexpectedStatus.into());
899						},
900						BountyStatus::Funded | BountyStatus::CuratorProposed { .. } => {
901							// Nothing extra to do besides the removal of the bounty below.
902						},
903						BountyStatus::Active { curator, .. } => {
904							// Cancelled by council, refund deposit of the working curator.
905							let err_amount =
906								T::Currency::unreserve(curator, bounty.curator_deposit);
907							debug_assert!(err_amount.is_zero());
908							// Then execute removal of the bounty below.
909						},
910						BountyStatus::PendingPayout { .. } => {
911							// Bounty is already pending payout. If council wants to cancel
912							// this bounty, it should mean the curator was acting maliciously.
913							// So the council should first unassign the curator, slashing their
914							// deposit.
915							return Err(Error::<T, I>::PendingPayout.into());
916						},
917					}
918
919					let bounty_account = Self::bounty_account_id(bounty_id);
920
921					BountyDescriptions::<T, I>::remove(bounty_id);
922
923					T::TransferAllAssets::force_transfer_all_assets(
924						&bounty_account,
925						&Self::account_id(),
926					)?;
927
928					*maybe_bounty = None;
929					T::ChildBountyManager::bounty_removed(bounty_id);
930
931					Self::deposit_event(Event::<T, I>::BountyCanceled { index: bounty_id });
932					Ok(Some(<T as Config<I>>::WeightInfo::close_bounty_active()).into())
933				},
934			)
935		}
936
937		/// Extend the expiry time of an active bounty.
938		///
939		/// The dispatch origin for this call must be the curator of this bounty.
940		///
941		/// - `bounty_id`: Bounty ID to extend.
942		/// - `remark`: additional information.
943		///
944		/// ## Complexity
945		/// - O(1).
946		#[pallet::call_index(8)]
947		#[pallet::weight(<T as Config<I>>::WeightInfo::extend_bounty_expiry())]
948		pub fn extend_bounty_expiry(
949			origin: OriginFor<T>,
950			#[pallet::compact] bounty_id: BountyIndex,
951			_remark: Vec<u8>,
952		) -> DispatchResult {
953			let signer = ensure_signed(origin)?;
954
955			Bounties::<T, I>::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult {
956				let bounty = maybe_bounty.as_mut().ok_or(Error::<T, I>::InvalidIndex)?;
957
958				match bounty.status {
959					BountyStatus::Active { ref curator, ref mut update_due } => {
960						ensure!(*curator == signer, Error::<T, I>::RequireCurator);
961						*update_due = Self::treasury_block_number()
962							.saturating_add(T::BountyUpdatePeriod::get())
963							.max(*update_due);
964					},
965					_ => return Err(Error::<T, I>::UnexpectedStatus.into()),
966				}
967
968				Ok(())
969			})?;
970
971			Self::deposit_event(Event::<T, I>::BountyExtended { index: bounty_id });
972			Ok(())
973		}
974
975		/// Approve bountry and propose a curator simultaneously.
976		/// This call is a shortcut to calling `approve_bounty` and `propose_curator` separately.
977		///
978		/// May only be called from `T::SpendOrigin`.
979		///
980		/// - `bounty_id`: Bounty ID to approve.
981		/// - `curator`: The curator account whom will manage this bounty.
982		/// - `fee`: The curator fee.
983		///
984		/// ## Complexity
985		/// - O(1).
986		#[pallet::call_index(9)]
987		#[pallet::weight(<T as Config<I>>::WeightInfo::approve_bounty_with_curator())]
988		pub fn approve_bounty_with_curator(
989			origin: OriginFor<T>,
990			#[pallet::compact] bounty_id: BountyIndex,
991			curator: AccountIdLookupOf<T>,
992			#[pallet::compact] fee: BalanceOf<T, I>,
993		) -> DispatchResult {
994			let max_amount = T::SpendOrigin::ensure_origin(origin)?;
995			let curator = T::Lookup::lookup(curator)?;
996			Bounties::<T, I>::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult {
997				// approve bounty
998				let bounty = maybe_bounty.as_mut().ok_or(Error::<T, I>::InvalidIndex)?;
999				ensure!(
1000					bounty.value <= max_amount,
1001					pallet_treasury::Error::<T, I>::InsufficientPermission
1002				);
1003				ensure!(bounty.status == BountyStatus::Proposed, Error::<T, I>::UnexpectedStatus);
1004				ensure!(fee < bounty.value, Error::<T, I>::InvalidFee);
1005
1006				BountyApprovals::<T, I>::try_append(bounty_id)
1007					.map_err(|()| Error::<T, I>::TooManyQueued)?;
1008
1009				bounty.status = BountyStatus::ApprovedWithCurator { curator: curator.clone() };
1010				bounty.fee = fee;
1011
1012				Ok(())
1013			})?;
1014
1015			Self::deposit_event(Event::<T, I>::BountyApproved { index: bounty_id });
1016			Self::deposit_event(Event::<T, I>::CuratorProposed { bounty_id, curator });
1017
1018			Ok(())
1019		}
1020
1021		/// Poke the deposit reserved for creating a bounty proposal.
1022		///
1023		/// This can be used by accounts to update their reserved amount.
1024		///
1025		/// The dispatch origin for this call must be _Signed_.
1026		///
1027		/// Parameters:
1028		/// - `bounty_id`: The bounty id for which to adjust the deposit.
1029		///
1030		/// If the deposit is updated, the difference will be reserved/unreserved from the
1031		/// proposer's account.
1032		///
1033		/// The transaction is made free if the deposit is updated and paid otherwise.
1034		///
1035		/// Emits `DepositPoked` if the deposit is updated.
1036		#[pallet::call_index(10)]
1037		#[pallet::weight(<T as Config<I>>::WeightInfo::poke_deposit())]
1038		pub fn poke_deposit(
1039			origin: OriginFor<T>,
1040			#[pallet::compact] bounty_id: BountyIndex,
1041		) -> DispatchResultWithPostInfo {
1042			ensure_signed(origin)?;
1043
1044			let deposit_updated = Self::poke_bounty_deposit(bounty_id)?;
1045
1046			Ok(if deposit_updated { Pays::No } else { Pays::Yes }.into())
1047		}
1048
1049		/// Reclaim funds stranded in a closed bounty's account back to the treasury.
1050		///
1051		/// Permissionless. Moves all remaining assets from a closed bounty's account back to the
1052		/// treasury in a single call. Which assets are swept depends on the `TransferAllAssets`
1053		/// configuration.
1054		///
1055		/// The call is free if funds were reclaimed and paid otherwise, so no-op calls cannot be
1056		/// used to grief the network. Emits `BountyFundsReclaimed` on success.
1057		///
1058		/// ## Complexity
1059		/// - O(A) where A is the number of relevant assets configured in `TransferAllAssets`.
1060		#[pallet::call_index(11)]
1061		#[pallet::weight(<T as Config<I>>::WeightInfo::reclaim_bounty_funds())]
1062		pub fn reclaim_bounty_funds(
1063			origin: OriginFor<T>,
1064			#[pallet::compact] bounty_id: BountyIndex,
1065		) -> DispatchResultWithPostInfo {
1066			ensure_signed(origin)?;
1067
1068			// A live bounty still manages its account, so leave it untouched.
1069			ensure!(!Bounties::<T, I>::contains_key(bounty_id), Error::<T, I>::BountyStillActive);
1070
1071			debug_assert!(
1072				T::ChildBountyManager::child_bounties_count(bounty_id) == 0,
1073				"child bounties should not exist for a closed bounty"
1074			);
1075
1076			let bounty_account = Self::bounty_account_id(bounty_id);
1077			let treasury_account = Self::account_id();
1078
1079			let transferred = T::TransferAllAssets::force_transfer_all_assets(
1080				&bounty_account,
1081				&treasury_account,
1082			)?;
1083
1084			// Free only if something moved, otherwise paid to prevent griefing.
1085			if !transferred {
1086				return Ok(Pays::Yes.into());
1087			}
1088
1089			Self::deposit_event(Event::<T, I>::BountyFundsReclaimed { bounty_id });
1090
1091			Ok(Pays::No.into())
1092		}
1093	}
1094
1095	#[pallet::hooks]
1096	impl<T: Config<I>, I: 'static> Hooks<SystemBlockNumberFor<T>> for Pallet<T, I> {
1097		#[cfg(feature = "try-runtime")]
1098		fn try_state(_n: SystemBlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
1099			Self::do_try_state()
1100		}
1101	}
1102}
1103
1104#[cfg(any(feature = "try-runtime", test))]
1105impl<T: Config<I>, I: 'static> Pallet<T, I> {
1106	/// Ensure the correctness of the state of this pallet.
1107	///
1108	/// This should be valid before or after each state transition of this pallet.
1109	pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
1110		Self::try_state_bounties_count()?;
1111
1112		Ok(())
1113	}
1114
1115	/// # Invariants
1116	///
1117	/// * `BountyCount` should be greater or equals to the length of the number of items in
1118	///   `Bounties`.
1119	/// * `BountyCount` should be greater or equals to the length of the number of items in
1120	///   `BountyDescriptions`.
1121	/// * Number of items in `Bounties` should be the same as `BountyDescriptions` length.
1122	fn try_state_bounties_count() -> Result<(), sp_runtime::TryRuntimeError> {
1123		let bounties_length = Bounties::<T, I>::iter().count() as u32;
1124
1125		ensure!(
1126			<BountyCount<T, I>>::get() >= bounties_length,
1127			"`BountyCount` must be grater or equals the number of `Bounties` in storage"
1128		);
1129
1130		let bounties_description_length = BountyDescriptions::<T, I>::iter().count() as u32;
1131		ensure!(
1132			<BountyCount<T, I>>::get() >= bounties_description_length,
1133			"`BountyCount` must be grater or equals the number of `BountiesDescriptions` in storage."
1134		);
1135
1136		ensure!(
1137				bounties_length == bounties_description_length,
1138				"Number of `Bounties` in storage must be the same as the Number of `BountiesDescription` in storage."
1139		);
1140		Ok(())
1141	}
1142}
1143
1144impl<T: Config<I>, I: 'static> Pallet<T, I> {
1145	/// Get the block number used in the treasury pallet.
1146	///
1147	/// It may be configured to use the relay chain block number on a parachain.
1148	pub fn treasury_block_number() -> BlockNumberFor<T, I> {
1149		<T as pallet_treasury::Config<I>>::BlockNumberProvider::current_block_number()
1150	}
1151
1152	/// Calculate the deposit required for a curator.
1153	pub fn calculate_curator_deposit(fee: &BalanceOf<T, I>) -> BalanceOf<T, I> {
1154		let mut deposit = T::CuratorDepositMultiplier::get() * *fee;
1155
1156		if let Some(max_deposit) = T::CuratorDepositMax::get() {
1157			deposit = deposit.min(max_deposit)
1158		}
1159
1160		if let Some(min_deposit) = T::CuratorDepositMin::get() {
1161			deposit = deposit.max(min_deposit)
1162		}
1163
1164		deposit
1165	}
1166
1167	/// The account ID of the treasury pot.
1168	///
1169	/// This actually does computation. If you need to keep using it, then make sure you cache the
1170	/// value and only call this once.
1171	pub fn account_id() -> T::AccountId {
1172		T::PalletId::get().into_account_truncating()
1173	}
1174
1175	/// The account ID of a bounty account
1176	pub fn bounty_account_id(id: BountyIndex) -> T::AccountId {
1177		// only use two byte prefix to support 16 byte account id (used by test)
1178		// "modl" ++ "py/trsry" ++ "bt" is 14 bytes, and two bytes remaining for bounty index
1179		T::PalletId::get().into_sub_account_truncating(("bt", id))
1180	}
1181
1182	/// The balance `who` can transfer. Anyone can lock funds in a bounty account with a vested
1183	/// transfer, so payouts must not count them.
1184	pub fn spendable_balance(who: &T::AccountId) -> BalanceOf<T, I> {
1185		<T::Currency as fungible::Inspect<_>>::reducible_balance(
1186			who,
1187			Preservation::Expendable,
1188			Fortitude::Polite,
1189		)
1190	}
1191
1192	fn create_bounty(
1193		proposer: T::AccountId,
1194		description: Vec<u8>,
1195		value: BalanceOf<T, I>,
1196	) -> DispatchResult {
1197		let bounded_description: BoundedVec<_, _> =
1198			description.try_into().map_err(|_| Error::<T, I>::ReasonTooBig)?;
1199		ensure!(value >= T::BountyValueMinimum::get(), Error::<T, I>::InvalidValue);
1200
1201		let index = BountyCount::<T, I>::get();
1202
1203		// reserve deposit for new bounty
1204		let bond = Self::calculate_bounty_deposit(&bounded_description);
1205		T::Currency::reserve(&proposer, bond)
1206			.map_err(|_| Error::<T, I>::InsufficientProposersBalance)?;
1207
1208		BountyCount::<T, I>::put(index + 1);
1209
1210		let bounty = Bounty {
1211			proposer,
1212			value,
1213			fee: 0u32.into(),
1214			curator_deposit: 0u32.into(),
1215			bond,
1216			status: BountyStatus::Proposed,
1217		};
1218
1219		Bounties::<T, I>::insert(index, &bounty);
1220		BountyDescriptions::<T, I>::insert(index, bounded_description);
1221
1222		Self::deposit_event(Event::<T, I>::BountyProposed { index });
1223
1224		Ok(())
1225	}
1226
1227	/// Helper function to calculate the bounty storage deposit.
1228	fn calculate_bounty_deposit(
1229		description: &BoundedVec<u8, T::MaximumReasonLength>,
1230	) -> BalanceOf<T, I> {
1231		T::BountyDepositBase::get().saturating_add(
1232			T::DataDepositPerByte::get().saturating_mul((description.len() as u32).into()),
1233		)
1234	}
1235
1236	/// Helper function to poke the deposit reserved for proposing a bounty.
1237	///
1238	/// Returns true if the deposit was updated and false otherwise.
1239	fn poke_bounty_deposit(bounty_id: BountyIndex) -> Result<bool, DispatchError> {
1240		let mut bounty = Bounties::<T, I>::get(bounty_id).ok_or(Error::<T, I>::InvalidIndex)?;
1241		let bounty_description =
1242			BountyDescriptions::<T, I>::get(bounty_id).ok_or(Error::<T, I>::InvalidIndex)?;
1243		// ensure that the bounty status is proposed.
1244		ensure!(bounty.status == BountyStatus::Proposed, Error::<T, I>::UnexpectedStatus);
1245
1246		let new_bond = Self::calculate_bounty_deposit(&bounty_description);
1247		let old_bond = bounty.bond;
1248		if new_bond == old_bond {
1249			return Ok(false);
1250		}
1251		if new_bond > old_bond {
1252			let extra = new_bond.saturating_sub(old_bond);
1253			T::Currency::reserve(&bounty.proposer, extra)?;
1254		} else {
1255			let excess = old_bond.saturating_sub(new_bond);
1256			let remaining_unreserved = T::Currency::unreserve(&bounty.proposer, excess);
1257			if !remaining_unreserved.is_zero() {
1258				defensive!(
1259					"Failed to unreserve full amount. (Requested, Actual)",
1260					(excess, excess.saturating_sub(remaining_unreserved))
1261				);
1262			}
1263		}
1264		bounty.bond = new_bond;
1265		Bounties::<T, I>::insert(bounty_id, &bounty);
1266
1267		Self::deposit_event(Event::<T, I>::DepositPoked {
1268			bounty_id,
1269			proposer: bounty.proposer,
1270			old_deposit: old_bond,
1271			new_deposit: new_bond,
1272		});
1273
1274		Ok(true)
1275	}
1276}
1277
1278impl<T: Config<I>, I: 'static> pallet_treasury::SpendFunds<T, I> for Pallet<T, I> {
1279	fn spend_funds(
1280		budget_remaining: &mut BalanceOf<T, I>,
1281		imbalance: &mut PositiveImbalanceOf<T, I>,
1282		total_weight: &mut Weight,
1283		missed_any: &mut bool,
1284	) {
1285		let bounties_len = BountyApprovals::<T, I>::mutate(|v| {
1286			let bounties_approval_len = v.len() as u32;
1287			v.retain(|&index| {
1288				Bounties::<T, I>::mutate(index, |bounty| {
1289					// Should always be true, but shouldn't panic if false or we're screwed.
1290					if let Some(bounty) = bounty {
1291						if bounty.value <= *budget_remaining {
1292							*budget_remaining -= bounty.value;
1293
1294							// jump through the funded phase if we're already approved with curator
1295							if let BountyStatus::ApprovedWithCurator { curator } = &bounty.status {
1296								bounty.status =
1297									BountyStatus::CuratorProposed { curator: curator.clone() };
1298							} else {
1299								bounty.status = BountyStatus::Funded;
1300							}
1301
1302							// return their deposit.
1303							let err_amount = T::Currency::unreserve(&bounty.proposer, bounty.bond);
1304							debug_assert!(err_amount.is_zero());
1305
1306							// fund the bounty account
1307							imbalance.subsume(T::Currency::deposit_creating(
1308								&Self::bounty_account_id(index),
1309								bounty.value,
1310							));
1311
1312							Self::deposit_event(Event::<T, I>::BountyBecameActive { index });
1313							false
1314						} else {
1315							*missed_any = true;
1316							true
1317						}
1318					} else {
1319						false
1320					}
1321				})
1322			});
1323			bounties_approval_len
1324		});
1325
1326		*total_weight += <T as pallet::Config<I>>::WeightInfo::spend_funds(bounties_len);
1327	}
1328}
1329
1330// Default impl for when ChildBounties is not being used in the runtime.
1331impl<Balance: Zero> ChildBountyManager<Balance> for () {
1332	fn child_bounties_count(_bounty_id: BountyIndex) -> BountyIndex {
1333		Default::default()
1334	}
1335
1336	fn children_curator_fees(_bounty_id: BountyIndex) -> Balance {
1337		Zero::zero()
1338	}
1339
1340	fn bounty_removed(_bounty_id: BountyIndex) {}
1341}