-
Notifications
You must be signed in to change notification settings - Fork 6
/
lib.rs
1442 lines (1314 loc) · 60.7 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Polimec Blockchain – https://www.polimec.org/
// Copyright (C) Polimec 2022. All rights reserved.
// The Polimec Blockchain is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The Polimec Blockchain is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! # Funding Pallet
//!
//! Polimec's main business logic. It allows users to create, evaluate, and fund projects.
//!
//! It rewards project evaluators and contributors with `Contribution Tokens`. These tokens
//! can be redeemed for a project's native tokens, after their parachain is deployed on mainnet.
//! ## 👷 Work in progress 🏗️
//! Expect major changes between PRs
//!
//! ## Overview
//! The official logic for Polimec's blockchain can be found at our [whitepaper](https://polimec.link/whitepaper).
//!
//! There are 3 types of users in Polimec:
//! - **Issuers**: They create projects and are responsible for their success.
//! - **Evaluators**: They evaluate projects and are rewarded for their work.
//! - **Contributors**: They contribute financially to projects and are rewarded on the basis of their contribution
//!
//! A contributor, depending on their investor profile, can participate in different rounds of a project's funding.
//!
//! There are 3 types of contributors:
//! - **Institutional**
//! - **Professional**
//! - **Retail**
//!
//! Basic flow of a project's lifecycle:
//!
//!
//! | Step | Description | Resulting Project State |
//! |---------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------|
//! | Creation | Issuer creates a project with the [`create()`](Pallet::create) extrinsic. | [`Application`](ProjectStatus::Application) |
//! | Evaluation Start | Issuer starts the evaluation round with the [`start_evaluation()`](Pallet::start_evaluation) extrinsic. | [`EvaluationRound`](ProjectStatus::EvaluationRound) |
//! | Evaluation Submissions | Evaluators assess the project information, and if they think it is good enough to get funding, they bond Polimec's native token PLMC with [`bond_evaluation()`](Pallet::bond_evaluation) | [`EvaluationRound`](ProjectStatus::EvaluationRound) |
//! | Evaluation End | Evaluation round ends automatically after the [`Config::EvaluationDuration`] has passed. This is achieved by the [`on_initialize()`](Pallet::on_initialize) function. | [`AuctionInitializePeriod`](ProjectStatus::AuctionInitializePeriod) |
//! | Auction Start | Issuer starts the auction round within the [`Config::AuctionInitializePeriodDuration`], by calling the extrinsic [`start_auction()`](Pallet::start_auction) | [`AuctionRound(English)`](ProjectStatus::AuctionRound) |
//! | Bid Submissions | Institutional and Professional users can place bids with [`bid()`](Pallet::bid) by choosing their desired token price, amount, and multiplier (for vesting). Their bids are guaranteed to be considered | [`AuctionRound(English)`](ProjectStatus::AuctionRound) | | |
//! | Candle Auction Transition | After the [`Config::EnglishAuctionDuration`] has passed, the auction goes into candle mode thanks to [`on_initialize()`](Pallet::on_initialize) | [`AuctionRound(Candle)`](ProjectStatus::AuctionRound) |
//! | Bid Submissions | Institutional and Professional users can continue bidding, but this time their bids will only be considered, if they managed to fall before the random ending block calculated at the end of the auction. | [`AuctionRound(Candle)`](ProjectStatus::AuctionRound) |
//! | Community Funding Start | After the [`Config::CandleAuctionDuration`] has passed, the auction automatically. A final token price for the next rounds is calculated based on the accepted bids. | [`CommunityRound`](ProjectStatus::CommunityRound) |
//! | Funding Submissions | Retail investors can call the [`contribute()`](Pallet::contribute) extrinsic to buy tokens at the set price. | [`CommunityRound`](ProjectStatus::CommunityRound) |
//! | Remainder Funding Start | After the [`Config::CommunityFundingDuration`] has passed, the project is now open to token purchases from any user type | [`RemainderRound`](ProjectStatus::RemainderRound) |
//! | Funding End | If all tokens were sold, or after the [`Config::RemainderFundingDuration`] has passed, the project automatically ends, and it is calculated if it reached its desired funding or not. | [`FundingEnded`](ProjectStatus::FundingSuccessful) |
//! | Evaluator Rewards | If the funding was successful, evaluators can claim their contribution token rewards with the [`TBD`]() extrinsic. If it failed, evaluators can either call the [`failed_evaluation_unbond_for()`](Pallet::failed_evaluation_unbond_for) extrinsic, or wait for the [`on_idle()`](Pallet::on_initialize) function, to return their funds | [`FundingEnded`](ProjectStatus::FundingSuccessful) |
//! | Bidder Rewards | If the funding was successful, bidders will call [`vested_contribution_token_bid_mint_for()`](Pallet::vested_contribution_token_bid_mint_for) to mint the contribution tokens they are owed, and [`vested_plmc_bid_unbond_for()`](Pallet::vested_plmc_bid_unbond_for) to unbond their PLMC, based on their current vesting schedule. | [`FundingEnded`](ProjectStatus::FundingSuccessful) |
//! | Buyer Rewards | If the funding was successful, users who bought tokens on the Community or Remainder round, can call [`vested_contribution_token_purchase_mint_for()`](Pallet::vested_contribution_token_purchase_mint_for) to mint the contribution tokens they are owed, and [`vested_plmc_purchase_unbond_for()`](Pallet::vested_plmc_purchase_unbond_for) to unbond their PLMC, based on their current vesting schedule | [`FundingEnded`](ProjectStatus::FundingSuccessful) |
//!
//! ## Interface
//! All users who wish to participate need to have a valid credential, given to them on the KILT parachain, by a KYC/AML provider.
//! ### Extrinsics
//! * [`create`](Pallet::create) : Creates a new project.
//! * [`edit_metadata`](Pallet::edit_metadata) : Submit a new Hash of the project metadata.
//! * [`start_evaluation`](Pallet::start_evaluation) : Start the Evaluation round of a project.
//! * [`start_auction`](Pallet::start_auction) : Start the English Auction round of a project.
//! * [`bond_evaluation`](Pallet::bond_evaluation) : Bond PLMC on a project in the evaluation stage. A sort of "bet" that you think the project will be funded
//! * [`failed_evaluation_unbond_for`](Pallet::failed_evaluation_unbond_for) : Unbond the PLMC bonded on a project's evaluation round for any user, if the project failed the evaluation.
//! * [`bid`](Pallet::bid) : Perform a bid during the English or Candle Auction Round.
//! * [`contribute`](Pallet::contribute) : Buy contribution tokens if a project during the Community or Remainder round
//! * [`vested_plmc_bid_unbond_for`](Pallet::vested_plmc_bid_unbond_for) : Unbond the PLMC bonded on a project's English or Candle Auction Round for any user, based on their vesting schedule.
//! * [`vested_plmc_purchase_unbond_for`](Pallet::vested_plmc_purchase_unbond_for) : Unbond the PLMC bonded on a project's Community or Remainder Round for any user, based on their vesting schedule.
//! * [`vested_contribution_token_bid_mint_for`](Pallet::vested_contribution_token_bid_mint_for) : Mint the contribution tokens for a user who participated in the English or Candle Auction Round, based on their vesting schedule.
//! * [`vested_contribution_token_purchase_mint_for`](Pallet::vested_contribution_token_purchase_mint_for) : Mint the contribution tokens for a user who participated in the Community or Remainder Round, based on their vesting schedule.
//!
//! ### Storage Items
//! * [`NextProjectId`] : Increasing counter to get the next id to assign to a project.
//! * [`NextBidId`]: Increasing counter to get the next id to assign to a bid.
//! * [`Nonce`]: Increasing counter to be used in random number generation.
//! * [`Images`]: Map of the hash of some metadata to the user who owns it. Avoids storing the same image twice, and keeps track of ownership for a future project data access due to regulatory compliance.
//! * [`ProjectsMetadata`]: Map of the assigned id, to the main information of a project.
//! * [`ProjectsIssuers`]: Map of a project id, to its issuer account.
//! * [`ProjectsDetails`]: Map of a project id, to some additional information required for ensuring correctness of the protocol.
//! * [`ProjectsToUpdate`]: Map of a block number, to a vector of project ids. Used to keep track of projects that need to be updated in on_initialize.
//! * [`Bids`]: Double map linking a project-user to the bids they made.
//! * [`Evaluations`]: Double map linking a project-user to the PLMC they bonded in the evaluation round.
//! * [`Contributions`]: Double map linking a project-user to the contribution tokens they bought in the Community or Remainder round.
//!
//! ## Usage
//! You can circumvent the extrinsics by calling the do_* functions that they call directly.
//! This is useful if you need to make use of this pallet's functionalities in a pallet of your own, and you don't want to pay the transaction fees twice.
//! ### Example: A retail user buying tokens for a project in the community round
//! ```
//! #[frame_support::pallet(dev_mode)]
//! pub mod pallet {
//! use super::*;
//! use frame_support::pallet_prelude::*;
//! use frame_system::pallet_prelude::*;
//! use pallet_funding::{AcceptedFundingAsset, MultiplierOf};
//!
//! #[pallet::pallet]
//! pub struct Pallet<T>(_);
//!
//! #[pallet::config]
//! pub trait Config: frame_system::Config + pallet_funding::Config {}
//!
//! #[pallet::call]
//! impl<T: Config> Pallet<T> {
//! /// Buy tokens for a project in the community round if it achieved at least 500k USDT funding
//! #[pallet::weight(0)]
//! pub fn buy_if_popular(
//! origin: OriginFor<T>,
//! project_id: pallet_funding::ProjectId,
//! amount: <T as pallet_funding::Config>::Balance
//! ) -> DispatchResultWithPostInfo {
//! let retail_user = ensure_signed(origin)?;
//! // Check project is in the community round
//! let project_details = pallet_funding::Pallet::<T>::project_details(project_id).ok_or(Error::<T>::ProjectNotFound)?;
//! ensure!(project_details.status == pallet_funding::ProjectStatus::CommunityRound, "Project is not in the community round");
//!
//! // Calculate how much funding was done already
//! let project_contributions: <T as pallet_funding::Config>::Balance = pallet_funding::Contributions::<T>::iter_prefix_values((project_id,))
//! .fold(
//! 0u64.into(),
//! |total_tokens_bought, contribution| {
//! total_tokens_bought + contribution.usd_contribution_amount
//! }
//! );
//!
//! ensure!(project_contributions >= 500_000_0_000_000_000u64.into(), "Project did not achieve at least 500k USDT funding");
//! let multiplier: MultiplierOf<T> = 1u8.try_into().map_err(|_| Error::<T>::ProjectNotFound)?;
//! // Buy tokens with the default multiplier
//! pallet_funding::Pallet::<T>::do_contribute(&retail_user, project_id, amount, multiplier, AcceptedFundingAsset::USDT)
//! }
//! }
//!
//! #[pallet::error]
//! pub enum Error<T> {
//! ProjectNotFound,
//! }
//! }
//! ```
//!
//! ## Credentials
//! The pallet will only allow users with certain credential types, to execute certain extrinsics.:
//!
//!
//! | Extrinsic | Issuer | Retail Investor | Professional Investor | Institutional Investor |
//! |-----------------------------------------------|--------|-----------------|-----------------------|------------------------|
//! | `create` | X | | | |
//! | `edit_metadata` | X | | | |
//! | `start_evaluation` | X | | | |
//! | `start_auction` | X | | | |
//! | `bond_evaluation` | | X | X | X |
//! | `failed_evaluation_unbond_for` | | X | X | X |
//! | `bid` | | | X | X |
//! | `contribute` | | X | X* | X* |
//! | `vested_plmc_bid_unbond_for` | | | X | X |
//! | `vested_plmc_purchase_unbond_for` | | X | X | X |
//! | `vested_contribution_token_bid_mint_for` | | | X | X |
//! | `vested_contribution_token_purchase_mint_for` | | X | X | X |
//!
//! _* They can call contribute only if the project is on the remainder round._
//!
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
// This recursion limit is needed because we have too many benchmarks and benchmarking will fail if
// we add more without this limit.
#![cfg_attr(feature = "runtime-benchmarks", recursion_limit = "512")]
pub use crate::weights::WeightInfo;
use frame_support::{
traits::{
tokens::{fungible, fungibles, Balance},
AccountTouch, ContainsPair, Randomness,
},
BoundedVec, PalletId,
};
use frame_system::pallet_prelude::BlockNumberFor;
pub use pallet::*;
use polimec_common::migration_types::*;
use polkadot_parachain::primitives::Id as ParaId;
use sp_arithmetic::traits::{One, Saturating};
use sp_runtime::{traits::AccountIdConversion, FixedPointNumber, FixedPointOperand, FixedU128};
use sp_std::{marker::PhantomData, prelude::*};
use traits::DoRemainingOperation;
pub use types::*;
use xcm::v3::{opaque::Instruction, prelude::*, SendXcm};
pub mod functions;
#[cfg(test)]
pub mod mock;
pub mod types;
pub mod weights;
#[cfg(test)]
pub mod tests;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
pub mod impls;
#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
pub mod instantiator;
pub mod traits;
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
pub type ProjectId = u32;
pub type MultiplierOf<T> = <T as Config>::Multiplier;
pub type BalanceOf<T> = <T as Config>::Balance;
pub type PriceOf<T> = <T as Config>::Price;
pub type StringLimitOf<T> = <T as Config>::StringLimit;
pub type HashOf<T> = <T as frame_system::Config>::Hash;
pub type AssetIdOf<T> =
<<T as Config>::FundingCurrency as fungibles::Inspect<<T as frame_system::Config>::AccountId>>::AssetId;
pub type RewardInfoOf<T> = RewardInfo<BalanceOf<T>>;
pub type EvaluatorsOutcomeOf<T> = EvaluatorsOutcome<BalanceOf<T>>;
pub type ProjectMetadataOf<T> =
ProjectMetadata<BoundedVec<u8, StringLimitOf<T>>, BalanceOf<T>, PriceOf<T>, AccountIdOf<T>, HashOf<T>>;
pub type ProjectDetailsOf<T> =
ProjectDetails<AccountIdOf<T>, BlockNumberFor<T>, PriceOf<T>, BalanceOf<T>, EvaluationRoundInfoOf<T>>;
pub type EvaluationRoundInfoOf<T> = EvaluationRoundInfo<BalanceOf<T>>;
pub type VestingInfoOf<T> = VestingInfo<BlockNumberFor<T>, BalanceOf<T>>;
pub type EvaluationInfoOf<T> = EvaluationInfo<u32, ProjectId, AccountIdOf<T>, BalanceOf<T>, BlockNumberFor<T>>;
pub type BidInfoOf<T> =
BidInfo<ProjectId, BalanceOf<T>, PriceOf<T>, AccountIdOf<T>, BlockNumberFor<T>, MultiplierOf<T>, VestingInfoOf<T>>;
pub type ContributionInfoOf<T> =
ContributionInfo<u32, ProjectId, AccountIdOf<T>, BalanceOf<T>, MultiplierOf<T>, VestingInfoOf<T>>;
pub type ProjectMigrationOriginsOf<T> =
ProjectMigrationOrigins<ProjectId, BoundedVec<MigrationOrigin, MaxMigrationsPerXcm<T>>>;
pub type BucketOf<T> = Bucket<BalanceOf<T>, PriceOf<T>>;
pub type WeightInfoOf<T> = <T as Config>::WeightInfo;
pub const PLMC_STATEMINT_ID: u32 = 2069;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use crate::traits::{BondingRequirementCalculation, ProvideStatemintPrice, VestingDurationCalculation};
use frame_support::{
pallet_prelude::*,
traits::{OnFinalize, OnIdle, OnInitialize},
};
use frame_system::pallet_prelude::*;
use local_macros::*;
use sp_arithmetic::Percent;
use sp_runtime::traits::{Convert, ConvertBack};
#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
use crate::traits::SetPrices;
#[pallet::composite_enum]
pub enum HoldReason {
Evaluation(ProjectId),
Participation(ProjectId),
// We require a PLMC deposit to create an account for minting the CTs to this user.
// Here we make sure the user has this amount before letting him participate.
FutureDeposit(ProjectId),
}
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config:
frame_system::Config + pallet_balances::Config<Balance = BalanceOf<Self>> + pallet_xcm::Config
{
#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
type SetPrices: SetPrices;
type AllPalletsWithoutSystem: OnFinalize<BlockNumberFor<Self>>
+ OnIdle<BlockNumberFor<Self>>
+ OnInitialize<BlockNumberFor<Self>>;
type RuntimeEvent: From<Event<Self>>
+ TryInto<Event<Self>>
+ IsType<<Self as frame_system::Config>::RuntimeEvent>
+ Parameter
+ Member;
// TODO: our local BlockNumber should be removed once we move onto using Moment for time tracking
type BlockNumber: IsType<BlockNumberFor<Self>> + Into<u64>;
type AccountId32Conversion: ConvertBack<Self::AccountId, [u8; 32]>;
type RuntimeOrigin: IsType<<Self as frame_system::Config>::RuntimeOrigin>
+ Into<Result<pallet_xcm::Origin, <Self as Config>::RuntimeOrigin>>;
type RuntimeCall: Parameter + IsType<<Self as frame_system::Config>::RuntimeCall> + From<Call<Self>>;
/// Multiplier that decides how much PLMC needs to be bonded for a token buy/bid
type Multiplier: Parameter
+ BondingRequirementCalculation
+ VestingDurationCalculation
+ Default
+ Copy
+ TryFrom<u8>
+ MaxEncodedLen
+ MaybeSerializeDeserialize;
/// The inner balance type we will use for all of our outer currency types. (e.g native, funding, CTs)
type Balance: Balance + From<u64> + FixedPointOperand + MaybeSerializeDeserialize + Into<u128>;
/// Represents the value of something in USD
type Price: FixedPointNumber + Parameter + Copy + MaxEncodedLen + MaybeSerializeDeserialize;
type RuntimeHoldReason: From<HoldReason>;
/// The chains native currency
type NativeCurrency: fungible::InspectHold<AccountIdOf<Self>, Balance = BalanceOf<Self>>
+ fungible::MutateHold<
AccountIdOf<Self>,
Balance = BalanceOf<Self>,
Reason = <Self as Config>::RuntimeHoldReason,
> + fungible::BalancedHold<AccountIdOf<Self>, Balance = BalanceOf<Self>>
+ fungible::Mutate<AccountIdOf<Self>, Balance = BalanceOf<Self>>;
/// The currency used for funding projects in bids and contributions
// type FundingCurrency: ReservableCurrency<AccountIdOf<Self, Balance = BalanceOf<Self>>;
type FundingCurrency: fungibles::InspectEnumerable<AccountIdOf<Self>, Balance = BalanceOf<Self>, AssetId = u32>
+ fungibles::metadata::Inspect<AccountIdOf<Self>, AssetId = u32>
+ fungibles::metadata::Mutate<AccountIdOf<Self>, AssetId = u32>
+ fungibles::Mutate<AccountIdOf<Self>, Balance = BalanceOf<Self>>;
/// The currency used for minting contribution tokens as fungible assets (i.e pallet-assets)
type ContributionTokenCurrency: fungibles::Create<AccountIdOf<Self>, AssetId = ProjectId, Balance = BalanceOf<Self>>
+ fungibles::Destroy<AccountIdOf<Self>, AssetId = ProjectId, Balance = BalanceOf<Self>>
+ fungibles::InspectEnumerable<AccountIdOf<Self>, Balance = BalanceOf<Self>>
+ fungibles::metadata::Inspect<AccountIdOf<Self>>
+ fungibles::metadata::Mutate<AccountIdOf<Self>>
+ fungibles::Mutate<AccountIdOf<Self>, Balance = BalanceOf<Self>>
+ fungibles::roles::Inspect<AccountIdOf<Self>>
+ AccountTouch<ProjectId, AccountIdOf<Self>, Balance = BalanceOf<Self>>
+ ContainsPair<ProjectId, AccountIdOf<Self>>;
type PriceProvider: ProvideStatemintPrice<AssetId = u32, Price = Self::Price>;
/// Something that provides randomness in the runtime.
type Randomness: Randomness<Self::Hash, BlockNumberFor<Self>>;
/// The maximum length of data stored on-chain.
#[pallet::constant]
type StringLimit: Get<u32>;
/// The maximum size of a preimage allowed, expressed in bytes.
#[pallet::constant]
type PreImageLimit: Get<u32>;
/// The length (expressed in number of blocks) of the evaluation period.
#[pallet::constant]
type EvaluationDuration: Get<BlockNumberFor<Self>>;
/// The time window (expressed in number of blocks) that an issuer has to start the auction round.
#[pallet::constant]
type AuctionInitializePeriodDuration: Get<BlockNumberFor<Self>>;
/// The length (expressed in number of blocks) of the Auction Round, English period.
#[pallet::constant]
type EnglishAuctionDuration: Get<BlockNumberFor<Self>>;
/// The length (expressed in number of blocks) of the Auction Round, Candle period.
#[pallet::constant]
type CandleAuctionDuration: Get<BlockNumberFor<Self>>;
/// The length (expressed in number of blocks) of the Community Round.
#[pallet::constant]
type CommunityFundingDuration: Get<BlockNumberFor<Self>>;
/// The length (expressed in number of blocks) of the Remainder Round.
#[pallet::constant]
type RemainderFundingDuration: Get<BlockNumberFor<Self>>;
/// `PalletId` for the funding pallet. An appropriate value could be
/// `PalletId(*b"py/cfund")`
#[pallet::constant]
type PalletId: Get<PalletId>;
/// How many projects should we update in on_initialize each block
#[pallet::constant]
type MaxProjectsToUpdatePerBlock: Get<u32>;
/// How many distinct evaluations per user per project
type MaxEvaluationsPerUser: Get<u32>;
/// The maximum number of bids per user per project
#[pallet::constant]
type MaxBidsPerUser: Get<u32>;
/// The maximum number of bids per user per project
#[pallet::constant]
type MaxContributionsPerUser: Get<u32>;
/// The maximum number of bids per user
#[pallet::constant]
type ContributionVesting: Get<u32>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: weights::WeightInfo;
type FeeBrackets: Get<Vec<(Percent, <Self as Config>::Balance)>>;
type EvaluationSuccessThreshold: Get<Percent>;
type Vesting: polimec_common::ReleaseSchedule<
AccountIdOf<Self>,
<Self as Config>::RuntimeHoldReason,
Currency = Self::NativeCurrency,
Moment = BlockNumberFor<Self>,
>;
/// For now we expect 3 days until the project is automatically accepted. Timeline decided by MiCA regulations.
type ManualAcceptanceDuration: Get<BlockNumberFor<Self>>;
/// For now we expect 4 days from acceptance to settlement due to MiCA regulations.
type SuccessToSettlementTime: Get<BlockNumberFor<Self>>;
type EvaluatorSlash: Get<Percent>;
type TreasuryAccount: Get<AccountIdOf<Self>>;
/// Convert 24 hours as FixedU128, to the corresponding amount of blocks in the same type as frame_system
type DaysToBlocks: Convert<FixedU128, BlockNumberFor<Self>>;
type BlockNumberToBalance: Convert<BlockNumberFor<Self>, BalanceOf<Self>>;
type PolimecReceiverInfo: Get<PalletInfo>;
/// Range of max_message_size values for the hrmp config where we accept the incoming channel request
type MaxMessageSizeThresholds: Get<(u32, u32)>;
/// Range of max_capacity_thresholds values for the hrmp config where we accept the incoming channel request
type MaxCapacityThresholds: Get<(u32, u32)>;
/// max_capacity config required for the channel from polimec to the project
type RequiredMaxCapacity: Get<u32>;
/// max_message_size config required for the channel from polimec to the project
type RequiredMaxMessageSize: Get<u32>;
}
#[pallet::storage]
#[pallet::getter(fn next_project_id)]
/// A global counter for indexing the projects
/// OnEmpty in this case is GetDefault, so 0.
pub type NextProjectId<T: Config> = StorageValue<_, ProjectId, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn next_evaluation_id)]
pub type NextEvaluationId<T: Config> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn next_bid_id)]
pub type NextBidId<T: Config> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn next_contribution_id)]
pub type NextContributionId<T: Config> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn nonce)]
/// A global counter used in the randomness generation
// TODO: PLMC-155. Remove it after using the Randomness from BABE's VRF: https://github.com/PureStake/moonbeam/issues/1391
// Or use the randomness from Moonbeam.
pub type Nonce<T: Config> = StorageValue<_, u32, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn images)]
/// A StorageMap containing all the hashes of the project metadata uploaded by the users.
pub type Images<T: Config> = StorageMap<_, Blake2_128Concat, T::Hash, AccountIdOf<T>>;
#[pallet::storage]
#[pallet::getter(fn projects_metadata)]
/// A StorageMap containing the primary project information of projects
pub type ProjectsMetadata<T: Config> = StorageMap<_, Blake2_128Concat, ProjectId, ProjectMetadataOf<T>>;
#[pallet::storage]
/// A StorageMap containing the primary project information of projects
pub type Buckets<T: Config> = StorageMap<_, Blake2_128Concat, ProjectId, BucketOf<T>>;
#[pallet::storage]
#[pallet::getter(fn project_details)]
/// StorageMap containing additional information for the projects, relevant for correctness of the protocol
pub type ProjectsDetails<T: Config> = StorageMap<_, Blake2_128Concat, ProjectId, ProjectDetailsOf<T>>;
#[pallet::storage]
#[pallet::getter(fn projects_to_update)]
/// A map to know in which block to update which active projects using on_initialize.
pub type ProjectsToUpdate<T: Config> = StorageMap<
_,
Blake2_128Concat,
BlockNumberFor<T>,
BoundedVec<(ProjectId, UpdateType), T::MaxProjectsToUpdatePerBlock>,
ValueQuery,
>;
#[pallet::storage]
#[pallet::getter(fn evaluations)]
/// Keep track of the PLMC bonds made to each project by each evaluator
pub type Evaluations<T: Config> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, ProjectId>,
NMapKey<Blake2_128Concat, AccountIdOf<T>>,
NMapKey<Blake2_128Concat, u32>,
),
EvaluationInfoOf<T>,
>;
#[pallet::storage]
#[pallet::getter(fn bids)]
/// StorageMap containing the bids for each project and user
pub type Bids<T: Config> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, ProjectId>,
NMapKey<Blake2_128Concat, AccountIdOf<T>>,
NMapKey<Blake2_128Concat, u32>,
),
BidInfoOf<T>,
>;
#[pallet::storage]
#[pallet::getter(fn contributions)]
/// Contributions made during the Community and Remainder round. i.e token buys
pub type Contributions<T: Config> = StorageNMap<
_,
(
NMapKey<Blake2_128Concat, ProjectId>,
NMapKey<Blake2_128Concat, AccountIdOf<T>>,
NMapKey<Blake2_128Concat, u32>,
),
ContributionInfoOf<T>,
>;
#[pallet::storage]
/// Migrations sent and awaiting for confirmation
pub type UnconfirmedMigrations<T: Config> = StorageMap<_, Blake2_128Concat, QueryId, ProjectMigrationOriginsOf<T>>;
#[pallet::event]
#[pallet::generate_deposit(pub (super) fn deposit_event)]
pub enum Event<T: Config> {
/// A project was created.
ProjectCreated {
project_id: ProjectId,
issuer: T::AccountId,
},
/// The metadata of a project was modified.
MetadataEdited {
project_id: ProjectId,
},
/// The evaluation phase of a project started.
EvaluationStarted {
project_id: ProjectId,
},
/// The evaluation phase of a project ended without reaching the minimum threshold of evaluation bonds.
EvaluationFailed {
project_id: ProjectId,
},
/// The period an issuer has to start the auction phase of the project.
AuctionInitializePeriod {
project_id: ProjectId,
start_block: BlockNumberFor<T>,
end_block: BlockNumberFor<T>,
},
/// The auction round of a project started.
EnglishAuctionStarted {
project_id: ProjectId,
when: BlockNumberFor<T>,
},
/// The candle auction part of the auction started for a project
CandleAuctionStarted {
project_id: ProjectId,
when: BlockNumberFor<T>,
},
/// The auction round of a project ended.
AuctionFailed {
project_id: ProjectId,
},
/// A `bonder` bonded an `amount` of PLMC for `project_id`.
FundsBonded {
project_id: ProjectId,
amount: BalanceOf<T>,
bonder: AccountIdOf<T>,
},
/// Someone paid for the release of a user's PLMC bond for a project.
BondReleased {
project_id: ProjectId,
amount: BalanceOf<T>,
bonder: AccountIdOf<T>,
releaser: AccountIdOf<T>,
},
/// A bid was made for a project
Bid {
project_id: ProjectId,
amount: BalanceOf<T>,
price: T::Price,
multiplier: MultiplierOf<T>,
},
/// A contribution was made for a project. i.e token purchase
Contribution {
project_id: ProjectId,
contributor: AccountIdOf<T>,
amount: BalanceOf<T>,
multiplier: MultiplierOf<T>,
},
/// A project is now in its community funding round
CommunityFundingStarted {
project_id: ProjectId,
},
/// A project is now in the remainder funding round
RemainderFundingStarted {
project_id: ProjectId,
},
/// A project has now finished funding
FundingEnded {
project_id: ProjectId,
outcome: FundingOutcome,
},
/// Something was not properly initialized. Most likely due to dev error manually calling do_* functions or updating storage
TransitionError {
project_id: ProjectId,
error: DispatchError,
},
/// Something terribly wrong happened where the bond could not be unbonded. Most likely a programming error
EvaluationUnbondFailed {
project_id: ProjectId,
evaluator: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
/// Contribution tokens were minted to a user
ContributionTokenMinted {
releaser: AccountIdOf<T>,
project_id: ProjectId,
claimer: AccountIdOf<T>,
amount: BalanceOf<T>,
},
/// A transfer of tokens failed, but because it was done inside on_initialize it cannot be solved.
TransferError {
error: DispatchError,
},
EvaluationRewardFailed {
project_id: ProjectId,
evaluator: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
EvaluationSlashFailed {
project_id: ProjectId,
evaluator: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
ReleaseBidFundsFailed {
project_id: ProjectId,
bidder: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
BidUnbondFailed {
project_id: ProjectId,
bidder: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
ReleaseContributionFundsFailed {
project_id: ProjectId,
contributor: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
ContributionUnbondFailed {
project_id: ProjectId,
contributor: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
PayoutContributionFundsFailed {
project_id: ProjectId,
contributor: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
PayoutBidFundsFailed {
project_id: ProjectId,
bidder: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
EvaluationRewarded {
project_id: ProjectId,
evaluator: AccountIdOf<T>,
id: u32,
amount: BalanceOf<T>,
caller: AccountIdOf<T>,
},
EvaluationSlashed {
project_id: ProjectId,
evaluator: AccountIdOf<T>,
id: u32,
amount: BalanceOf<T>,
caller: AccountIdOf<T>,
},
CTMintFailed {
project_id: ProjectId,
claimer: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
StartBidderVestingScheduleFailed {
project_id: ProjectId,
bidder: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
StartContributionVestingScheduleFailed {
project_id: ProjectId,
contributor: AccountIdOf<T>,
id: u32,
error: DispatchError,
},
BidPlmcVestingScheduled {
project_id: ProjectId,
bidder: AccountIdOf<T>,
id: u32,
amount: BalanceOf<T>,
caller: AccountIdOf<T>,
},
ContributionPlmcVestingScheduled {
project_id: ProjectId,
contributor: AccountIdOf<T>,
id: u32,
amount: BalanceOf<T>,
caller: AccountIdOf<T>,
},
ParticipantPlmcVested {
project_id: ProjectId,
participant: AccountIdOf<T>,
amount: BalanceOf<T>,
caller: AccountIdOf<T>,
},
BidFundingPaidOut {
project_id: ProjectId,
bidder: AccountIdOf<T>,
id: u32,
amount: BalanceOf<T>,
caller: AccountIdOf<T>,
},
ContributionFundingPaidOut {
project_id: ProjectId,
contributor: AccountIdOf<T>,
id: u32,
amount: BalanceOf<T>,
caller: AccountIdOf<T>,
},
BidFundingReleased {
project_id: ProjectId,
bidder: AccountIdOf<T>,
id: u32,
amount: BalanceOf<T>,
caller: AccountIdOf<T>,
},
ContributionFundingReleased {
project_id: ProjectId,
contributor: AccountIdOf<T>,
id: u32,
amount: BalanceOf<T>,
caller: AccountIdOf<T>,
},
ProjectOutcomeDecided {
project_id: ProjectId,
decision: FundingOutcomeDecision,
},
ProjectParaIdSet {
project_id: ProjectId,
para_id: ParaId,
caller: T::AccountId,
},
/// A channel was accepted from a parachain to Polimec belonging to a project. A request has been sent to the relay for a Polimec->project channel
HrmpChannelAccepted {
project_id: ProjectId,
para_id: ParaId,
},
/// A channel was established from Polimec to a project. The relay has notified us of their acceptance of our request
HrmpChannelEstablished {
project_id: ProjectId,
para_id: ParaId,
},
/// Started a migration readiness check
MigrationReadinessCheckStarted {
project_id: ProjectId,
caller: T::AccountId,
},
MigrationCheckResponseAccepted {
project_id: ProjectId,
query_id: QueryId,
response: Response,
},
MigrationCheckResponseRejected {
project_id: ProjectId,
query_id: QueryId,
response: Response,
},
MigrationStarted {
project_id: ProjectId,
},
UserMigrationSent {
project_id: ProjectId,
caller: AccountIdOf<T>,
participant: AccountIdOf<T>,
},
MigrationsConfirmed {
project_id: ProjectId,
migration_origins: BoundedVec<MigrationOrigin, MaxMigrationsPerXcm<T>>,
},
MigrationsFailed {
project_id: ProjectId,
migration_origins: BoundedVec<MigrationOrigin, MaxMigrationsPerXcm<T>>,
},
ReleaseFutureCTDepositFailed {
project_id: ProjectId,
participant: AccountIdOf<T>,
error: DispatchError,
},
FutureCTDepositReleased {
project_id: ProjectId,
participant: AccountIdOf<T>,
caller: AccountIdOf<T>,
},
}
#[pallet::error]
pub enum Error<T> {
/// Something in storage has a state which should never be possible at this point. Programming error
ImpossibleState,
/// The price provided in the `create` call is too low
PriceTooLow,
/// The participation size provided in the `create` call is too low
ParticipantsSizeError,
/// The ticket size provided in the `create` call is too low
TicketSizeError,
/// The specified project does not exist
ProjectNotFound,
/// The Evaluation Round of the project has not started yet
EvaluationNotStarted,
/// The Evaluation Round of the project has ended without reaching the minimum threshold
EvaluationFailed,
/// The issuer cannot contribute to their own project during the Funding Round
ContributionToThemselves,
/// Only the issuer can start the Evaluation Round
NotAllowed,
/// The Metadata Hash of the project was not found
MetadataNotProvided,
/// The Auction Round of the project has not started yet
AuctionNotStarted,
/// You cannot edit the metadata of a project that already passed the Evaluation Round
Frozen,
/// The bid is too low
BidTooLow,
/// The Funding Round of the project has not ended yet
CannotClaimYet,
/// No bids were made for the project at the time of the auction close
NoBidsFound,
/// Tried to freeze the project to start the Evaluation Round, but the project is already frozen
ProjectAlreadyFrozen,
/// Tried to move the project from Application to Evaluation round, but the project is not in ApplicationRound
ProjectNotInApplicationRound,
/// Tried to move the project from Evaluation to EvaluationEnded round, but the project is not in EvaluationRound
ProjectNotInEvaluationRound,
/// Tried to move the project from AuctionInitializePeriod to EnglishAuctionRound, but the project is not in AuctionInitializePeriodRound
ProjectNotInAuctionInitializePeriodRound,
/// Tried to move the project to CandleAuction, but it was not in EnglishAuctionRound before
ProjectNotInEnglishAuctionRound,
/// Tried to move the project to Community round, but it was not in CandleAuctionRound before
ProjectNotInCandleAuctionRound,
/// Tried to move the project to RemainderRound, but it was not in CommunityRound before
ProjectNotInCommunityRound,
/// Tried to move the project to ReadyToLaunch round, but it was not in FundingEnded round before
ProjectNotInFundingEndedRound,
/// Tried to start an auction before the initialization period
TooEarlyForEnglishAuctionStart,
/// Tried to move the project to CandleAuctionRound, but its too early for that
TooEarlyForCandleAuctionStart,
/// Tried to move the project to CommunityRound, but its too early for that
TooEarlyForCommunityRoundStart,
/// Tried to move the project to RemainderRound, but its too early for that
TooEarlyForRemainderRoundStart,
/// Tried to move to project to FundingEnded round, but its too early for that
TooEarlyForFundingEnd,
/// Checks for other projects not copying metadata of others
MetadataAlreadyExists,
/// The specified project details does not exist
ProjectDetailsNotFound,
/// Tried to finish an evaluation before its target end block
EvaluationPeriodNotEnded,
/// Tried to access field that is not set
FieldIsNone,
/// Checked math failed
BadMath,
/// Tried to retrieve a bid but it does not exist
BidNotFound,
/// Tried to contribute but its too low to be accepted
ContributionTooLow,
/// Contribution is higher than the limit set by the issuer
ContributionTooHigh,
/// Tried to delete a project from the update store but it is not there to begin with.
ProjectNotInUpdateStore,
/// The provided asset is not accepted by the project issuer
FundingAssetNotAccepted,
/// Could not get the price in USD for PLMC
PLMCPriceNotAvailable,
/// Could not get the price in USD for the provided asset
PriceNotFound,
/// Bond is either lower than the minimum set by the issuer, or the vec is full and can't replace an old one with a lower value
EvaluationBondTooLow,
/// Tried to do an operation on an evaluation that does not exist
EvaluationNotFound,
/// Tried to do an operation on a finalizer that already finished
FinalizerFinished,
///
ContributionNotFound,
/// Tried to start a migration check but the bidirectional channel is not yet open
CommsNotEstablished,
XcmFailed,
// Tried to convert one type into another and failed. i.e try_into failed
BadConversion,
/// Tried to release the PLMC deposit held for a future CT mint, but there was nothing to release
NoFutureDepositHeld,
/// The issuer doesn't have enough funds (ExistentialDeposit), to create the escrow account
NotEnoughFundsForEscrowCreation,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Creates a project and assigns it to the `issuer` account.
#[pallet::call_index(0)]
#[pallet::weight(WeightInfoOf::<T>::create())]
pub fn create(origin: OriginFor<T>, project: ProjectMetadataOf<T>) -> DispatchResult {
let issuer = ensure_signed(origin)?;
log::trace!(target: "pallet_funding::test", "in create");
Self::do_create(&issuer, project)
}
/// Change the metadata hash of a project
#[pallet::call_index(1)]
#[pallet::weight(WeightInfoOf::<T>::edit_metadata())]
pub fn edit_metadata(
origin: OriginFor<T>,
project_id: ProjectId,
project_metadata_hash: T::Hash,
) -> DispatchResult {
let issuer = ensure_signed(origin)?;
Self::do_edit_metadata(issuer, project_id, project_metadata_hash)
}
/// Starts the evaluation round of a project. It needs to be called by the project issuer.
#[pallet::call_index(2)]
#[pallet::weight(WeightInfoOf::<T>::start_evaluation())]
pub fn start_evaluation(origin: OriginFor<T>, project_id: ProjectId) -> DispatchResult {
let issuer = ensure_signed(origin)?;
Self::do_evaluation_start(issuer, project_id)
}
/// Starts the auction round for a project. From the next block forward, any professional or
/// institutional user can set bids for a token_amount/token_price pair.
/// Any bids from this point until the candle_auction starts, will be considered as valid.
#[pallet::call_index(3)]
#[pallet::weight(WeightInfoOf::<T>::start_auction())]
pub fn start_auction(origin: OriginFor<T>, project_id: ProjectId) -> DispatchResult {
let issuer = ensure_signed(origin)?;
Self::do_english_auction(issuer, project_id)
}
/// Bond PLMC for a project in the evaluation stage
#[pallet::call_index(4)]
#[pallet::weight(WeightInfoOf::<T>::bond_evaluation())]
pub fn bond_evaluation(
origin: OriginFor<T>,
project_id: ProjectId,
#[pallet::compact] usd_amount: BalanceOf<T>,
) -> DispatchResult {
let evaluator = ensure_signed(origin)?;
Self::do_evaluate(&evaluator, project_id, usd_amount)
}
/// Bid for a project in the Auction round
#[pallet::call_index(5)]
#[pallet::weight(WeightInfoOf::<T>::bid())]
pub fn bid(
origin: OriginFor<T>,
project_id: ProjectId,
#[pallet::compact] amount: BalanceOf<T>,
multiplier: T::Multiplier,
asset: AcceptedFundingAsset,
) -> DispatchResult {
let bidder = ensure_signed(origin)?;
Self::do_bid(&bidder, project_id, amount, multiplier, asset)
}
/// Buy tokens in the Community or Remainder round at the price set in the Auction Round