-
Notifications
You must be signed in to change notification settings - Fork 6
/
functions.rs
3229 lines (2859 loc) · 123 KB
/
functions.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/>.
// If you feel like getting in touch with us, you can do so at info@polimec.org
//! Functions for the Funding pallet.
use crate::ProjectStatus::FundingSuccessful;
use frame_support::{
dispatch::{DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo, PostDispatchInfo},
ensure,
pallet_prelude::*,
traits::{
fungible::{InspectHold, Mutate, MutateHold as FungibleMutateHold},
fungibles::{
metadata::{MetadataDeposit, Mutate as MetadataMutate},
Create, Inspect, Mutate as FungiblesMutate,
},
tokens::{Fortitude, Precision, Preservation, Restriction},
Get,
},
};
use frame_system::pallet_prelude::BlockNumberFor;
use itertools::Itertools;
use polimec_common::ReleaseSchedule;
use sp_arithmetic::{
traits::{CheckedDiv, CheckedSub, Zero},
Percent, Perquintill,
};
use sp_runtime::traits::{Convert, ConvertBack};
use sp_std::marker::PhantomData;
use xcm::v3::MaxDispatchErrorLen;
use super::*;
use crate::traits::{BondingRequirementCalculation, ProvideAssetPrice, VestingDurationCalculation};
use polimec_common::migration_types::{MigrationInfo, MigrationOrigin, Migrations, ParticipationType};
const POLIMEC_PARA_ID: u32 = 3344u32;
const QUERY_RESPONSE_TIME_WINDOW_BLOCKS: u32 = 20u32;
// Round transitions
impl<T: Config> Pallet<T> {
/// Called by user extrinsic
/// Creates a project and assigns it to the `issuer` account.
///
/// # Arguments
/// * `issuer` - The account that will be the issuer of the project.
/// * `project` - The project struct containing all the necessary information.
///
/// # Storage access
/// * [`ProjectsMetadata`] - Inserting the main project information. 1 to 1 with the `project` argument.
/// * [`ProjectsDetails`] - Inserting the project information. constructed from the `project` argument.
/// * [`ProjectsIssuers`] - Inserting the issuer of the project. Mapping of the two parameters `project_id` and `issuer`.
/// * [`NextProjectId`] - Getting the next usable id, and updating it for the next project.
///
/// # Success path
/// The `project` argument is valid. A ProjectInfo struct is constructed, and the storage is updated
/// with the new structs and mappings to reflect the new project creation
///
/// # Next step
/// The issuer will call an extrinsic to start the evaluation round of the project.
/// [`do_start_evaluation`](Self::do_start_evaluation) will be executed.
pub fn do_create(issuer: &AccountIdOf<T>, initial_metadata: ProjectMetadataOf<T>) -> DispatchResult {
// * Get variables *
let project_id = Self::next_project_id();
// * Validity checks *
if let Some(metadata) = initial_metadata.offchain_information_hash {
ensure!(!Images::<T>::contains_key(metadata), Error::<T>::MetadataAlreadyExists);
}
if let Err(error) = initial_metadata.validity_check() {
return match error {
ValidityError::PriceTooLow => Err(Error::<T>::PriceTooLow.into()),
ValidityError::ParticipantsSizeError => Err(Error::<T>::ParticipantsSizeError.into()),
ValidityError::TicketSizeError => Err(Error::<T>::TicketSizeError.into()),
};
}
let total_allocation_size =
initial_metadata.total_allocation_size.0.saturating_add(initial_metadata.total_allocation_size.1);
// * Calculate new variables *
let fundraising_target =
initial_metadata.minimum_price.checked_mul_int(total_allocation_size).ok_or(Error::<T>::BadMath)?;
let now = <frame_system::Pallet<T>>::block_number();
let project_details = ProjectDetails {
issuer: issuer.clone(),
is_frozen: false,
weighted_average_price: None,
fundraising_target,
status: ProjectStatus::Application,
phase_transition_points: PhaseTransitionPoints::new(now),
remaining_contribution_tokens: initial_metadata.total_allocation_size,
funding_amount_reached: BalanceOf::<T>::zero(),
cleanup: Cleaner::NotReady,
evaluation_round_info: EvaluationRoundInfoOf::<T> {
total_bonded_usd: Zero::zero(),
total_bonded_plmc: Zero::zero(),
evaluators_outcome: EvaluatorsOutcome::Unchanged,
},
funding_end_block: None,
parachain_id: None,
migration_readiness_check: None,
hrmp_channel_status: HRMPChannelStatus {
project_to_polimec: ChannelStatus::Closed,
polimec_to_project: ChannelStatus::Closed,
},
};
let bucket: BucketOf<T> = Self::create_bucket_from_metadata(&initial_metadata)?;
// Each project needs an escrow system account to temporarily hold the USDT/USDC. We need to create it by depositing `ED` amount of PLMC into it.
// This should be paid by the issuer.
let escrow_account = Self::fund_account_id(project_id);
// transfer ED from issuer to escrow
T::NativeCurrency::transfer(
issuer,
&escrow_account,
<T as pallet_balances::Config>::ExistentialDeposit::get(),
Preservation::Preserve,
)
.map_err(|_| Error::<T>::NotEnoughFundsForEscrowCreation)?;
// Each project needs a new token type to be created (i.e contribution token).
// This creation is done automatically in the project transition on success, but someone needs to pay for the storage
// of the metadata associated with it.
let metadata_deposit = T::ContributionTokenCurrency::calc_metadata_deposit(
initial_metadata.token_information.name.as_slice(),
initial_metadata.token_information.symbol.as_slice(),
);
T::NativeCurrency::transfer(&issuer, &escrow_account, metadata_deposit, Preservation::Preserve)
.map_err(|_| Error::<T>::NotEnoughFundsForCTMetadata)?;
// * Update storage *
ProjectsMetadata::<T>::insert(project_id, &initial_metadata);
ProjectsDetails::<T>::insert(project_id, project_details);
Buckets::<T>::insert(project_id, bucket);
NextProjectId::<T>::mutate(|n| n.saturating_inc());
if let Some(metadata) = initial_metadata.offchain_information_hash {
Images::<T>::insert(metadata, issuer);
}
// * Emit events *
Self::deposit_event(Event::ProjectCreated { project_id, issuer: issuer.clone() });
Ok(())
}
/// Called by user extrinsic
/// Starts the evaluation round of a project. It needs to be called by the project issuer.
///
/// # Arguments
/// * `project_id` - The id of the project to start the evaluation round for.
///
/// # Storage access
/// * [`ProjectsDetails`] - Checking and updating the round status, transition points and freezing the project.
/// * [`ProjectsToUpdate`] - Scheduling the project for automatic transition by on_initialize later on.
///
/// # Success path
/// The project information is found, its round status was in Application round, and It's not yet frozen.
/// The pertinent project info is updated on the storage, and the project is scheduled for automatic transition by on_initialize.
///
/// # Next step
/// Users will pond PLMC for this project, and when the time comes, the project will be transitioned
/// to the next round by `on_initialize` using [`do_evaluation_end`](Self::do_evaluation_end)
pub fn do_start_evaluation(caller: AccountIdOf<T>, project_id: ProjectId) -> DispatchResultWithPostInfo {
// * Get variables *
let project_metadata = ProjectsMetadata::<T>::get(project_id).ok_or(Error::<T>::ProjectNotFound)?;
let mut project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let now = <frame_system::Pallet<T>>::block_number();
// * Validity checks *
ensure!(project_details.issuer == caller, Error::<T>::NotAllowed);
ensure!(project_details.status == ProjectStatus::Application, Error::<T>::ProjectNotInApplicationRound);
ensure!(!project_details.is_frozen, Error::<T>::ProjectAlreadyFrozen);
ensure!(project_metadata.offchain_information_hash.is_some(), Error::<T>::MetadataNotProvided);
// * Calculate new variables *
let evaluation_end_block = now + T::EvaluationDuration::get();
project_details.phase_transition_points.application.update(None, Some(now));
project_details.phase_transition_points.evaluation.update(Some(now + 1u32.into()), Some(evaluation_end_block));
project_details.is_frozen = true;
project_details.status = ProjectStatus::EvaluationRound;
// * Update storage *
ProjectsDetails::<T>::insert(project_id, project_details);
let actual_insertion_attempts = match Self::add_to_update_store(
evaluation_end_block + 1u32.into(),
(&project_id, UpdateType::EvaluationEnd),
) {
Ok(insertions) => insertions,
Err(insertions) =>
return Err(DispatchErrorWithPostInfo {
post_info: PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_evaluation(insertions)),
pays_fee: Pays::Yes,
},
error: Error::<T>::TooManyInsertionAttempts.into(),
}),
};
// * Emit events *
Self::deposit_event(Event::EvaluationStarted { project_id });
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_evaluation(actual_insertion_attempts)),
pays_fee: Pays::Yes,
})
}
/// Called automatically by on_initialize.
/// Ends the evaluation round, and sets the current round to `AuctionInitializePeriod` if it
/// reached enough PLMC bonding, or to `EvaluationFailed` if it didn't.
///
/// # Arguments
/// * `project_id` - The id of the project to end the evaluation round for.
///
/// # Storage access
/// * [`ProjectsDetails`] - Checking the round status and transition points for validity, and updating
/// the round status and transition points in case of success or failure of the evaluation.
/// * [`Evaluations`] - Checking that the threshold for PLMC bonded was reached, to decide
/// whether the project failed or succeeded.
///
/// # Possible paths
/// * Project achieves its evaluation goal. >=10% of the target funding was reached through bonding,
/// so the project is transitioned to the [`AuctionInitializePeriod`](ProjectStatus::AuctionInitializePeriod) round. The project information
/// is updated with the new transition points and round status.
///
/// * Project doesn't reach the evaluation goal - <10% of the target funding was reached
/// through bonding, so the project is transitioned to the `EvaluationFailed` round. The project
/// information is updated with the new rounds status and it is scheduled for automatic unbonding.
///
/// # Next step
/// * Bonding achieved - The issuer calls an extrinsic within the set period to initialize the
/// auction round. `auction` is called
///
/// * Bonding failed - `on_idle` at some point checks for failed evaluation projects, and
/// unbonds the evaluators funds.
pub fn do_evaluation_end(project_id: ProjectId) -> DispatchResultWithPostInfo {
// * Get variables *
let mut project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let now = <frame_system::Pallet<T>>::block_number();
let evaluation_end_block =
project_details.phase_transition_points.evaluation.end().ok_or(Error::<T>::FieldIsNone)?;
let fundraising_target_usd = project_details.fundraising_target;
let current_plmc_price =
T::PriceProvider::get_price(PLMC_FOREIGN_ID).ok_or(Error::<T>::PLMCPriceNotAvailable)?;
// * Validity checks *
ensure!(project_details.status == ProjectStatus::EvaluationRound, Error::<T>::ProjectNotInEvaluationRound);
ensure!(now > evaluation_end_block, Error::<T>::EvaluationPeriodNotEnded);
// * Calculate new variables *
let initial_balance: BalanceOf<T> = 0u32.into();
let total_amount_bonded = Evaluations::<T>::iter_prefix((project_id,))
.fold(initial_balance, |total, (_evaluator, bond)| total.saturating_add(bond.original_plmc_bond));
let evaluation_target_usd = <T as Config>::EvaluationSuccessThreshold::get() * fundraising_target_usd;
let evaluation_target_plmc = current_plmc_price
.reciprocal()
.ok_or(Error::<T>::BadMath)?
.checked_mul_int(evaluation_target_usd)
.ok_or(Error::<T>::BadMath)?;
let auction_initialize_period_start_block = now + 1u32.into();
let auction_initialize_period_end_block =
auction_initialize_period_start_block + T::AuctionInitializePeriodDuration::get();
// Check which logic path to follow
let is_funded = total_amount_bonded >= evaluation_target_plmc;
// * Branch in possible project paths *
// Successful path
if is_funded {
// * Update storage *
project_details
.phase_transition_points
.auction_initialize_period
.update(Some(auction_initialize_period_start_block), Some(auction_initialize_period_end_block));
project_details.status = ProjectStatus::AuctionInitializePeriod;
ProjectsDetails::<T>::insert(project_id, project_details);
let insertion_attempts = match Self::add_to_update_store(
auction_initialize_period_end_block + 1u32.into(),
(&project_id, UpdateType::EnglishAuctionStart),
) {
Ok(insertions) => insertions,
Err(_insertions) => return Err(Error::<T>::TooManyInsertionAttempts.into()),
};
// * Emit events *
Self::deposit_event(Event::AuctionInitializePeriod {
project_id,
start_block: auction_initialize_period_start_block,
end_block: auction_initialize_period_end_block,
});
return Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::end_evaluation_success(insertion_attempts)),
pays_fee: Pays::Yes,
});
// Unsuccessful path
} else {
// * Update storage *
project_details.status = ProjectStatus::EvaluationFailed;
project_details.cleanup = Cleaner::Failure(CleanerState::Initialized(PhantomData::<Failure>));
ProjectsDetails::<T>::insert(project_id, project_details);
// * Emit events *
Self::deposit_event(Event::EvaluationFailed { project_id });
return Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::end_evaluation_failure()),
pays_fee: Pays::Yes,
});
}
}
/// Called by user extrinsic
/// 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.
///
/// # Arguments
/// * `project_id` - The project identifier
///
/// # Storage access
/// * [`ProjectsDetails`] - Get the project information, and check if the project is in the correct
/// round, and the current block is between the defined start and end blocks of the initialize period.
/// Update the project information with the new round status and transition points in case of success.
///
/// # Success Path
/// The validity checks pass, and the project is transitioned to the English Auction round.
/// The project is scheduled to be transitioned automatically by `on_initialize` at the end of the
/// english auction round.
///
/// # Next step
/// Professional and Institutional users set bids for the project using the [`bid`](Self::bid) extrinsic.
/// Later on, `on_initialize` transitions the project into the candle auction round, by calling
/// [`do_candle_auction`](Self::do_candle_auction).
pub fn do_english_auction(caller: AccountIdOf<T>, project_id: ProjectId) -> DispatchResultWithPostInfo {
// * Get variables *
let mut project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let now = <frame_system::Pallet<T>>::block_number();
let auction_initialize_period_start_block = project_details
.phase_transition_points
.auction_initialize_period
.start()
.ok_or(Error::<T>::EvaluationPeriodNotEnded)?;
// * Validity checks *
ensure!(
caller == project_details.issuer || caller == T::PalletId::get().into_account_truncating(),
Error::<T>::NotAllowed
);
ensure!(now >= auction_initialize_period_start_block, Error::<T>::TooEarlyForEnglishAuctionStart);
// If the auction is first manually started, the automatic transition fails here. This
// behaviour is intended, as it gracefully skips the automatic transition if the
// auction was started manually.
ensure!(
project_details.status == ProjectStatus::AuctionInitializePeriod,
Error::<T>::ProjectNotInAuctionInitializePeriodRound
);
// * Calculate new variables *
let english_start_block = now + 1u32.into();
let english_end_block = now + T::EnglishAuctionDuration::get();
// * Update Storage *
project_details
.phase_transition_points
.english_auction
.update(Some(english_start_block), Some(english_end_block));
project_details.status = ProjectStatus::AuctionRound(AuctionPhase::English);
ProjectsDetails::<T>::insert(project_id, project_details);
let insertion_attempts;
// Schedule for automatic transition to candle auction round
match Self::add_to_update_store(english_end_block + 1u32.into(), (&project_id, UpdateType::CandleAuctionStart))
{
Ok(iterations) => {
insertion_attempts = iterations;
},
Err(insertion_attempts) =>
return Err(DispatchErrorWithPostInfo {
post_info: PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_auction_manually(insertion_attempts)),
pays_fee: Pays::Yes,
},
error: Error::<T>::TooManyInsertionAttempts.into(),
}),
};
// * Emit events *
Self::deposit_event(Event::EnglishAuctionStarted { project_id, when: now });
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_auction_manually(insertion_attempts)),
pays_fee: Pays::Yes,
})
}
/// Called automatically by on_initialize
/// Starts the candle round for a project.
/// Any bids from this point until the candle round ends, are not guaranteed. Only bids
/// made before the random ending block between the candle start and end will be considered
///
/// # Arguments
/// * `project_id` - The project identifier
///
/// # Storage access
/// * [`ProjectsDetails`] - Get the project information, and check if the project is in the correct
/// round, and the current block after the english auction end period.
/// Update the project information with the new round status and transition points in case of success.
///
/// # Success Path
/// The validity checks pass, and the project is transitioned to the Candle Auction round.
/// The project is scheduled to be transitioned automatically by `on_initialize` at the end of the
/// candle auction round.
///
/// # Next step
/// Professional and Institutional users set bids for the project using the `bid` extrinsic,
/// but now their bids are not guaranteed.
/// Later on, `on_initialize` ends the candle auction round and starts the community round,
/// by calling [`do_community_funding`](Self::do_community_funding).
pub fn do_candle_auction(project_id: ProjectId) -> DispatchResultWithPostInfo {
// * Get variables *
let mut project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let now = <frame_system::Pallet<T>>::block_number();
let english_end_block =
project_details.phase_transition_points.english_auction.end().ok_or(Error::<T>::FieldIsNone)?;
// * Validity checks *
ensure!(now > english_end_block, Error::<T>::TooEarlyForCandleAuctionStart);
ensure!(
project_details.status == ProjectStatus::AuctionRound(AuctionPhase::English),
Error::<T>::ProjectNotInEnglishAuctionRound
);
// * Calculate new variables *
let candle_start_block = now + 1u32.into();
let candle_end_block = now + T::CandleAuctionDuration::get();
// * Update Storage *
project_details.phase_transition_points.candle_auction.update(Some(candle_start_block), Some(candle_end_block));
project_details.status = ProjectStatus::AuctionRound(AuctionPhase::Candle);
ProjectsDetails::<T>::insert(project_id, project_details);
// Schedule for automatic check by on_initialize. Success depending on enough funding reached
let insertion_iterations = match Self::add_to_update_store(
candle_end_block + 1u32.into(),
(&project_id, UpdateType::CommunityFundingStart),
) {
Ok(iterations) => iterations,
Err(_iterations) => return Err(Error::<T>::TooManyInsertionAttempts.into()),
};
// * Emit events *
Self::deposit_event(Event::CandleAuctionStarted { project_id, when: now });
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_candle_phase(insertion_iterations)),
pays_fee: Pays::Yes,
})
}
/// Called automatically by on_initialize
/// Starts the community round for a project.
/// Retail users now buy tokens instead of bidding on them. The price of the tokens are calculated
/// based on the available bids, using the function [`calculate_weighted_average_price`](Self::calculate_weighted_average_price).
///
/// # Arguments
/// * `project_id` - The project identifier
///
/// # Storage access
/// * [`ProjectsDetails`] - Get the project information, and check if the project is in the correct
/// round, and the current block is after the candle auction end period.
/// Update the project information with the new round status and transition points in case of success.
///
/// # Success Path
/// The validity checks pass, and the project is transitioned to the Community Funding round.
/// The project is scheduled to be transitioned automatically by `on_initialize` at the end of the
/// round.
///
/// # Next step
/// Retail users buy tokens at the price set on the auction round.
/// Later on, `on_initialize` ends the community round by calling [`do_remainder_funding`](Self::do_remainder_funding) and
/// starts the remainder round, where anyone can buy at that price point.
pub fn do_community_funding(project_id: ProjectId) -> DispatchResultWithPostInfo {
// * Get variables *
let project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let project_metadata = ProjectsMetadata::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let now = <frame_system::Pallet<T>>::block_number();
let auction_candle_start_block =
project_details.phase_transition_points.candle_auction.start().ok_or(Error::<T>::FieldIsNone)?;
let auction_candle_end_block =
project_details.phase_transition_points.candle_auction.end().ok_or(Error::<T>::FieldIsNone)?;
// * Validity checks *
ensure!(now > auction_candle_end_block, Error::<T>::TooEarlyForCommunityRoundStart);
ensure!(
project_details.status == ProjectStatus::AuctionRound(AuctionPhase::Candle),
Error::<T>::ProjectNotInCandleAuctionRound
);
// * Calculate new variables *
let end_block = Self::select_random_block(auction_candle_start_block, auction_candle_end_block);
let community_start_block = now + 1u32.into();
let community_end_block = now + T::CommunityFundingDuration::get();
// * Update Storage *
let calculation_result =
Self::calculate_weighted_average_price(project_id, end_block, project_metadata.total_allocation_size.0);
let mut project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
match calculation_result {
Err(pallet_error) if pallet_error == Error::<T>::NoBidsFound.into() => {
project_details.status = ProjectStatus::FundingFailed;
ProjectsDetails::<T>::insert(project_id, project_details);
let insertion_iterations = match Self::add_to_update_store(
<frame_system::Pallet<T>>::block_number() + 1u32.into(),
(&project_id, UpdateType::FundingEnd),
) {
Ok(iterations) => iterations,
Err(_iterations) => return Err(Error::<T>::TooManyInsertionAttempts.into()),
};
// * Emit events *
Self::deposit_event(Event::AuctionFailed { project_id });
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_community_funding_failure(insertion_iterations)),
pays_fee: Pays::Yes,
})
},
Err(e) => return Err(DispatchErrorWithPostInfo { post_info: ().into(), error: e }),
Ok((accepted_bids_count, rejected_bids_count)) => {
// Get info again after updating it with new price.
project_details.phase_transition_points.random_candle_ending = Some(end_block);
project_details
.phase_transition_points
.community
.update(Some(community_start_block), Some(community_end_block));
project_details.status = ProjectStatus::CommunityRound;
ProjectsDetails::<T>::insert(project_id, project_details);
let insertion_iterations = match Self::add_to_update_store(
community_end_block + 1u32.into(),
(&project_id, UpdateType::RemainderFundingStart),
) {
Ok(iterations) => iterations,
Err(_iterations) => return Err(Error::<T>::TooManyInsertionAttempts.into()),
};
// * Emit events *
Self::deposit_event(Event::CommunityFundingStarted { project_id });
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_community_funding_success(
insertion_iterations,
accepted_bids_count,
rejected_bids_count,
)),
pays_fee: Pays::Yes,
})
},
}
}
/// Called automatically by on_initialize
/// Starts the remainder round for a project.
/// Anyone can now buy tokens, until they are all sold out, or the time is reached.
///
/// # Arguments
/// * `project_id` - The project identifier
///
/// # Storage access
/// * [`ProjectsDetails`] - Get the project information, and check if the project is in the correct
/// round, the current block is after the community funding end period, and there are still tokens left to sell.
/// Update the project information with the new round status and transition points in case of success.
///
/// # Success Path
/// The validity checks pass, and the project is transitioned to the Remainder Funding round.
/// The project is scheduled to be transitioned automatically by `on_initialize` at the end of the
/// round.
///
/// # Next step
/// Any users can now buy tokens at the price set on the auction round.
/// Later on, `on_initialize` ends the remainder round, and finalizes the project funding, by calling
/// [`do_end_funding`](Self::do_end_funding).
pub fn do_remainder_funding(project_id: ProjectId) -> DispatchResultWithPostInfo {
// * Get variables *
let mut project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let now = <frame_system::Pallet<T>>::block_number();
let community_end_block =
project_details.phase_transition_points.community.end().ok_or(Error::<T>::FieldIsNone)?;
// * Validity checks *
ensure!(now > community_end_block, Error::<T>::TooEarlyForRemainderRoundStart);
ensure!(project_details.status == ProjectStatus::CommunityRound, Error::<T>::ProjectNotInCommunityRound);
// Transition to remainder round was initiated by `do_community_funding`, but the ct
// tokens where already sold in the community round. This transition is obsolete.
ensure!(
project_details
.remaining_contribution_tokens
.0
.saturating_add(project_details.remaining_contribution_tokens.1) >
0u32.into(),
Error::<T>::RoundTransitionAlreadyHappened
);
// * Calculate new variables *
let remainder_start_block = now + 1u32.into();
let remainder_end_block = now + T::RemainderFundingDuration::get();
// * Update Storage *
project_details
.phase_transition_points
.remainder
.update(Some(remainder_start_block), Some(remainder_end_block));
project_details.status = ProjectStatus::RemainderRound;
ProjectsDetails::<T>::insert(project_id, project_details);
// Schedule for automatic transition by `on_initialize`
let insertion_iterations =
match Self::add_to_update_store(remainder_end_block + 1u32.into(), (&project_id, UpdateType::FundingEnd)) {
Ok(iterations) => iterations,
Err(_iterations) => return Err(Error::<T>::TooManyInsertionAttempts.into()),
};
// * Emit events *
Self::deposit_event(Event::RemainderFundingStarted { project_id });
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_remainder_funding(insertion_iterations)),
pays_fee: Pays::Yes,
})
}
/// Called automatically by on_initialize
/// Ends the project funding, and calculates if the project was successfully funded or not.
///
/// # Arguments
/// * `project_id` - The project identifier
///
/// # Storage access
/// * [`ProjectsDetails`] - Get the project information, and check if the project is in the correct
/// round, the current block is after the remainder funding end period.
/// Update the project information with the new round status.
///
/// # Success Path
/// The validity checks pass, and either of 2 paths happen:
///
/// * Project achieves its funding target - the project info is set to a successful funding state,
/// and the contribution token asset class is created with the same id as the project.
///
/// * Project doesn't achieve its funding target - the project info is set to an unsuccessful funding state.
///
/// # Next step
/// If **successful**, bidders can claim:
/// * Contribution tokens with [`vested_contribution_token_bid_mint_for`](Self::vested_contribution_token_bid_mint_for)
/// * Bonded plmc with [`vested_plmc_bid_unbond_for`](Self::vested_plmc_bid_unbond_for)
///
/// And contributors can claim:
/// * Contribution tokens with [`vested_contribution_token_purchase_mint_for`](Self::vested_contribution_token_purchase_mint_for)
/// * Bonded plmc with [`vested_plmc_purchase_unbond_for`](Self::vested_plmc_purchase_unbond_for)
///
/// If **unsuccessful**, users every user should have their PLMC vesting unbonded.
pub fn do_end_funding(project_id: ProjectId) -> DispatchResultWithPostInfo {
// * Get variables *
let mut project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let project_metadata = ProjectsMetadata::<T>::get(project_id).ok_or(Error::<T>::ProjectNotFound)?;
let remaining_cts = project_details
.remaining_contribution_tokens
.0
.saturating_add(project_details.remaining_contribution_tokens.1);
let remainder_end_block = project_details.phase_transition_points.remainder.end();
let now = <frame_system::Pallet<T>>::block_number();
// * Validity checks *
ensure!(
remaining_cts == Zero::zero() ||
project_details.status == ProjectStatus::FundingFailed ||
matches!(remainder_end_block, Some(end_block) if now > end_block),
Error::<T>::TooEarlyForFundingEnd
);
// do_end_funding was already executed, but automatic transition was included in the
// do_remainder_funding function. We gracefully skip the this transition.
ensure!(
!matches!(
project_details.status,
ProjectStatus::FundingSuccessful |
ProjectStatus::FundingFailed |
ProjectStatus::AwaitingProjectDecision
),
Error::<T>::RoundTransitionAlreadyHappened
);
// * Calculate new variables *
let funding_target = project_metadata
.minimum_price
.checked_mul_int(
project_metadata.total_allocation_size.0.saturating_add(project_metadata.total_allocation_size.1),
)
.ok_or(Error::<T>::BadMath)?;
let funding_reached = project_details.funding_amount_reached;
let funding_ratio = Perquintill::from_rational(funding_reached, funding_target);
// * Update Storage *
if funding_ratio <= Perquintill::from_percent(33u64) {
project_details.evaluation_round_info.evaluators_outcome = EvaluatorsOutcome::Slashed;
let insertion_iterations = Self::make_project_funding_fail(
project_id,
project_details,
FailureReason::TargetNotReached,
1u32.into(),
)?;
return Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::end_funding_automatically_rejected_evaluators_slashed(
insertion_iterations,
)),
pays_fee: Pays::Yes,
});
} else if funding_ratio <= Perquintill::from_percent(75u64) {
project_details.evaluation_round_info.evaluators_outcome = EvaluatorsOutcome::Slashed;
project_details.status = ProjectStatus::AwaitingProjectDecision;
let insertion_iterations = match Self::add_to_update_store(
now + T::ManualAcceptanceDuration::get() + 1u32.into(),
(&project_id, UpdateType::ProjectDecision(FundingOutcomeDecision::AcceptFunding)),
) {
Ok(iterations) => iterations,
Err(_iterations) => return Err(Error::<T>::TooManyInsertionAttempts.into()),
};
ProjectsDetails::<T>::insert(project_id, project_details);
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::end_funding_awaiting_decision_evaluators_slashed(
insertion_iterations,
)),
pays_fee: Pays::Yes,
})
} else if funding_ratio < Perquintill::from_percent(90u64) {
project_details.evaluation_round_info.evaluators_outcome = EvaluatorsOutcome::Unchanged;
project_details.status = ProjectStatus::AwaitingProjectDecision;
let insertion_iterations = match Self::add_to_update_store(
now + T::ManualAcceptanceDuration::get() + 1u32.into(),
(&project_id, UpdateType::ProjectDecision(FundingOutcomeDecision::AcceptFunding)),
) {
Ok(iterations) => iterations,
Err(_iterations) => return Err(Error::<T>::TooManyInsertionAttempts.into()),
};
ProjectsDetails::<T>::insert(project_id, project_details);
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::end_funding_awaiting_decision_evaluators_unchanged(
insertion_iterations,
)),
pays_fee: Pays::Yes,
})
} else {
let (reward_info, evaluations_count) = Self::generate_evaluator_rewards_info(project_id)?;
project_details.evaluation_round_info.evaluators_outcome = EvaluatorsOutcome::Rewarded(reward_info);
let insertion_iterations = Self::make_project_funding_successful(
project_id,
project_details,
SuccessReason::ReachedTarget,
T::SuccessToSettlementTime::get(),
)?;
return Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::end_funding_automatically_accepted_evaluators_rewarded(
insertion_iterations,
evaluations_count,
)),
pays_fee: Pays::Yes,
});
}
}
pub fn do_project_decision(project_id: ProjectId, decision: FundingOutcomeDecision) -> DispatchResultWithPostInfo {
// * Get variables *
let project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
ensure!(
project_details.status == ProjectStatus::AwaitingProjectDecision,
Error::<T>::RoundTransitionAlreadyHappened
);
// * Update storage *
match decision {
FundingOutcomeDecision::AcceptFunding => {
Self::make_project_funding_successful(
project_id,
project_details,
SuccessReason::ProjectDecision,
T::SuccessToSettlementTime::get(),
)?;
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::project_decision_accept_funding()),
pays_fee: Pays::Yes,
})
},
FundingOutcomeDecision::RejectFunding => {
Self::make_project_funding_fail(
project_id,
project_details,
FailureReason::ProjectDecision,
T::SuccessToSettlementTime::get(),
)?;
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::project_decision_reject_funding()),
pays_fee: Pays::Yes,
})
},
}
}
pub fn do_start_settlement(project_id: ProjectId) -> DispatchResultWithPostInfo {
// * Get variables *
let mut project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let token_information =
ProjectsMetadata::<T>::get(project_id).ok_or(Error::<T>::ProjectNotFound)?.token_information;
let now = <frame_system::Pallet<T>>::block_number();
// * Validity checks *
ensure!(
project_details.status == ProjectStatus::FundingSuccessful ||
project_details.status == ProjectStatus::FundingFailed,
Error::<T>::NotAllowed
);
// * Calculate new variables *
project_details.cleanup =
Cleaner::try_from(project_details.status.clone()).map_err(|_| Error::<T>::NotAllowed)?;
project_details.funding_end_block = Some(now);
// * Update storage *
ProjectsDetails::<T>::insert(project_id, &project_details);
let escrow_account = Self::fund_account_id(project_id);
if project_details.status == ProjectStatus::FundingSuccessful {
T::ContributionTokenCurrency::create(project_id, escrow_account.clone(), false, 1_u32.into())?;
T::ContributionTokenCurrency::set(
project_id,
&escrow_account.clone(),
token_information.name.into(),
token_information.symbol.into(),
token_information.decimals,
)?;
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_settlement_funding_success()),
pays_fee: Pays::Yes,
})
} else {
Ok(PostDispatchInfo {
actual_weight: Some(WeightInfoOf::<T>::start_settlement_funding_failure()),
pays_fee: Pays::Yes,
})
}
}
}
// Extrinsics and HRMP interactions
impl<T: Config> Pallet<T> {
/// Change the metadata hash of a project
///
/// # Arguments
/// * `issuer` - The project issuer account
/// * `project_id` - The project identifier
/// * `project_metadata_hash` - The hash of the image that contains the metadata
///
/// # Storage access
/// * [`ProjectsIssuers`] - Check that the issuer is the owner of the project
/// * [`Images`] - Check that the image exists
/// * [`ProjectsDetails`] - Check that the project is not frozen
/// * [`ProjectsMetadata`] - Update the metadata hash
pub fn do_edit_metadata(
issuer: AccountIdOf<T>,
project_id: ProjectId,
project_metadata_hash: T::Hash,
) -> DispatchResult {
// * Get variables *
let mut project_metadata = ProjectsMetadata::<T>::get(project_id).ok_or(Error::<T>::ProjectNotFound)?;
let project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
// * Validity checks *
ensure!(project_details.issuer == issuer, Error::<T>::NotAllowed);
ensure!(!project_details.is_frozen, Error::<T>::Frozen);
ensure!(!Images::<T>::contains_key(project_metadata_hash), Error::<T>::MetadataAlreadyExists);
// * Calculate new variables *
// * Update Storage *
project_metadata.offchain_information_hash = Some(project_metadata_hash);
ProjectsMetadata::<T>::insert(project_id, project_metadata);
// * Emit events *
Self::deposit_event(Event::MetadataEdited { project_id });
Ok(())
}
// Note: usd_amount needs to have the same amount of decimals as PLMC, so when multiplied by the plmc-usd price, it gives us the PLMC amount with the decimals we wanted.
pub fn do_evaluate(
evaluator: &AccountIdOf<T>,
project_id: ProjectId,
usd_amount: BalanceOf<T>,
) -> DispatchResultWithPostInfo {
// * Get variables *
let mut project_details = ProjectsDetails::<T>::get(project_id).ok_or(Error::<T>::ProjectDetailsNotFound)?;
let now = <frame_system::Pallet<T>>::block_number();
let evaluation_id = Self::next_evaluation_id();
let caller_existing_evaluations: Vec<(u32, EvaluationInfoOf<T>)> =
Evaluations::<T>::iter_prefix((project_id, evaluator)).collect();
let plmc_usd_price = T::PriceProvider::get_price(PLMC_FOREIGN_ID).ok_or(Error::<T>::PLMCPriceNotAvailable)?;
let early_evaluation_reward_threshold_usd =
T::EvaluationSuccessThreshold::get() * project_details.fundraising_target;
let evaluation_round_info = &mut project_details.evaluation_round_info;
let ct_deposit = T::ContributionTokenCurrency::deposit_required(project_id);
let evaluations_count = EvaluationCounts::<T>::get(project_id);
// * Validity Checks *
ensure!(evaluator.clone() != project_details.issuer, Error::<T>::ContributionToThemselves);
ensure!(project_details.status == ProjectStatus::EvaluationRound, Error::<T>::EvaluationNotStarted);
ensure!(evaluations_count < T::MaxEvaluationsPerProject::get(), Error::<T>::TooManyEvaluationsForProject);
// * Calculate new variables *
let plmc_bond = plmc_usd_price
.reciprocal()
.ok_or(Error::<T>::BadMath)?
.checked_mul_int(usd_amount)
.ok_or(Error::<T>::BadMath)?;
let previous_total_evaluation_bonded_usd = evaluation_round_info.total_bonded_usd;
let remaining_bond_to_reach_threshold =
early_evaluation_reward_threshold_usd.saturating_sub(previous_total_evaluation_bonded_usd);
let early_usd_amount = if usd_amount <= remaining_bond_to_reach_threshold {
usd_amount
} else {
remaining_bond_to_reach_threshold
};
let late_usd_amount = usd_amount.checked_sub(&early_usd_amount).ok_or(Error::<T>::BadMath)?;
let new_evaluation = EvaluationInfoOf::<T> {
id: evaluation_id,
project_id,
evaluator: evaluator.clone(),
original_plmc_bond: plmc_bond,
current_plmc_bond: plmc_bond,
early_usd_amount,
late_usd_amount,
when: now,
rewarded_or_slashed: None,
ct_migration_status: MigrationStatus::NotStarted,
};
// * Update Storage *
// Reserve plmc deposit to create a contribution token account for this project
if T::NativeCurrency::balance_on_hold(&HoldReason::FutureDeposit(project_id).into(), evaluator) < ct_deposit {
T::NativeCurrency::hold(&HoldReason::FutureDeposit(project_id).into(), evaluator, ct_deposit)?;
}
if caller_existing_evaluations.len() < T::MaxEvaluationsPerUser::get() as usize {
T::NativeCurrency::hold(&HoldReason::Evaluation(project_id).into(), evaluator, plmc_bond)?;
} else {
let (low_id, lowest_evaluation) = caller_existing_evaluations
.iter()
.min_by_key(|(_, evaluation)| evaluation.original_plmc_bond)
.ok_or(Error::<T>::ImpossibleState)?;
ensure!(lowest_evaluation.original_plmc_bond < plmc_bond, Error::<T>::EvaluationBondTooLow);
ensure!(
lowest_evaluation.original_plmc_bond == lowest_evaluation.current_plmc_bond,
"Using evaluation funds for participating should not be possible in the evaluation round"
);
T::NativeCurrency::release(
&HoldReason::Evaluation(project_id).into(),
&lowest_evaluation.evaluator,
lowest_evaluation.original_plmc_bond,
Precision::Exact,
)?;
T::NativeCurrency::hold(&HoldReason::Evaluation(project_id).into(), evaluator, plmc_bond)?;
Evaluations::<T>::remove((project_id, evaluator, low_id));
EvaluationCounts::<T>::mutate(project_id, |c| *c -= 1);
}
Evaluations::<T>::insert((project_id, evaluator, evaluation_id), new_evaluation);
NextEvaluationId::<T>::set(evaluation_id.saturating_add(One::one()));
evaluation_round_info.total_bonded_usd += usd_amount;