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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
// Copyright (C) 2020 Mangata team

#![cfg_attr(not(feature = "std"), no_std)]

//! # Bootstrap Module
//!
//! The Bootstrap module provides price discovery mechanism between two tokens. When bootstrap
//! is finished all provisioned tokens are collected and used for new liquidity token(pool) creation.
//! From that moment people that participated in bootstrap can claim their liquidity tokens share using
//! dedicated. Also since that moment its possible to exchange/trade tokens that were bootstraped using `Xyk `pallet.
//!
//!
//! ### Features
//!
//! * Bootstrap pallet is reusable** - after bootstrap between tokens `X` and `Y` is finished the following one can be scheduled (with different pair of tokens).
//! * After bootstrap is finished new liquidity token (`Z`) is created and [`pallet_xyk`] can be used to:
//!        * exchange/trade `X` and `Y` tokens
//!        * mint/burn `Z` tokens
//!
//! * Bootstrap state transition from [`BeforeStart`] -> [`Finished`] happens automatically thanks to substrate framework
//! hooks. **Only transition from `Finished` -> `BeforeStart` needs to be triggered manually because
//! cleaning up storage is complex operation and might not fit in a single block.(as it needs to
//! remove a lot of keys/value pair from the runtime storage)**
//!
//! # How to bootstrap
//! 1. Entity with sudo privileges needs to use [`Pallet::schedule_bootstrap`] to initiate new bootstrap
//!
//! 1.1 [**optional**] depending on fact if [`BootstrapPhase::Whitelist`] is enabled entity
//!   with sudo privileges can whitelist particular users using [`Pallet::whitelist_accounts`]
//!
//! 1.2 [**optional**] [`Pallet::update_promote_bootstrap_pool`] can be used to enable or disable
//!   automatic pool promotion of liquidity pool.
//!
//! 1.3 [**optional**] [`Pallet::cancel_bootstrap`] can be used to cancel bootstrap event
//!
//! 2. When blockchain reaches block that is scheduled as start od the bootstrap participation is
//!    automatically enabled:
//!    * in [`BootstrapPhase::Whitelist`] phase only whitelisted accounts [`Pallet::whitelist_accounts`]
//!    can participate
//!    * in [`BootstrapPhase::Public`] phase everyone can participate
//!
//! 3. When blockchain reaches block:
//! ```ignore
//!  current_block_nr > bootstrap_start_block + whitelist_phase_length + public_phase_length
//! ```
//!
//! Bootstrap is automatically finished and following participations will not be accepted. Also new
//! liquidity pool is created from all the tokens gathered during bootstrap (see [`Valuations`]). `TokenId`
//! of newly created liquidity token as well as amount of minted tokens is persisted into [`MintedLiquidity`]
//! storage item. All the liquidity token minted as a result of pool creation are now stored in
//! bootstrap pallet account.
//!
//! 4. Accounts that participated in bootstrap can claim their liquidity pool share. Share is
//!    calculated proportionally based on provisioned amount. One can use one of below extrinsics to
//!    claim rewards:
//!    * [`Pallet::claim_liquidity_tokens`]
//!    * [`Pallet::claim_and_activate_liquidity_tokens`]
//!
//! 5. When every participant of the bootstrap has claimed their liquidity tokens entity with sudo
//!    rights can [`Pallet::finalize`] whole bootstrap event. If there are some accounts that still
//!    hasnt claim their tokens [`Pallet::claim_liquidity_tokens_for_account`] can be used to do
//!    that in behalf of these accounts. When [`Pallet::finalize`] results with [`Event::BootstrapFinalized`]
//!    Bootstrap is finalized and another bootstrap can be scheduled (as described in 1st point).
//!
//! Bootstrap has specific lifecycle as presented below:
//! ```plantuml
//! @startuml
//! [*] --> BeforeStart
//! BeforeStart --> Whitelist
//! BeforeStart --> Public
//! Whitelist --> Public
//! Public --> Finished
//! Finished --> BeforeStart
//! @enduml
//! ```
//!
//! # API
//!
//! ## Runtime Storage Entries
//!
//! - [`Provisions`] - stores information about who provisioned what (non vested tokens)
//!
//! - [`VestedProvisions`] - stores information about who provisioned what (vested tokens)
//!
//! - [`WhitelistedAccount`] - list of accounts allowed to participate in [`BootstrapPhase::Whitelist`]
//!
//! - [`Phase`] - current state of bootstrap
//!
//! - [`Valuations`] - sum of all provisions in active bootstrap
//!
//! - [`BootstrapSchedule`] - parameters of active bootstrap stored as for more details check [`Pallet::schedule_bootstrap`]
//!
//!  ```ignore
//!  [
//!            block_nr: T::BlockNumber,
//!            first_token_id: u32,
//!            second_token_id: u32,
//!            [
//!                    ratio_numerator:u128,
//!                    ratio_denominator:u128
//!            ]
//!  ]
//!  ```
//!
//! - [`ClaimedRewards`] - how many liquidity tokens has user already **after** bootstrap
//! [`BootstrapPhase::Public`] period has finished.
//!
//! - [`ProvisionAccounts`] - list of participants that hasnt claim their tokens yet
//!
//! - [`ActivePair`] - bootstraped pair of tokens
//!
//! ## Extrinsics
//!
//! * [`Pallet::schedule_bootstrap`]
//! * [`Pallet::whitelist_accounts`]
//! * [`Pallet::update_promote_bootstrap_pool`]
//! * [`Pallet::cancel_bootstrap`]
//! * [`Pallet::provision`]
//! * [`Pallet::claim_liquidity_tokens`]
//! * [`Pallet::claim_liquidity_tokens_for_account`]
//! * [`Pallet::claim_and_activate_liquidity_tokens`]
//! * [`Pallet::finalize`]
//!
//! for more details see [click](#how-to-bootstrap)
//!
//!
use frame_support::pallet_prelude::*;

use codec::{Decode, Encode};
use frame_support::{
	traits::{
		Contains, ExistenceRequirement, Get, MultiTokenCurrency, MultiTokenVestingLocks,
		StorageVersion,
	},
	transactional, PalletId,
};
use frame_system::{ensure_root, ensure_signed, pallet_prelude::*};

use mangata_support::traits::{
	AssetRegistryApi, GetMaintenanceStatusTrait, PoolCreateApi, ProofOfStakeRewardsApi,
};
use mangata_types::multipurpose_liquidity::ActivateKind;

use orml_tokens::{MultiTokenCurrencyExtended, MultiTokenReservableCurrency};
use scale_info::TypeInfo;
use sp_arithmetic::{helpers_128bit::multiply_by_rational_with_rounding, per_things::Rounding};
use sp_core::U256;
use sp_io::KillStorageResult;
use sp_runtime::traits::{
	AccountIdConversion, Bounded, CheckedAdd, One, SaturatedConversion, Saturating, Zero,
};
use sp_std::{convert::TryInto, prelude::*};

#[cfg(test)]
mod mock;

mod benchmarking;

#[cfg(test)]
mod tests;

pub mod weights;
pub use weights::WeightInfo;

pub use pallet::*;
const PALLET_ID: PalletId = PalletId(*b"bootstrp");

#[macro_export]
macro_rules! log {
	($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
		log::$level!(
			target: "bootstrap",
			concat!("[{:?}] 💸 ", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
		)
	};
}

type BalanceOf<T> = <<T as Config>::Currency as MultiTokenCurrency<
	<T as frame_system::Config>::AccountId,
>>::Balance;

type CurrencyIdOf<T> = <<T as Config>::Currency as MultiTokenCurrency<
	<T as frame_system::Config>::AccountId,
>>::CurrencyId;

type BlockNrAsBalance<T> = BalanceOf<T>;

#[frame_support::pallet]
pub mod pallet {
	use super::*;

	const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);

	#[pallet::pallet]
	#[pallet::without_storage_info]
	#[pallet::storage_version(STORAGE_VERSION)]
	pub struct Pallet<T>(PhantomData<T>);

	#[pallet::hooks]
	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
		fn on_initialize(n: BlockNumberFor<T>) -> Weight {
			let phase = Phase::<T>::get(); // R:1
			if phase == BootstrapPhase::Finished {
				return T::DbWeight::get().reads(1)
			}

			if let Some((start, whitelist_length, public_length, _)) = BootstrapSchedule::<T>::get()
			{
				// R:1
				// NOTE: arythmetics protected by invariant check in Bootstrap::start_ido
				let whitelist_start = start;
				let public_start = start + whitelist_length.into();
				let finished = start + whitelist_length.into() + public_length.into();

				if n >= finished {
					Phase::<T>::put(BootstrapPhase::Finished); // 1 WRINTE
					log!(info, "bootstrap event finished");
					let (second_token_valuation, first_token_valuation) = Valuations::<T>::get();

					// one updated takes R:2, W:2; and multiply for two assets
					if !T::AssetRegistryApi::enable_pool_creation((
						Self::first_token_id(),
						Self::second_token_id(),
					)) {
						log!(error, "cannot modify asset registry!");
					}
					// XykFunctionsTrait R: 11 W:12
					// PoolCreateApi::pool_create R:2  +
					// ---------------------------------
					// R: 13 W 12
					if let Some((liq_asset_id, issuance)) = T::PoolCreateApi::pool_create(
						Self::vault_address(),
						Self::first_token_id(),
						first_token_valuation,
						Self::second_token_id(),
						second_token_valuation,
					) {
						MintedLiquidity::<T>::put((liq_asset_id, issuance)); // W:1
						if PromoteBootstrapPool::<T>::get() {
							T::RewardsApi::enable(
								liq_asset_id,
								T::DefaultBootstrapPromotedPoolWeight::get(),
							);
						}
					} else {
						log!(error, "cannot create pool!");
					}
					// TODO: include cost of pool_create call
					T::DbWeight::get().reads_writes(21, 18)
				} else if n >= public_start {
					if phase != BootstrapPhase::Public {
						Phase::<T>::put(BootstrapPhase::Public);
						log!(info, "starting public phase");
						T::DbWeight::get().reads_writes(2, 1)
					} else {
						T::DbWeight::get().reads(2)
					}
				} else if n >= whitelist_start {
					if phase != BootstrapPhase::Whitelist {
						log!(info, "starting whitelist phase");
						Phase::<T>::put(BootstrapPhase::Whitelist);
						T::DbWeight::get().reads_writes(2, 1)
					} else {
						T::DbWeight::get().reads(2)
					}
				} else {
					T::DbWeight::get().reads(2)
				}
			} else {
				T::DbWeight::get().reads(2)
			}
		}
	}

	#[cfg(feature = "runtime-benchmarks")]
	pub trait BootstrapBenchmarkingConfig {}

	#[cfg(not(feature = "runtime-benchmarks"))]
	pub trait BootstrapBenchmarkingConfig {}

	/// Configure the pallet by specifying the parameters and types on which it depends.
	#[pallet::config]
	pub trait Config: frame_system::Config + BootstrapBenchmarkingConfig {
		/// Because this pallet emits events, it depends on the runtime's definition of an event.
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

		type MaintenanceStatusProvider: GetMaintenanceStatusTrait;

		/// tokens
		type Currency: MultiTokenCurrencyExtended<Self::AccountId>
			+ MultiTokenReservableCurrency<Self::AccountId>;

		type PoolCreateApi: PoolCreateApi<Self::AccountId, BalanceOf<Self>, CurrencyIdOf<Self>>;

		#[pallet::constant]
		type DefaultBootstrapPromotedPoolWeight: Get<u8>;

		#[pallet::constant]
		type BootstrapUpdateBuffer: Get<BlockNumberFor<Self>>;

		#[pallet::constant]
		type TreasuryPalletId: Get<PalletId>;

		type VestingProvider: MultiTokenVestingLocks<
			Self::AccountId,
			Currency = Self::Currency,
			Moment = BlockNumberFor<Self>,
		>;

		type ClearStorageLimit: Get<u32>;

		type WeightInfo: WeightInfo;

		type RewardsApi: ProofOfStakeRewardsApi<
			Self::AccountId,
			BalanceOf<Self>,
			CurrencyIdOf<Self>,
		>;

		type AssetRegistryApi: AssetRegistryApi<CurrencyIdOf<Self>>;
	}

	/// maps ([`frame_system::Config::AccountId`], [`CurrencyId`]) -> [`Balance`] - identifies how much tokens did account provisioned in active bootstrap
	#[pallet::storage]
	#[pallet::getter(fn provisions)]
	pub type Provisions<T: Config> = StorageDoubleMap<
		_,
		Twox64Concat,
		T::AccountId,
		Twox64Concat,
		CurrencyIdOf<T>,
		BalanceOf<T>,
		ValueQuery,
	>;

	/// maps ([`frame_system::Config::AccountId`], [`CurrencyId`]) -> [`Balance`] - identifies how much vested tokens did account provisioned in active bootstrap
	#[pallet::storage]
	#[pallet::getter(fn vested_provisions)]
	pub type VestedProvisions<T: Config> = StorageDoubleMap<
		_,
		Twox64Concat,
		T::AccountId,
		Twox64Concat,
		CurrencyIdOf<T>,
		(BalanceOf<T>, BlockNrAsBalance<T>, BlockNrAsBalance<T>),
		ValueQuery,
	>;

	/// list ([`Vec<AccountId>`]) of whitelisted accounts allowed to participate in [`BootstrapPhase::Whitelist`] phase
	#[pallet::storage]
	#[pallet::getter(fn whitelisted_accounts)]
	pub type WhitelistedAccount<T: Config> =
		StorageMap<_, Twox64Concat, T::AccountId, (), ValueQuery>;

	/// Current state of bootstrap as [`BootstrapPhase`]
	#[pallet::storage]
	#[pallet::getter(fn phase)]
	pub type Phase<T: Config> = StorageValue<_, BootstrapPhase, ValueQuery>;

	/// Total sum of provisions of `first` and `second` token in active bootstrap
	#[pallet::storage]
	#[pallet::getter(fn valuations)]
	pub type Valuations<T: Config> = StorageValue<_, (BalanceOf<T>, BalanceOf<T>), ValueQuery>;

	/// Active bootstrap parameters
	#[pallet::storage]
	#[pallet::getter(fn config)]
	pub type BootstrapSchedule<T: Config> =
		StorageValue<_, (BlockNumberFor<T>, u32, u32, (BalanceOf<T>, BalanceOf<T>)), OptionQuery>;

	#[pallet::storage]
	#[pallet::getter(fn minted_liquidity)]
	pub type MintedLiquidity<T: Config> =
		StorageValue<_, (CurrencyIdOf<T>, BalanceOf<T>), ValueQuery>;

	///  Maps ([`frame_system::Config::AccountId`], [`CurrencyId`] ) -> [`Balance`] - where [`CurrencyId`] is id of the token that user participated with. This storage item is used to identify how much liquidity tokens has been claim by the user. If user participated with 2 tokens there are two entries associated with given account (`Address`, `first_token_id`) and (`Address`, `second_token_id`)
	#[pallet::storage]
	#[pallet::getter(fn claimed_rewards)]
	pub type ClaimedRewards<T: Config> = StorageDoubleMap<
		_,
		Twox64Concat,
		T::AccountId,
		Twox64Concat,
		CurrencyIdOf<T>,
		BalanceOf<T>,
		ValueQuery,
	>;

	/// List of accounts that provisioned funds to bootstrap and has not claimed liquidity tokens yet
	#[pallet::storage]
	#[pallet::getter(fn provision_accounts)]
	pub type ProvisionAccounts<T: Config> =
		StorageMap<_, Twox64Concat, T::AccountId, (), OptionQuery>;

	/// Currently bootstraped pair of tokens representaed as [ `first_token_id`, `second_token_id`]
	#[pallet::storage]
	#[pallet::getter(fn pair)]
	pub type ActivePair<T: Config> =
		StorageValue<_, (CurrencyIdOf<T>, CurrencyIdOf<T>), OptionQuery>;

	/// Wheter to automatically promote the pool after [`BootstrapPhase::PublicPhase`] or not.
	#[pallet::storage]
	#[pallet::getter(fn get_promote_bootstrap_pool)]
	pub type PromoteBootstrapPool<T: Config> = StorageValue<_, bool, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn archived)]
	pub type ArchivedBootstrap<T: Config> = StorageValue<
		_,
		Vec<(BlockNumberFor<T>, u32, u32, (BalanceOf<T>, BalanceOf<T>))>,
		ValueQuery,
	>;

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		// /// provisions vested/locked tokens into the boostrstrap
		// #[pallet::weight(<<T as Config>::WeightInfo>::provision_vested())]
		// #[transactional]
		// pub fn provision_vested(
		// 	origin: OriginFor<T>,
		// 	token_id: TokenId,
		// 	amount: Balance,
		// ) -> DispatchResult {
		// 	let sender = ensure_signed(origin)?;
		//
		// ensure!(!T::MaintenanceStatusProvider::is_maintenance(), Error::<T>::ProvisioningBlockedByMaintenanceMode);
		//
		// 	let (vesting_starting_block, vesting_ending_block_as_balance) =
		// 		<<T as Config>::VestingProvider>::unlock_tokens(
		// 			&sender,
		// 			token_id.into(),
		// 			amount.into(),
		// 		)
		// 		.map_err(|_| Error::<T>::NotEnoughVestedAssets)?;
		// 	Self::do_provision(
		// 		&sender,
		// 		token_id,
		// 		amount,
		// 		ProvisionKind::Vested(
		// 			vesting_starting_block.saturated_into::<BlockNrAsBalance>(),
		// 			vesting_ending_block_as_balance.into(),
		// 		),
		// 	)?;
		// 	ProvisionAccounts::<T>::insert(&sender, ());
		// 	Self::deposit_event(Event::Provisioned(token_id, amount));
		// 	Ok(().into())
		// }

		/// Allows for provisioning one of the tokens from currently bootstrapped pair. Can only be called during:
		/// - [`BootstrapPhase::Whitelist`]
		/// - [`BootstrapPhase::Public`]
		///
		/// phases.
		///
		/// # Args:
		///  - `token_id` - id of the token to provision (should be one of the currently bootstraped pair([`ActivePair`]))
		///  - `amount` - amount of the token to provision
		#[pallet::call_index(0)]
		#[pallet::weight(<<T as Config>::WeightInfo>::provision())]
		#[transactional]
		pub fn provision(
			origin: OriginFor<T>,
			token_id: CurrencyIdOf<T>,
			amount: BalanceOf<T>,
		) -> DispatchResult {
			let sender = ensure_signed(origin)?;

			ensure!(
				!T::MaintenanceStatusProvider::is_maintenance(),
				Error::<T>::ProvisioningBlockedByMaintenanceMode
			);

			Self::do_provision(&sender, token_id, amount)?;
			ProvisionAccounts::<T>::insert(&sender, ());
			Self::deposit_event(Event::Provisioned(token_id, amount));
			Ok(())
		}

		/// Allows for whitelisting accounts, so they can participate in during whitelist phase. The list of
		/// account is extended with every subsequent call
		#[pallet::call_index(1)]
		#[pallet::weight(T::DbWeight::get().writes(1) * (accounts.len() as u64))]
		#[transactional]
		pub fn whitelist_accounts(
			origin: OriginFor<T>,
			accounts: Vec<T::AccountId>,
		) -> DispatchResult {
			ensure_root(origin)?;
			for account in accounts {
				WhitelistedAccount::<T>::insert(&account, ());
			}
			Self::deposit_event(Event::AccountsWhitelisted);
			Ok(())
		}

		/// Used for starting/scheduling new bootstrap
		///
		/// # Args:
		/// - `first_token_id` - first token of the tokens pair
		/// - `second_token_id`: second token of the tokens pair
		/// - `ido_start` - number of block when bootstrap will be started (people will be allowed to participate)
		/// - `whitelist_phase_length`: - length of whitelist phase
		/// - `public_phase_lenght`- length of public phase
		/// - `promote_bootstrap_pool`- whether liquidity pool created by bootstrap should be promoted
		/// - `max_first_to_second_ratio` - represented as (numerator,denominator) - Ratio may be used to limit participations of second token id. Ratio between first and second token needs to be held during whole bootstrap. Whenever user tries to participate (using [`Pallet::provision`] extrinsic) the following conditions is check.
		/// ```ignore
		/// all previous first participations + first token participations             ratio numerator
		/// ----------------------------------------------------------------------- <= ------------------
		/// all previous second token participations + second token participations     ratio denominator
		/// ```
		/// and if it evaluates to `false` extrinsic will fail.
		///
		/// **Because of above equation only participations with first token of a bootstrap pair are limited!**
		///
		/// # Examples
		/// Consider:
		///
		/// - user willing to participate 1000 of first token, when:
		/// 	- ratio set during bootstrap schedule is is set to (1/2)
		/// 	- sum of first token participations - 10_000
		/// 	- sum of second token participations - 20_000
		///
		/// participation extrinsic will **fail** because ratio condition **is not met**
		/// ```ignore
		/// 10_000 + 10_000      1
		/// --------------- <=  ---
		///     20_000           2
		/// ```
		///
		/// - user willing to participate 1000 of first token, when:
		/// 	- ratio set during bootstrap schedule is is set to (1/2)
		/// 	- sum of first token participations - 10_000
		/// 	- sum of second token participations - 40_000
		///
		/// participation extrinsic will **succeed** because ratio condition **is met**
		/// ```ignore
		/// 10_000 + 10_000      1
		/// --------------- <=  ---
		///     40_000           2
		/// ```
		///
		///
		/// **If one doesn't want to limit participations in any way, ratio should be set to (u128::MAX,0) - then ratio requirements are always met**
		///
		/// ```ignore
		/// all previous first participations + first token participations                u128::MAX
		/// ----------------------------------------------------------------------- <= ------------------
		/// all previous second token participations + second token participations            1
		/// ```
		#[pallet::call_index(2)]
		#[pallet::weight(<<T as Config>::WeightInfo>::schedule_bootstrap())]
		#[transactional]
		pub fn schedule_bootstrap(
			origin: OriginFor<T>,
			first_token_id: CurrencyIdOf<T>,
			second_token_id: CurrencyIdOf<T>,
			ido_start: BlockNumberFor<T>,
			whitelist_phase_length: Option<u32>,
			public_phase_length: u32,
			max_first_to_second_ratio: Option<(BalanceOf<T>, BalanceOf<T>)>,
			promote_bootstrap_pool: bool,
		) -> DispatchResult {
			ensure_root(origin)?;

			ensure!(Phase::<T>::get() == BootstrapPhase::BeforeStart, Error::<T>::AlreadyStarted);

			if let Some((scheduled_ido_start, _, _, _)) = BootstrapSchedule::<T>::get() {
				let now = <frame_system::Pallet<T>>::block_number();
				ensure!(
					now.saturating_add(T::BootstrapUpdateBuffer::get()) < scheduled_ido_start,
					Error::<T>::TooLateToUpdateBootstrap
				);
			}

			ensure!(first_token_id != second_token_id, Error::<T>::SameToken);

			ensure!(T::Currency::exists(first_token_id.into()), Error::<T>::TokenIdDoesNotExists);
			ensure!(T::Currency::exists(second_token_id.into()), Error::<T>::TokenIdDoesNotExists);

			ensure!(
				ido_start > frame_system::Pallet::<T>::block_number(),
				Error::<T>::BootstrapStartInThePast
			);

			let whitelist_phase_length = whitelist_phase_length.unwrap_or_default();
			let max_first_to_second_ratio = max_first_to_second_ratio
				.unwrap_or((BalanceOf::<T>::max_value(), BalanceOf::<T>::one()));

			ensure!(max_first_to_second_ratio.0 != BalanceOf::<T>::zero(), Error::<T>::WrongRatio);

			ensure!(max_first_to_second_ratio.1 != BalanceOf::<T>::zero(), Error::<T>::WrongRatio);

			ensure!(public_phase_length > 0, Error::<T>::PhaseLengthCannotBeZero);

			ensure!(
				ido_start
					.checked_add(&whitelist_phase_length.into())
					.and_then(|whiteslist_start| whiteslist_start
						.checked_add(&public_phase_length.into()))
					.is_some(),
				Error::<T>::MathOverflow
			);

			ensure!(
				ido_start.checked_add(&whitelist_phase_length.into()).is_some(),
				Error::<T>::MathOverflow
			);

			ensure!(
				!T::PoolCreateApi::pool_exists(first_token_id, second_token_id),
				Error::<T>::PoolAlreadyExists
			);

			ActivePair::<T>::put((first_token_id, second_token_id));
			BootstrapSchedule::<T>::put((
				ido_start,
				whitelist_phase_length,
				public_phase_length,
				max_first_to_second_ratio,
			));

			PromoteBootstrapPool::<T>::put(promote_bootstrap_pool);

			Ok(())
		}

		/// Used to cancel active bootstrap. Can only be called before bootstrap is actually started
		#[pallet::call_index(3)]
		#[pallet::weight(T::DbWeight::get().reads_writes(3, 4).saturating_add(Weight::from_parts(1_000_000, 0)))]
		#[transactional]
		pub fn cancel_bootstrap(origin: OriginFor<T>) -> DispatchResult {
			ensure_root(origin)?;

			// BootstrapSchedule should exist but not after BootstrapUpdateBuffer blocks before start

			let now = <frame_system::Pallet<T>>::block_number();
			let (ido_start, _, _, _) =
				BootstrapSchedule::<T>::get().ok_or(Error::<T>::BootstrapNotSchduled)?;
			ensure!(Phase::<T>::get() == BootstrapPhase::BeforeStart, Error::<T>::AlreadyStarted);

			ensure!(
				now.saturating_add(T::BootstrapUpdateBuffer::get()) < ido_start,
				Error::<T>::TooLateToUpdateBootstrap
			);

			ActivePair::<T>::kill();
			BootstrapSchedule::<T>::kill();
			PromoteBootstrapPool::<T>::kill();
			// Unnecessary
			Phase::<T>::put(BootstrapPhase::BeforeStart);

			Ok(())
		}

		#[pallet::call_index(4)]
		#[pallet::weight(T::DbWeight::get().reads_writes(2, 1).saturating_add(Weight::from_parts(1_000_000, 0)))]
		#[transactional]
		// can be used to enable or disable automatic pool promotion of liquidity pool. Updates [`PromoteBootstrapPool`]
		pub fn update_promote_bootstrap_pool(
			origin: OriginFor<T>,
			promote_bootstrap_pool: bool,
		) -> DispatchResult {
			ensure_root(origin)?;

			// BootstrapSchedule should exist but not finalized
			// we allow this to go thru if the BootstrapSchedule exists and the phase is before finalized

			ensure!(BootstrapSchedule::<T>::get().is_some(), Error::<T>::BootstrapNotSchduled);
			ensure!(Phase::<T>::get() != BootstrapPhase::Finished, Error::<T>::BootstrapFinished);

			PromoteBootstrapPool::<T>::put(promote_bootstrap_pool);

			Ok(())
		}

		/// When bootstrap is in [`BootstrapPhase::Finished`] state user can claim his part of liquidity tokens.
		#[pallet::call_index(5)]
		#[pallet::weight(<<T as Config>::WeightInfo>::claim_and_activate_liquidity_tokens())]
		#[transactional]
		pub fn claim_liquidity_tokens(origin: OriginFor<T>) -> DispatchResult {
			let sender = ensure_signed(origin)?;
			Self::do_claim_liquidity_tokens(&sender, false)
		}

		/// When bootstrap is in [`BootstrapPhase::Finished`] state user can claim his part of liquidity tokens comparing to `claim_liquidity_tokens` when calling `claim_and_activate_liquidity_tokens` tokens will be automatically activated.
		#[pallet::call_index(6)]
		#[pallet::weight(<<T as Config>::WeightInfo>::claim_and_activate_liquidity_tokens())]
		#[transactional]
		pub fn claim_and_activate_liquidity_tokens(origin: OriginFor<T>) -> DispatchResult {
			let sender = ensure_signed(origin)?;
			Self::do_claim_liquidity_tokens(&sender, true)
		}

		/// Used to reset Bootstrap state of large storages and prepare it for running another bootstrap.
		/// It should be called multiple times until it produces [`Event::BootstrapReadyToBeFinalized`] event.
		///
		/// **!!! Cleaning up storage is complex operation and pruning all storage items related to particular
		/// bootstrap might not fit in a single block. As a result tx can be rejected !!!**
		#[pallet::call_index(7)]
		#[pallet::weight(Weight::from_parts(40_000_000, 0)
							.saturating_add(T::DbWeight::get().reads_writes(6, 0)
								.saturating_add(T::DbWeight::get().reads_writes(1, 1).saturating_mul(Into::<u64>::into(T::ClearStorageLimit::get())))))]
		#[transactional]
		pub fn pre_finalize(origin: OriginFor<T>) -> DispatchResult {
			let _ = ensure_signed(origin)?;

			ensure!(Self::phase() == BootstrapPhase::Finished, Error::<T>::NotFinishedYet);

			ensure!(
				ProvisionAccounts::<T>::iter_keys().next().is_none(),
				Error::<T>::BootstrapNotReadyToBeFinished
			);

			let mut limit = T::ClearStorageLimit::get();

			match VestedProvisions::<T>::clear(limit, None).into() {
				KillStorageResult::AllRemoved(num_iter) => limit = limit.saturating_sub(num_iter),
				KillStorageResult::SomeRemaining(_) => {
					Self::deposit_event(Event::BootstrapParitallyPreFinalized);
					return Ok(())
				},
			}

			match WhitelistedAccount::<T>::clear(limit, None).into() {
				KillStorageResult::AllRemoved(num_iter) => limit = limit.saturating_sub(num_iter),
				KillStorageResult::SomeRemaining(_) => {
					Self::deposit_event(Event::BootstrapParitallyPreFinalized);
					return Ok(())
				},
			}

			match ClaimedRewards::<T>::clear(limit, None).into() {
				KillStorageResult::AllRemoved(num_iter) => limit = limit.saturating_sub(num_iter),
				KillStorageResult::SomeRemaining(_) => {
					Self::deposit_event(Event::BootstrapParitallyPreFinalized);
					return Ok(())
				},
			}

			match Provisions::<T>::clear(limit, None).into() {
				KillStorageResult::AllRemoved(num_iter) => limit = limit.saturating_sub(num_iter),
				KillStorageResult::SomeRemaining(_) => {
					Self::deposit_event(Event::BootstrapParitallyPreFinalized);
					return Ok(())
				},
			}

			Self::deposit_event(Event::BootstrapReadyToBeFinalized);

			Ok(())
		}

		/// Used to complete resetting Bootstrap state and prepare it for running another bootstrap.
		/// It should be called after pre_finalize has produced the [`Event::BootstrapReadyToBeFinalized`] event.
		#[pallet::call_index(8)]
		#[pallet::weight(<<T as Config>::WeightInfo>::finalize())]
		#[transactional]
		pub fn finalize(origin: OriginFor<T>) -> DispatchResult {
			let _ = ensure_signed(origin)?;

			ensure!(Self::phase() == BootstrapPhase::Finished, Error::<T>::NotFinishedYet);

			ensure!(
				ProvisionAccounts::<T>::iter_keys().next().is_none(),
				Error::<T>::BootstrapNotReadyToBeFinished
			);

			ensure!(
				VestedProvisions::<T>::iter_keys().next().is_none(),
				Error::<T>::BootstrapMustBePreFinalized
			);

			ensure!(
				WhitelistedAccount::<T>::iter_keys().next().is_none(),
				Error::<T>::BootstrapMustBePreFinalized
			);

			ensure!(
				ClaimedRewards::<T>::iter_keys().next().is_none(),
				Error::<T>::BootstrapMustBePreFinalized
			);

			ensure!(
				Provisions::<T>::iter_keys().next().is_none(),
				Error::<T>::BootstrapMustBePreFinalized
			);

			Phase::<T>::put(BootstrapPhase::BeforeStart);
			let (liq_token_id, _) = MintedLiquidity::<T>::take();
			let balance = T::Currency::free_balance(liq_token_id.into(), &Self::vault_address());
			if balance > 0_u32.into() {
				T::Currency::transfer(
					liq_token_id.into(),
					&Self::vault_address(),
					&T::TreasuryPalletId::get().into_account_truncating(),
					balance,
					ExistenceRequirement::AllowDeath,
				)?;
			}
			Valuations::<T>::kill();
			ActivePair::<T>::kill();
			PromoteBootstrapPool::<T>::kill();

			if let Some(bootstrap) = BootstrapSchedule::<T>::take() {
				ArchivedBootstrap::<T>::mutate(|v| {
					v.push(bootstrap);
				});
			}

			Self::deposit_event(Event::BootstrapFinalized);

			Ok(())
		}

		/// Allows claiming rewards for some account that haven't done that yet. The only difference between
		/// calling [`Pallet::claim_liquidity_tokens_for_account`] by some other account and calling [`Pallet::claim_liquidity_tokens`] directly by that account is account that will be charged for transaction fee.
		/// # Args:
		/// - `other` - account in behalf of which liquidity tokens should be claimed
		#[pallet::call_index(9)]
		#[pallet::weight(<<T as Config>::WeightInfo>::claim_and_activate_liquidity_tokens())]
		#[transactional]
		pub fn claim_liquidity_tokens_for_account(
			origin: OriginFor<T>,
			account: T::AccountId,
			activate_rewards: bool,
		) -> DispatchResult {
			let _ = ensure_signed(origin)?;
			Self::do_claim_liquidity_tokens(&account, activate_rewards)
		}
	}

	#[pallet::error]
	/// Errors
	pub enum Error<T> {
		/// Only scheduled token pair can be used for provisions
		UnsupportedTokenId,
		/// Not enough funds for provision
		NotEnoughAssets,
		/// Not enough funds for provision (vested)
		NotEnoughVestedAssets,
		/// Math problem
		MathOverflow,
		/// User cannot participate at this moment
		Unauthorized,
		/// Bootstrap cant be scheduled in past
		BootstrapStartInThePast,
		/// Bootstarap phases cannot lasts 0 blocks
		PhaseLengthCannotBeZero,
		/// Bootstrate event already started
		AlreadyStarted,
		/// Valuation ratio exceeded
		ValuationRatio,
		/// First provision must be in non restricted token
		FirstProvisionInSecondTokenId,
		/// Bootstraped pool already exists
		PoolAlreadyExists,
		/// Cannot claim rewards before bootstrap finish
		NotFinishedYet,
		/// no rewards to claim
		NothingToClaim,
		/// wrong ratio
		WrongRatio,
		/// no rewards to claim
		BootstrapNotReadyToBeFinished,
		/// Tokens used in bootstrap cannot be the same
		SameToken,
		/// Token does not exists
		TokenIdDoesNotExists,
		/// Token activations failed
		TokensActivationFailed,
		/// Bootstrap not scheduled
		BootstrapNotSchduled,
		/// Bootstrap already Finished
		BootstrapFinished,
		/// Bootstrap can only be updated or cancelled
		/// BootstrapUpdateBuffer blocks or more before bootstrap start
		TooLateToUpdateBootstrap,
		/// Bootstrap provisioning blocked by maintenance mode
		ProvisioningBlockedByMaintenanceMode,
		/// Bootstrap must be pre finalized before it can be finalized
		BootstrapMustBePreFinalized,
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
	pub enum Event<T: Config> {
		/// Funds provisioned
		Provisioned(CurrencyIdOf<T>, BalanceOf<T>),
		/// Funds provisioned using vested tokens
		VestedProvisioned(CurrencyIdOf<T>, BalanceOf<T>),
		/// The activation of the rewards liquidity tokens failed
		RewardsLiquidityAcitvationFailed(T::AccountId, CurrencyIdOf<T>, BalanceOf<T>),
		/// Rewards claimed
		RewardsClaimed(CurrencyIdOf<T>, BalanceOf<T>),
		/// account whitelisted
		AccountsWhitelisted,
		/// bootstrap pre finalization has completed partially
		BootstrapParitallyPreFinalized,
		/// bootstrap pre finalization has completed, and the bootstrap can now be finalized
		BootstrapReadyToBeFinalized,
		/// finalization process finished
		BootstrapFinalized,
	}
}

#[derive(Eq, PartialEq, Encode, Decode, TypeInfo, Debug)]
pub enum BootstrapPhase {
	/// Waiting for another bootstrap to be scheduled using [`Pallet::schedule_bootstrap`]
	BeforeStart,
	// Phase where only whitelisted accounts (see [`Bootstrap::whitelist_accounts`]) can participate with both tokens as long as particular accounts are whitelisted and ratio after participation is below enforced ratio.
	Whitelist,
	/// Anyone can participate as long as ratio after participation is below enforced ratio
	Public,
	/// Bootstrap has finished. At this phase users that participated in bootstrap during previous phases can claim their share of minted `liquidity tokens`. `Bootstrap::finalize` can be call to reset pallet state schedule following bootstrap again.
	Finished,
}

impl Default for BootstrapPhase {
	fn default() -> Self {
		BootstrapPhase::BeforeStart
	}
}

impl<T: Config> Pallet<T> {
	fn is_whitelisted(account: &T::AccountId) -> bool {
		WhitelistedAccount::<T>::try_get(account).is_ok()
	}

	fn vault_address() -> T::AccountId {
		PALLET_ID.into_account_truncating()
	}

	fn claim_liquidity_tokens_from_single_currency(
		who: &T::AccountId,
		provision_token_id: &CurrencyIdOf<T>,
		rewards: BalanceOf<T>,
		rewards_vested: BalanceOf<T>,
		lock: (BlockNrAsBalance<T>, BlockNrAsBalance<T>),
	) -> DispatchResult {
		let (liq_token_id, _) = Self::minted_liquidity();
		let total_rewards = rewards.checked_add(&rewards_vested).ok_or(Error::<T>::MathOverflow)?;
		if total_rewards == BalanceOf::<T>::zero() {
			return Ok(())
		}

		T::Currency::transfer(
			liq_token_id.into(),
			&Self::vault_address(),
			who,
			total_rewards,
			ExistenceRequirement::KeepAlive,
		)?;

		ClaimedRewards::<T>::try_mutate(who, provision_token_id, |rewards| {
			if let Some(val) = rewards.checked_add(&total_rewards) {
				*rewards = val;
				Ok(())
			} else {
				Err(Error::<T>::MathOverflow)
			}
		})?;

		if rewards_vested > BalanceOf::<T>::zero() {
			T::VestingProvider::lock_tokens(
				who,
				liq_token_id,
				rewards_vested,
				Some(lock.0.into().saturated_into()),
				lock.1,
			)?;
		}

		Ok(())
	}

	///
	/// assures that
	///
	/// actual_nominator              expected_nominator
	/// --------------------   <=     ------------------
	/// actual_denominator            expected_denominator
	///
	/// actual_nominator * expected_denominator     expected_nominator * actual_denominator
	/// ---------------------------------------- <= ----------------------------------------
	/// actual_denominator * expected_denominator    expected_denominator * actual_nominator
	fn is_ratio_kept(ratio_nominator: BalanceOf<T>, ratio_denominator: BalanceOf<T>) -> bool {
		let (second_token_valuation, first_token_valuation) = Valuations::<T>::get();
		let left = U256::from(first_token_valuation.into()) * U256::from(ratio_denominator.into());
		let right = U256::from(ratio_nominator.into()) * U256::from(second_token_valuation.into());
		left <= right
	}

	pub fn do_provision(
		sender: &T::AccountId,
		token_id: CurrencyIdOf<T>,
		amount: BalanceOf<T>,
		// is_vested: ProvisionKind,
	) -> DispatchResult {
		let is_first_token = token_id == Self::first_token_id();
		let is_second_token = token_id == Self::second_token_id();
		let is_public_phase = Phase::<T>::get() == BootstrapPhase::Public;
		let is_whitelist_phase = Phase::<T>::get() == BootstrapPhase::Whitelist;
		let am_i_whitelisted = Self::is_whitelisted(sender);

		ensure!(is_first_token || is_second_token, Error::<T>::UnsupportedTokenId);

		ensure!(
			is_public_phase || (is_whitelist_phase && (am_i_whitelisted || is_second_token)),
			Error::<T>::Unauthorized
		);

		let schedule = BootstrapSchedule::<T>::get();
		ensure!(schedule.is_some(), Error::<T>::Unauthorized);
		let (_, _, _, (ratio_nominator, ratio_denominator)) = schedule.unwrap();

		<T as Config>::Currency::transfer(
			token_id.into(),
			sender,
			&Self::vault_address(),
			amount,
			ExistenceRequirement::KeepAlive,
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		// match is_vested {
		// 	ProvisionKind::Regular => {
		ensure!(
			Provisions::<T>::try_mutate(sender, token_id, |provision| {
				if let Some(val) = provision.checked_add(&amount) {
					*provision = val;
					Ok(())
				} else {
					Err(())
				}
			})
			.is_ok(),
			Error::<T>::MathOverflow
		);
		/*
					 },
					ProvisionKind::Vested(provision_start_block, provision_end_block) => {
						ensure!(
							VestedProvisions::<T>::try_mutate(
								sender,
								token_id,
								|(provision, start_block, end_block)| {
									if let Some(val) = provision.checked_add(amount) {
										*provision = val;
										*start_block = (*start_block).max(provision_start_block);
										*end_block = (*end_block).max(provision_end_block);
										Ok(())
									} else {
										Err(())
									}
								}
							)
							.is_ok(),
							Error::<T>::MathOverflow
						);
					},
			}
		*/
		let (pre_second_token_valuation, _) = Valuations::<T>::get();
		ensure!(
			token_id != Self::first_token_id() ||
				pre_second_token_valuation != BalanceOf::<T>::zero(),
			Error::<T>::FirstProvisionInSecondTokenId
		);

		ensure!(
			Valuations::<T>::try_mutate(
				|(second_token_valuation, first_token_valuation)| -> Result<(), ()> {
					if token_id == Self::second_token_id() {
						*second_token_valuation =
							second_token_valuation.checked_add(&amount).ok_or(())?;
					}
					if token_id == Self::first_token_id() {
						*first_token_valuation =
							first_token_valuation.checked_add(&amount).ok_or(())?;
					}
					Ok(())
				}
			)
			.is_ok(),
			Error::<T>::MathOverflow
		);

		if token_id == Self::first_token_id() {
			ensure!(
				Self::is_ratio_kept(ratio_nominator, ratio_denominator),
				Error::<T>::ValuationRatio
			);
		}
		Ok(())
	}

	fn get_valuation(token_id: &CurrencyIdOf<T>) -> BalanceOf<T> {
		if *token_id == Self::first_token_id() {
			Self::valuations().1
		} else if *token_id == Self::second_token_id() {
			Self::valuations().0
		} else {
			BalanceOf::<T>::zero()
		}
	}

	fn calculate_rewards(
		who: &T::AccountId,
		token_id: &CurrencyIdOf<T>,
	) -> Result<(BalanceOf<T>, BalanceOf<T>, (BlockNrAsBalance<T>, BlockNrAsBalance<T>)), Error<T>>
	{
		let valuation = Self::get_valuation(token_id);
		let provision = Self::provisions(who, token_id);
		let (vested_provision, lock_start, lock_end) = Self::vested_provisions(who, token_id);
		let (_, liquidity) = Self::minted_liquidity();
		let rewards = multiply_by_rational_with_rounding(
			liquidity.into() / 2,
			provision.into(),
			valuation.into(),
			Rounding::Down,
		)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let vested_rewards = multiply_by_rational_with_rounding(
			liquidity.into() / 2,
			vested_provision.into(),
			valuation.into(),
			Rounding::Down,
		)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		Ok((rewards, vested_rewards, (lock_start, lock_end)))
	}

	fn do_claim_liquidity_tokens(who: &T::AccountId, activate_rewards: bool) -> DispatchResult {
		ensure!(Self::phase() == BootstrapPhase::Finished, Error::<T>::NotFinishedYet);

		let (liq_token_id, _) = Self::minted_liquidity();

		// for backward compatibility
		if !Self::archived().is_empty() {
			ensure!(ProvisionAccounts::<T>::get(who).is_some(), Error::<T>::NothingToClaim);
		} else {
			ensure!(
				!ClaimedRewards::<T>::contains_key(&who, &Self::first_token_id()),
				Error::<T>::NothingToClaim
			);
			ensure!(
				!ClaimedRewards::<T>::contains_key(&who, &Self::second_token_id()),
				Error::<T>::NothingToClaim
			);
		}

		let (first_token_rewards, first_token_rewards_vested, first_token_lock) =
			Self::calculate_rewards(who, &Self::first_token_id())?;
		let (second_token_rewards, second_token_rewards_vested, second_token_lock) =
			Self::calculate_rewards(who, &Self::second_token_id())?;

		let total_rewards_claimed = second_token_rewards
			.checked_add(&second_token_rewards_vested)
			.ok_or(Error::<T>::MathOverflow)?
			.checked_add(&first_token_rewards)
			.ok_or(Error::<T>::MathOverflow)?
			.checked_add(&first_token_rewards_vested)
			.ok_or(Error::<T>::MathOverflow)?;

		Self::claim_liquidity_tokens_from_single_currency(
			who,
			&Self::second_token_id(),
			second_token_rewards,
			second_token_rewards_vested,
			second_token_lock,
		)?;
		log!(
			info,
			"Second token rewards (non-vested, vested) = ({:?}, {:?})",
			second_token_rewards,
			second_token_rewards_vested,
		);

		Self::claim_liquidity_tokens_from_single_currency(
			who,
			&Self::first_token_id(),
			first_token_rewards,
			first_token_rewards_vested,
			first_token_lock,
		)?;
		log!(
			info,
			"First token rewards (non-vested, vested) = ({:?}, {:?})",
			first_token_rewards,
			first_token_rewards_vested,
		);

		ProvisionAccounts::<T>::remove(who);

		if activate_rewards && <T as Config>::RewardsApi::is_enabled(liq_token_id) {
			let non_vested_rewards = second_token_rewards
				.checked_add(&first_token_rewards)
				.ok_or(Error::<T>::MathOverflow)?;
			if non_vested_rewards > BalanceOf::<T>::zero() {
				let activate_result = <T as Config>::RewardsApi::activate_liquidity(
					who.clone(),
					liq_token_id,
					non_vested_rewards,
					Some(ActivateKind::AvailableBalance),
				);
				if let Err(err) = activate_result {
					log!(
						error,
						"Activating liquidity tokens failed upon bootstrap claim rewards = ({:?}, {:?}, {:?}, {:?})",
						who,
						liq_token_id,
						non_vested_rewards,
						err
					);

					Self::deposit_event(Event::RewardsLiquidityAcitvationFailed(
						who.clone(),
						liq_token_id,
						non_vested_rewards,
					));
				};
			}
		}

		Self::deposit_event(Event::RewardsClaimed(liq_token_id, total_rewards_claimed));

		Ok(())
	}

	fn first_token_id() -> CurrencyIdOf<T> {
		ActivePair::<T>::get().map(|(first, _)| first).unwrap_or(4_u32.into())
	}

	fn second_token_id() -> CurrencyIdOf<T> {
		ActivePair::<T>::get().map(|(_, second)| second).unwrap_or(0_u32.into())
	}
}

impl<T: Config> Contains<(CurrencyIdOf<T>, CurrencyIdOf<T>)> for Pallet<T> {
	fn contains(pair: &(CurrencyIdOf<T>, CurrencyIdOf<T>)) -> bool {
		pair == &(Self::first_token_id(), Self::second_token_id()) ||
			pair == &(Self::second_token_id(), Self::first_token_id())
	}
}