1#![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
129pub 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#[derive(
139 Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen,
140)]
141pub struct Bounty<AccountId, Balance, BlockNumber> {
142 pub proposer: AccountId,
144 pub value: Balance,
146 pub fee: Balance,
148 pub curator_deposit: Balance,
150 bond: Balance,
152 status: BountyStatus<AccountId, BlockNumber>,
154}
155
156impl<AccountId: PartialEq + Clone + Ord, Balance, BlockNumber: Clone>
157 Bounty<AccountId, Balance, BlockNumber>
158{
159 pub fn get_status(&self) -> BountyStatus<AccountId, BlockNumber> {
161 self.status.clone()
162 }
163}
164
165#[derive(
167 Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen,
168)]
169pub enum BountyStatus<AccountId, BlockNumber> {
170 Proposed,
172 Approved,
174 Funded,
176 CuratorProposed {
178 curator: AccountId,
180 },
181 Active {
183 curator: AccountId,
185 update_due: BlockNumber,
187 },
188 PendingPayout {
190 curator: AccountId,
192 beneficiary: AccountId,
194 unlock_at: BlockNumber,
196 },
197 ApprovedWithCurator {
199 curator: AccountId,
201 },
202}
203
204pub trait ChildBountyManager<Balance> {
206 fn child_bounties_count(bounty_id: BountyIndex) -> BountyIndex;
208
209 fn children_curator_fees(bounty_id: BountyIndex) -> Balance;
211
212 fn bounty_removed(bounty_id: BountyIndex);
214}
215
216pub trait TransferAllAssets<AccountId> {
218 fn force_transfer_all_assets(from: &AccountId, to: &AccountId) -> Result<bool, DispatchError>;
223
224 #[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
238pub 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
265pub 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 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 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 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 #[pallet::constant]
339 type BountyDepositBase: Get<BalanceOf<Self, I>>;
340
341 #[pallet::constant]
343 type BountyDepositPayoutDelay: Get<BlockNumberFor<Self, I>>;
344
345 #[pallet::constant]
352 type BountyUpdatePeriod: Get<BlockNumberFor<Self, I>>;
353
354 #[pallet::constant]
359 type CuratorDepositMultiplier: Get<Permill>;
360
361 #[pallet::constant]
363 type CuratorDepositMax: Get<Option<BalanceOf<Self, I>>>;
364
365 #[pallet::constant]
367 type CuratorDepositMin: Get<Option<BalanceOf<Self, I>>>;
368
369 #[pallet::constant]
371 type BountyValueMinimum: Get<BalanceOf<Self, I>>;
372
373 #[pallet::constant]
375 type DataDepositPerByte: Get<BalanceOf<Self, I>>;
376
377 #[allow(deprecated)]
379 type RuntimeEvent: From<Event<Self, I>>
380 + IsType<<Self as frame_system::Config>::RuntimeEvent>;
381
382 #[pallet::constant]
386 type MaximumReasonLength: Get<u32>;
387
388 type WeightInfo: WeightInfo;
390
391 type ChildBountyManager: ChildBountyManager<BalanceOf<Self, I>>;
393
394 type OnSlash: OnUnbalanced<pallet_treasury::NegativeImbalanceOf<Self, I>>;
396
397 type TransferAllAssets: TransferAllAssets<Self::AccountId>;
402 }
403
404 #[pallet::error]
405 pub enum Error<T, I = ()> {
406 InsufficientProposersBalance,
408 InvalidIndex,
410 ReasonTooBig,
412 UnexpectedStatus,
414 RequireCurator,
416 InvalidValue,
418 InvalidFee,
420 PendingPayout,
423 Premature,
425 HasActiveChildBounty,
427 TooManyQueued,
429 NotProposer,
431 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 BountyProposed { index: BountyIndex },
440 BountyRejected { index: BountyIndex, bond: BalanceOf<T, I> },
442 BountyBecameActive { index: BountyIndex },
444 BountyAwarded { index: BountyIndex, beneficiary: T::AccountId },
446 BountyClaimed { index: BountyIndex, payout: BalanceOf<T, I>, beneficiary: T::AccountId },
448 BountyCanceled { index: BountyIndex },
450 BountyExtended { index: BountyIndex },
452 BountyApproved { index: BountyIndex },
454 CuratorProposed { bounty_id: BountyIndex, curator: T::AccountId },
456 CuratorUnassigned { bounty_id: BountyIndex },
458 CuratorAccepted { bounty_id: BountyIndex, curator: T::AccountId },
460 DepositPoked {
462 bounty_id: BountyIndex,
463 proposer: T::AccountId,
464 old_deposit: BalanceOf<T, I>,
465 new_deposit: BalanceOf<T, I>,
466 },
467 BountyFundsReclaimed { bounty_id: BountyIndex },
469 }
470
471 #[pallet::storage]
473 pub type BountyCount<T: Config<I>, I: 'static = ()> = StorageValue<_, BountyIndex, ValueQuery>;
474
475 #[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 #[pallet::storage]
486 pub type BountyDescriptions<T: Config<I>, I: 'static = ()> =
487 StorageMap<_, Twox64Concat, BountyIndex, BoundedVec<u8, T::MaximumReasonLength>>;
488
489 #[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 #[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 #[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 #[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 #[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 return Err(Error::<T, I>::UnexpectedStatus.into());
636 },
637 BountyStatus::ApprovedWithCurator { ref curator } => {
638 ensure!(maybe_sender.map_or(true, |sender| sender == *curator), BadOrigin);
641 bounty.status = BountyStatus::Approved;
644 return Ok(());
645 },
646 BountyStatus::CuratorProposed { ref curator } => {
647 ensure!(maybe_sender.map_or(true, |sender| sender == *curator), BadOrigin);
650 },
651 BountyStatus::Active { ref curator, ref update_due } => {
652 match maybe_sender {
654 None => {
656 slash_curator(curator, &mut bounty.curator_deposit);
657 },
659 Some(sender) => {
660 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 } else {
668 return Err(Error::<T, I>::Premature.into());
670 }
671 } else {
672 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 }
680 },
681 }
682 },
683 BountyStatus::PendingPayout { ref curator, .. } => {
684 ensure!(maybe_sender.is_none(), BadOrigin);
688 slash_curator(curator, &mut bounty.curator_deposit);
689 },
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 #[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 #[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!(
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 #[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)?; 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); 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 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 #[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!(
873 T::ChildBountyManager::child_bounties_count(bounty_id) == 0,
874 Error::<T, I>::HasActiveChildBounty
875 );
876
877 match &bounty.status {
878 BountyStatus::Proposed => {
879 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 Ok(
892 Some(<T as Config<I>>::WeightInfo::close_bounty_proposed()).into()
893 );
894 },
895 BountyStatus::Approved | BountyStatus::ApprovedWithCurator { .. } => {
896 return Err(Error::<T, I>::UnexpectedStatus.into());
899 },
900 BountyStatus::Funded | BountyStatus::CuratorProposed { .. } => {
901 },
903 BountyStatus::Active { curator, .. } => {
904 let err_amount =
906 T::Currency::unreserve(curator, bounty.curator_deposit);
907 debug_assert!(err_amount.is_zero());
908 },
910 BountyStatus::PendingPayout { .. } => {
911 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 #[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 #[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 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 #[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 #[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 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 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 pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
1110 Self::try_state_bounties_count()?;
1111
1112 Ok(())
1113 }
1114
1115 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 pub fn treasury_block_number() -> BlockNumberFor<T, I> {
1149 <T as pallet_treasury::Config<I>>::BlockNumberProvider::current_block_number()
1150 }
1151
1152 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 pub fn account_id() -> T::AccountId {
1172 T::PalletId::get().into_account_truncating()
1173 }
1174
1175 pub fn bounty_account_id(id: BountyIndex) -> T::AccountId {
1177 T::PalletId::get().into_sub_account_truncating(("bt", id))
1180 }
1181
1182 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 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 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 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!(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 if let Some(bounty) = bounty {
1291 if bounty.value <= *budget_remaining {
1292 *budget_remaining -= bounty.value;
1293
1294 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 let err_amount = T::Currency::unreserve(&bounty.proposer, bounty.bond);
1304 debug_assert!(err_amount.is_zero());
1305
1306 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
1330impl<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}