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
// This file is part of Basilisk-node.

// Copyright (C) 2020-2022  Intergalactic, Limited (GIB).
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! # XYK Pallet
//!
//! ## Overview
//!
//! XYK pallet provides functionality for managing liquidity pool and executing trades.
//!
//! This pallet implements AMM Api trait therefore it is possible to plug this pool implementation
//! into the exchange pallet.

#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
#![allow(clippy::upper_case_acronyms)]

use frame_support::sp_runtime::{traits::Zero, DispatchError};
use frame_support::{dispatch::DispatchResult, ensure, traits::Get, transactional};
use frame_system::ensure_signed;
use hydradx_traits::{
	AMMPosition, AMMTransfer, AssetPairAccountIdFor, CanCreatePool, OnCreatePoolHandler, OnLiquidityChangedHandler,
	OnTradeHandler, Source, AMM,
};
use primitives::{asset::AssetPair, AssetId, Balance};
use sp_std::{vec, vec::Vec};

use orml_traits::{MultiCurrency, MultiCurrencyExtended};
use primitives::Amount;

#[cfg(test)]
mod tests;

mod benchmarking;

mod impls;
mod trade_execution;
pub mod weights;

pub use impls::XYKSpotPrice;

use weights::WeightInfo;

/// Oracle source identifier for this pallet.
pub const SOURCE: Source = *b"snek/xyk";

// Re-export pallet items so that they can be accessed from the crate namespace.
pub use pallet::*;

#[frame_support::pallet]
pub mod pallet {
	use super::*;
	use frame_support::pallet_prelude::*;
	use frame_system::pallet_prelude::OriginFor;
	use hydradx_traits::{pools::DustRemovalAccountWhitelist, registry::ShareTokenRegistry};

	#[pallet::pallet]
	pub struct Pallet<T>(_);

	#[pallet::hooks]
	impl<T: Config> Hooks<T::BlockNumber> for Pallet<T> {}

	#[pallet::config]
	pub trait Config: frame_system::Config {
		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;

		/// Registry support
		type AssetRegistry: ShareTokenRegistry<AssetId, Vec<u8>, Balance, DispatchError>;

		/// Share token support
		type AssetPairAccountId: AssetPairAccountIdFor<AssetId, Self::AccountId>;

		/// Multi currency for transfer of currencies
		type Currency: MultiCurrencyExtended<Self::AccountId, CurrencyId = AssetId, Balance = Balance, Amount = Amount>;

		/// Native Asset Id
		#[pallet::constant]
		type NativeAssetId: Get<AssetId>;

		/// Weight information for the extrinsics.
		type WeightInfo: WeightInfo;

		/// Trading fee rate
		#[pallet::constant]
		type GetExchangeFee: Get<(u32, u32)>;

		/// Minimum trading limit
		#[pallet::constant]
		type MinTradingLimit: Get<Balance>;

		/// Minimum pool liquidity
		#[pallet::constant]
		type MinPoolLiquidity: Get<Balance>;

		/// Max fraction of pool to sell in single transaction
		#[pallet::constant]
		type MaxInRatio: Get<u128>;

		/// Max fraction of pool to buy in single transaction
		#[pallet::constant]
		type MaxOutRatio: Get<u128>;

		/// Called to ensure that pool can be created
		type CanCreatePool: CanCreatePool<AssetId>;

		/// AMM handlers
		type AMMHandler: OnCreatePoolHandler<AssetId>
			+ OnTradeHandler<AssetId, Balance>
			+ OnLiquidityChangedHandler<AssetId, Balance>;

		/// Discounted fee
		type DiscountedFee: Get<(u32, u32)>;

		/// Account whitelist manager to exclude pool accounts from dusting mechanism.
		type NonDustableWhitelistHandler: DustRemovalAccountWhitelist<Self::AccountId, Error = DispatchError>;
	}

	#[pallet::error]
	pub enum Error<T> {
		/// It is not allowed to create a pool between same assets.
		CannotCreatePoolWithSameAssets,

		/// Liquidity has not reached the required minimum.
		InsufficientLiquidity,

		/// Amount is less than min trading limit.
		InsufficientTradingAmount,

		/// Liquidity is zero.
		ZeroLiquidity,

		/// It is not allowed to create a pool with zero initial price.
		/// Not used, kept for backward compatibility
		ZeroInitialPrice,

		/// Overflow
		/// Not used, kept for backward compatibility
		CreatePoolAssetAmountInvalid,

		/// Overflow
		InvalidMintedLiquidity, // No tests - but it is currently not possible this error to occur due to previous checks in the code.

		/// Overflow
		InvalidLiquidityAmount, // no tests - it is currently not possible this error to occur due to previous checks in the code.

		/// Asset amount has exceeded given limit.
		AssetAmountExceededLimit,

		/// Asset amount has not reached given limit.
		AssetAmountNotReachedLimit,

		/// Asset balance is not sufficient.
		InsufficientAssetBalance,

		/// Not enough asset liquidity in the pool.
		InsufficientPoolAssetBalance,

		/// Not enough core asset liquidity in the pool.
		InsufficientNativeCurrencyBalance,

		/// Liquidity pool for given assets does not exist.
		TokenPoolNotFound,

		/// Liquidity pool for given assets already exists.
		TokenPoolAlreadyExists,

		/// Overflow
		AddAssetAmountInvalid, // no tests
		/// Overflow
		RemoveAssetAmountInvalid, // no tests
		/// Overflow
		SellAssetAmountInvalid, // no tests
		/// Overflow
		BuyAssetAmountInvalid, // no tests

		/// Overflow
		FeeAmountInvalid,

		/// Overflow
		CannotApplyDiscount,

		/// Max fraction of pool to buy in single transaction has been exceeded.
		MaxOutRatioExceeded,
		/// Max fraction of pool to sell in single transaction has been exceeded.
		MaxInRatioExceeded,

		/// Overflow
		Overflow,

		/// Pool cannot be created due to outside factors.
		CannotCreatePool,
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(crate) fn deposit_event)]
	pub enum Event<T: Config> {
		/// New liquidity was provided to the pool.
		LiquidityAdded {
			who: T::AccountId,
			asset_a: AssetId,
			asset_b: AssetId,
			amount_a: Balance,
			amount_b: Balance,
		},

		/// Liquidity was removed from the pool.
		LiquidityRemoved {
			who: T::AccountId,
			asset_a: AssetId,
			asset_b: AssetId,
			shares: Balance,
		},

		/// Pool was created.
		PoolCreated {
			who: T::AccountId,
			asset_a: AssetId,
			asset_b: AssetId,
			initial_shares_amount: Balance,
			share_token: AssetId,
			pool: T::AccountId,
		},

		/// Pool was destroyed.
		PoolDestroyed {
			who: T::AccountId,
			asset_a: AssetId,
			asset_b: AssetId,
			share_token: AssetId,
			pool: T::AccountId,
		},

		/// Asset sale executed.
		SellExecuted {
			who: T::AccountId,
			asset_in: AssetId,
			asset_out: AssetId,
			amount: Balance,
			sale_price: Balance,
			fee_asset: AssetId,
			fee_amount: Balance,
			pool: T::AccountId,
		},

		/// Asset purchase executed.
		BuyExecuted {
			who: T::AccountId,
			asset_out: AssetId,
			asset_in: AssetId,
			amount: Balance,
			buy_price: Balance,
			fee_asset: AssetId,
			fee_amount: Balance,
			pool: T::AccountId,
		},
	}

	/// Asset id storage for shared pool tokens
	#[pallet::storage]
	#[pallet::getter(fn share_token)]
	pub(crate) type ShareToken<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, AssetId, ValueQuery>;

	/// Total liquidity in a pool.
	#[pallet::storage]
	#[pallet::getter(fn total_liquidity)]
	pub(crate) type TotalLiquidity<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, Balance, ValueQuery>;

	/// Asset pair in a pool.
	#[pallet::storage]
	#[pallet::getter(fn pool_assets)]
	pub(crate) type PoolAssets<T: Config> =
		StorageMap<_, Blake2_128Concat, T::AccountId, (AssetId, AssetId), OptionQuery>;

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// Create new pool for given asset pair.
		///
		/// Registers new pool for given asset pair (`asset a` and `asset b`) in asset registry.
		/// Asset registry creates new id or returns previously created one if such pool existed before.
		///
		/// Pool is created with initial liquidity provided by `origin`.
		/// Shares are issued with specified initial price and represents proportion of asset in the pool.
		///
		/// Emits `PoolCreated` event when successful.
		#[pallet::weight(<T as Config>::WeightInfo::create_pool())]
		pub fn create_pool(
			origin: OriginFor<T>,
			asset_a: AssetId,
			amount_a: Balance,
			asset_b: AssetId,
			amount_b: Balance,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;

			ensure!(
				T::CanCreatePool::can_create(asset_a, asset_b),
				Error::<T>::CannotCreatePool
			);

			ensure!(
				amount_a >= T::MinPoolLiquidity::get() && amount_b >= T::MinPoolLiquidity::get(),
				Error::<T>::InsufficientLiquidity
			);

			ensure!(asset_a != asset_b, Error::<T>::CannotCreatePoolWithSameAssets);

			let asset_pair = AssetPair {
				asset_in: asset_a,
				asset_out: asset_b,
			};

			ensure!(!Self::exists(asset_pair), Error::<T>::TokenPoolAlreadyExists);

			let shares_added = if asset_a < asset_b { amount_a } else { amount_b };

			ensure!(
				T::Currency::free_balance(asset_a, &who) >= amount_a,
				Error::<T>::InsufficientAssetBalance
			);

			ensure!(
				T::Currency::free_balance(asset_b, &who) >= amount_b,
				Error::<T>::InsufficientAssetBalance
			);

			let pair_account = Self::get_pair_id(asset_pair);

			let token_name = asset_pair.name();

			let share_token = T::AssetRegistry::get_or_create_shared_asset(
				token_name,
				vec![asset_a, asset_b],
				T::MinPoolLiquidity::get(),
			)?;

			let _ = T::AMMHandler::on_create_pool(asset_pair.asset_in, asset_pair.asset_out);

			T::NonDustableWhitelistHandler::add_account(&pair_account)?;

			<ShareToken<T>>::insert(&pair_account, share_token);
			<PoolAssets<T>>::insert(&pair_account, (asset_a, asset_b));

			Self::deposit_event(Event::PoolCreated {
				who: who.clone(),
				asset_a,
				asset_b,
				initial_shares_amount: shares_added,
				share_token,
				pool: pair_account.clone(),
			});

			T::Currency::transfer(asset_a, &who, &pair_account, amount_a)?;
			T::Currency::transfer(asset_b, &who, &pair_account, amount_b)?;

			T::Currency::deposit(share_token, &who, shares_added)?;

			<TotalLiquidity<T>>::insert(&pair_account, shares_added);

			Ok(())
		}

		/// Add liquidity to previously created asset pair pool.
		///
		/// Shares are issued with current price.
		///
		/// Emits `LiquidityAdded` event when successful.
		#[pallet::weight(
			<T as Config>::WeightInfo::add_liquidity()
				.saturating_add(T::AMMHandler::on_liquidity_changed_weight())
		)]
		#[transactional]
		pub fn add_liquidity(
			origin: OriginFor<T>,
			asset_a: AssetId,
			asset_b: AssetId,
			amount_a: Balance,
			amount_b_max_limit: Balance,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;

			let asset_pair = AssetPair {
				asset_in: asset_a,
				asset_out: asset_b,
			};

			ensure!(Self::exists(asset_pair), Error::<T>::TokenPoolNotFound);

			ensure!(
				amount_a >= T::MinTradingLimit::get(),
				Error::<T>::InsufficientTradingAmount
			);

			ensure!(!amount_b_max_limit.is_zero(), Error::<T>::ZeroLiquidity);

			ensure!(
				T::Currency::free_balance(asset_a, &who) >= amount_a,
				Error::<T>::InsufficientAssetBalance
			);

			let pair_account = Self::get_pair_id(asset_pair);

			let share_token = Self::share_token(&pair_account);

			let account_shares = T::Currency::free_balance(share_token, &who);

			let asset_a_reserve = T::Currency::free_balance(asset_a, &pair_account);
			let asset_b_reserve = T::Currency::free_balance(asset_b, &pair_account);
			let share_issuance = Self::total_liquidity(&pair_account);

			let amount_b = hydra_dx_math::xyk::calculate_liquidity_in(asset_a_reserve, asset_b_reserve, amount_a)
				.map_err(|_| Error::<T>::AddAssetAmountInvalid)?;

			ensure!(
				T::Currency::free_balance(asset_b, &who) >= amount_b,
				Error::<T>::InsufficientAssetBalance
			);

			ensure!(amount_b <= amount_b_max_limit, Error::<T>::AssetAmountExceededLimit);

			let shares_added = hydra_dx_math::xyk::calculate_shares(asset_a_reserve, amount_a, share_issuance)
				.ok_or(Error::<T>::Overflow)?;

			ensure!(!shares_added.is_zero(), Error::<T>::InvalidMintedLiquidity);

			// Make sure that account share liquidity is at least MinPoolLiquidity
			ensure!(
				account_shares
					.checked_add(shares_added)
					.ok_or(Error::<T>::InvalidMintedLiquidity)?
					>= T::MinPoolLiquidity::get(),
				Error::<T>::InsufficientLiquidity
			);

			let liquidity_amount = share_issuance
				.checked_add(shares_added)
				.ok_or(Error::<T>::InvalidLiquidityAmount)?;

			T::Currency::transfer(asset_a, &who, &pair_account, amount_a)?;
			T::Currency::transfer(asset_b, &who, &pair_account, amount_b)?;

			T::Currency::deposit(share_token, &who, shares_added)?;

			<TotalLiquidity<T>>::insert(&pair_account, liquidity_amount);

			let liquidity_a = T::Currency::total_balance(asset_a, &pair_account);
			let liquidity_b = T::Currency::total_balance(asset_b, &pair_account);
			T::AMMHandler::on_liquidity_changed(SOURCE, asset_a, asset_b, amount_a, amount_b, liquidity_a, liquidity_b)
				.map_err(|(_w, e)| e)?;

			Self::deposit_event(Event::LiquidityAdded {
				who,
				asset_a,
				asset_b,
				amount_a,
				amount_b,
			});

			Ok(())
		}

		/// Remove liquidity from specific liquidity pool in the form of burning shares.
		///
		/// If liquidity in the pool reaches 0, it is destroyed.
		///
		/// Emits 'LiquidityRemoved' when successful.
		/// Emits 'PoolDestroyed' when pool is destroyed.
		#[pallet::weight(
			<T as Config>::WeightInfo::remove_liquidity()
				.saturating_add(T::AMMHandler::on_liquidity_changed_weight())
		)]
		#[transactional]
		pub fn remove_liquidity(
			origin: OriginFor<T>,
			asset_a: AssetId,
			asset_b: AssetId,
			liquidity_amount: Balance,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;

			let asset_pair = AssetPair {
				asset_in: asset_a,
				asset_out: asset_b,
			};

			ensure!(!liquidity_amount.is_zero(), Error::<T>::ZeroLiquidity);

			ensure!(Self::exists(asset_pair), Error::<T>::TokenPoolNotFound);

			let pair_account = Self::get_pair_id(asset_pair);

			let share_token = Self::share_token(&pair_account);

			let total_shares = Self::total_liquidity(&pair_account);

			let account_shares = T::Currency::free_balance(share_token, &who);

			ensure!(total_shares >= liquidity_amount, Error::<T>::InsufficientLiquidity);

			ensure!(account_shares >= liquidity_amount, Error::<T>::InsufficientAssetBalance);

			// Account's liquidity left should be either 0 or at least MinPoolLiquidity
			ensure!(
				(account_shares.saturating_sub(liquidity_amount)) >= T::MinPoolLiquidity::get()
					|| (account_shares == liquidity_amount),
				Error::<T>::InsufficientLiquidity
			);

			let asset_a_reserve = T::Currency::free_balance(asset_a, &pair_account);
			let asset_b_reserve = T::Currency::free_balance(asset_b, &pair_account);

			let liquidity_out = hydra_dx_math::xyk::calculate_liquidity_out(
				asset_a_reserve,
				asset_b_reserve,
				liquidity_amount,
				total_shares,
			)
			.map_err(|_| Error::<T>::RemoveAssetAmountInvalid)?;

			let (remove_amount_a, remove_amount_b) = liquidity_out;

			ensure!(
				T::Currency::free_balance(asset_a, &pair_account) >= remove_amount_a,
				Error::<T>::InsufficientPoolAssetBalance
			);
			ensure!(
				T::Currency::free_balance(asset_b, &pair_account) >= remove_amount_b,
				Error::<T>::InsufficientPoolAssetBalance
			);

			let liquidity_left = total_shares
				.checked_sub(liquidity_amount)
				.ok_or(Error::<T>::InvalidLiquidityAmount)?;

			T::Currency::transfer(asset_a, &pair_account, &who, remove_amount_a)?;
			T::Currency::transfer(asset_b, &pair_account, &who, remove_amount_b)?;

			T::Currency::withdraw(share_token, &who, liquidity_amount)?;

			<TotalLiquidity<T>>::insert(&pair_account, liquidity_left);

			let liquidity_a = T::Currency::total_balance(asset_a, &pair_account);
			let liquidity_b = T::Currency::total_balance(asset_b, &pair_account);
			T::AMMHandler::on_liquidity_changed(
				SOURCE,
				asset_a,
				asset_b,
				remove_amount_a,
				remove_amount_b,
				liquidity_a,
				liquidity_b,
			)
			.map_err(|(_w, e)| e)?;

			Self::deposit_event(Event::LiquidityRemoved {
				who: who.clone(),
				asset_a,
				asset_b,
				shares: liquidity_amount,
			});

			if liquidity_left == 0 {
				<ShareToken<T>>::remove(&pair_account);
				<PoolAssets<T>>::remove(&pair_account);
				<TotalLiquidity<T>>::remove(&pair_account);

				// Ignore the failure, this cant stop liquidity removal
				let r = T::NonDustableWhitelistHandler::remove_account(&pair_account);

				if r.is_err() {
					log::trace!(
					target: "xyk::remova_liquidity", "XYK: Failed to remove account {:?} from dust-removal whitelist. Reason {:?}",
						pair_account,
					r
					);
				}

				Self::deposit_event(Event::PoolDestroyed {
					who,
					asset_a,
					asset_b,
					share_token,
					pool: pair_account,
				});
			}

			Ok(())
		}

		/// Trade asset in for asset out.
		///
		/// Executes a swap of `asset_in` for `asset_out`. Price is determined by the liquidity pool.
		///
		/// `max_limit` - minimum amount of `asset_out` / amount of asset_out to be obtained from the pool in exchange for `asset_in`.
		///
		/// Emits `SellExecuted` when successful.
		#[pallet::weight(<T as Config>::WeightInfo::sell() + <T as Config>::AMMHandler::on_trade_weight())]
		pub fn sell(
			origin: OriginFor<T>,
			asset_in: AssetId,
			asset_out: AssetId,
			amount: Balance,
			max_limit: Balance,
			discount: bool,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;

			<Self as AMM<_, _, _, _>>::sell(&who, AssetPair { asset_in, asset_out }, amount, max_limit, discount)?;

			Ok(())
		}

		/// Trade asset in for asset out.
		///
		/// Executes a swap of `asset_in` for `asset_out`. Price is determined by the liquidity pool.
		///
		/// `max_limit` - maximum amount of `asset_in` to be sold in exchange for `asset_out`.
		///
		/// Emits `BuyExecuted` when successful.
		#[pallet::weight(<T as Config>::WeightInfo::buy() + <T as Config>::AMMHandler::on_trade_weight())]
		pub fn buy(
			origin: OriginFor<T>,
			asset_out: AssetId,
			asset_in: AssetId,
			amount: Balance,
			max_limit: Balance,
			discount: bool,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;

			<Self as AMM<_, _, _, _>>::buy(&who, AssetPair { asset_in, asset_out }, amount, max_limit, discount)?;

			Ok(())
		}
	}
}

impl<T: Config> Pallet<T> {
	/// Return balance of each asset in selected liquidity pool.
	pub fn get_pool_balances(pool_address: T::AccountId) -> Option<Vec<(AssetId, Balance)>> {
		let mut balances = Vec::new();

		if let Some(assets) = Self::get_pool_assets(&pool_address) {
			for item in &assets {
				let reserve = T::Currency::free_balance(*item, &pool_address);
				balances.push((*item, reserve));
			}
		}
		Some(balances)
	}
	/// Calculate discounted trade fee
	fn calculate_discounted_fee(amount: Balance) -> Result<Balance, DispatchError> {
		Ok(
			hydra_dx_math::fee::calculate_pool_trade_fee(amount, T::DiscountedFee::get())
				.ok_or::<Error<T>>(Error::<T>::FeeAmountInvalid)?,
		)
	}

	/// Calculate trade fee
	fn calculate_fee(amount: Balance) -> Result<Balance, DispatchError> {
		let fee = T::GetExchangeFee::get();
		Ok(hydra_dx_math::fee::calculate_pool_trade_fee(amount, (fee.0, fee.1))
			.ok_or::<Error<T>>(Error::<T>::FeeAmountInvalid)?)
	}

	pub fn pair_account_from_assets(asset_a: AssetId, asset_b: AssetId) -> T::AccountId {
		T::AssetPairAccountId::from_assets(asset_a, asset_b, "xyk")
	}
}

// Implementation of AMM API which makes possible to plug the AMM pool into the exchange pallet.
impl<T: Config> AMM<T::AccountId, AssetId, AssetPair, Balance> for Pallet<T> {
	fn exists(assets: AssetPair) -> bool {
		<ShareToken<T>>::contains_key(&Self::get_pair_id(assets))
	}

	fn get_pair_id(assets: AssetPair) -> T::AccountId {
		Self::pair_account_from_assets(assets.asset_in, assets.asset_out)
	}

	fn get_share_token(assets: AssetPair) -> AssetId {
		let pair_account = Self::get_pair_id(assets);
		Self::share_token(&pair_account)
	}

	fn get_pool_assets(pool_account_id: &T::AccountId) -> Option<Vec<AssetId>> {
		let maybe_assets = <PoolAssets<T>>::get(pool_account_id);
		maybe_assets.map(|assets| vec![assets.0, assets.1])
	}

	fn get_spot_price_unchecked(asset_a: AssetId, asset_b: AssetId, amount: Balance) -> Balance {
		let pair_account = Self::get_pair_id(AssetPair {
			asset_out: asset_a,
			asset_in: asset_b,
		});

		let asset_a_reserve = T::Currency::free_balance(asset_a, &pair_account);
		let asset_b_reserve = T::Currency::free_balance(asset_b, &pair_account);

		hydra_dx_math::xyk::calculate_spot_price(asset_a_reserve, asset_b_reserve, amount)
			.unwrap_or_else(|_| Balance::zero())
	}

	/// Validate a sell. Perform all necessary checks and calculations.
	/// No storage changes are performed yet.
	///
	/// Return `AMMTransfer` with all info needed to execute the transaction.
	fn validate_sell(
		who: &T::AccountId,
		assets: AssetPair,
		amount: Balance,
		min_bought: Balance,
		discount: bool,
	) -> Result<AMMTransfer<T::AccountId, AssetId, AssetPair, Balance>, sp_runtime::DispatchError> {
		ensure!(
			amount >= T::MinTradingLimit::get(),
			Error::<T>::InsufficientTradingAmount
		);

		ensure!(Self::exists(assets), Error::<T>::TokenPoolNotFound);

		ensure!(
			T::Currency::free_balance(assets.asset_in, who) >= amount,
			Error::<T>::InsufficientAssetBalance
		);

		// If discount, pool for Sell asset and native asset must exist
		if discount {
			ensure!(
				Self::exists(AssetPair {
					asset_in: assets.asset_in,
					asset_out: T::NativeAssetId::get()
				}),
				Error::<T>::CannotApplyDiscount
			);
		}

		let pair_account = Self::get_pair_id(assets);

		let asset_in_reserve = T::Currency::free_balance(assets.asset_in, &pair_account);
		let asset_out_reserve = T::Currency::free_balance(assets.asset_out, &pair_account);

		ensure!(
			amount
				<= asset_in_reserve
					.checked_div(T::MaxInRatio::get())
					.ok_or(Error::<T>::Overflow)?,
			Error::<T>::MaxInRatioExceeded
		);

		let amount_out = hydra_dx_math::xyk::calculate_out_given_in(asset_in_reserve, asset_out_reserve, amount)
			.map_err(|_| Error::<T>::SellAssetAmountInvalid)?;

		ensure!(
			amount_out
				<= asset_out_reserve
					.checked_div(T::MaxOutRatio::get())
					.ok_or(Error::<T>::Overflow)?,
			Error::<T>::MaxOutRatioExceeded
		);

		let transfer_fee = if discount {
			Self::calculate_discounted_fee(amount_out)?
		} else {
			Self::calculate_fee(amount_out)?
		};

		let amount_out_without_fee = amount_out
			.checked_sub(transfer_fee)
			.ok_or(Error::<T>::SellAssetAmountInvalid)?;

		ensure!(asset_out_reserve > amount_out, Error::<T>::InsufficientAssetBalance);

		ensure!(
			min_bought <= amount_out_without_fee,
			Error::<T>::AssetAmountNotReachedLimit
		);

		let discount_fee = if discount {
			let native_asset = T::NativeAssetId::get();

			let native_pair_account = Self::get_pair_id(AssetPair {
				asset_in: assets.asset_in,
				asset_out: native_asset,
			});

			let native_reserve = T::Currency::free_balance(native_asset, &native_pair_account);
			let asset_reserve = T::Currency::free_balance(assets.asset_in, &native_pair_account);

			let native_fee_spot_price =
				hydra_dx_math::xyk::calculate_spot_price(asset_reserve, native_reserve, transfer_fee)
					.map_err(|_| Error::<T>::CannotApplyDiscount)?;

			ensure!(
				T::Currency::free_balance(native_asset, who) >= native_fee_spot_price,
				Error::<T>::InsufficientNativeCurrencyBalance
			);

			native_fee_spot_price
		} else {
			Balance::zero()
		};

		let transfer = AMMTransfer {
			origin: who.clone(),
			assets,
			amount,
			amount_b: amount_out_without_fee,
			discount,
			discount_amount: discount_fee,
			fee: (assets.asset_out, transfer_fee),
		};

		Ok(transfer)
	}

	/// Execute sell. validate_sell must be called first.
	/// Perform necessary storage/state changes.
	/// Note : the execution should not return error as everything was previously verified and validated.
	#[transactional]
	fn execute_sell(transfer: &AMMTransfer<T::AccountId, AssetId, AssetPair, Balance>) -> DispatchResult {
		let pair_account = Self::get_pair_id(transfer.assets);

		if transfer.discount && transfer.discount_amount > 0u128 {
			let native_asset = T::NativeAssetId::get();
			T::Currency::withdraw(native_asset, &transfer.origin, transfer.discount_amount)?;
		}

		T::Currency::transfer(
			transfer.assets.asset_in,
			&transfer.origin,
			&pair_account,
			transfer.amount,
		)?;
		T::Currency::transfer(
			transfer.assets.asset_out,
			&pair_account,
			&transfer.origin,
			transfer.amount_b,
		)?;

		let liquidity_in = T::Currency::total_balance(transfer.assets.asset_in, &pair_account);
		let liquidity_out = T::Currency::total_balance(transfer.assets.asset_out, &pair_account);
		T::AMMHandler::on_trade(
			SOURCE,
			transfer.assets.asset_in,
			transfer.assets.asset_out,
			transfer.amount,
			transfer.amount_b,
			liquidity_in,
			liquidity_out,
		)
		.map_err(|(_w, e)| e)?;

		Self::deposit_event(Event::<T>::SellExecuted {
			who: transfer.origin.clone(),
			asset_in: transfer.assets.asset_in,
			asset_out: transfer.assets.asset_out,
			amount: transfer.amount,
			sale_price: transfer.amount_b,
			fee_asset: transfer.fee.0,
			fee_amount: transfer.fee.1,
			pool: pair_account,
		});

		Ok(())
	}

	/// Validate a buy. Perform all necessary checks and calculations.
	/// No storage changes are performed yet.
	///
	/// Return `AMMTransfer` with all info needed to execute the transaction.
	fn validate_buy(
		who: &T::AccountId,
		assets: AssetPair,
		amount: Balance,
		max_limit: Balance,
		discount: bool,
	) -> Result<AMMTransfer<T::AccountId, AssetId, AssetPair, Balance>, DispatchError> {
		ensure!(
			amount >= T::MinTradingLimit::get(),
			Error::<T>::InsufficientTradingAmount
		);

		ensure!(Self::exists(assets), Error::<T>::TokenPoolNotFound);

		let pair_account = Self::get_pair_id(assets);

		let asset_out_reserve = T::Currency::free_balance(assets.asset_out, &pair_account);
		let asset_in_reserve = T::Currency::free_balance(assets.asset_in, &pair_account);

		ensure!(asset_out_reserve > amount, Error::<T>::InsufficientPoolAssetBalance);

		ensure!(
			amount
				<= asset_out_reserve
					.checked_div(T::MaxOutRatio::get())
					.ok_or(Error::<T>::Overflow)?,
			Error::<T>::MaxOutRatioExceeded
		);

		// If discount, pool for Sell asset and native asset must exist
		if discount {
			ensure!(
				Self::exists(AssetPair {
					asset_in: assets.asset_out,
					asset_out: T::NativeAssetId::get()
				}),
				Error::<T>::CannotApplyDiscount
			);
		}

		let buy_price = hydra_dx_math::xyk::calculate_in_given_out(asset_out_reserve, asset_in_reserve, amount)
			.map_err(|_| Error::<T>::BuyAssetAmountInvalid)?;

		ensure!(
			buy_price
				<= asset_in_reserve
					.checked_div(T::MaxInRatio::get())
					.ok_or(Error::<T>::Overflow)?,
			Error::<T>::MaxInRatioExceeded
		);

		let transfer_fee = if discount {
			Self::calculate_discounted_fee(buy_price)?
		} else {
			Self::calculate_fee(buy_price)?
		};

		let buy_price_with_fee = buy_price
			.checked_add(transfer_fee)
			.ok_or(Error::<T>::BuyAssetAmountInvalid)?;

		ensure!(max_limit >= buy_price_with_fee, Error::<T>::AssetAmountExceededLimit);

		ensure!(
			T::Currency::free_balance(assets.asset_in, who) >= buy_price_with_fee,
			Error::<T>::InsufficientAssetBalance
		);

		let discount_fee = if discount {
			let native_asset = T::NativeAssetId::get();

			let native_pair_account = Self::get_pair_id(AssetPair {
				asset_in: assets.asset_out,
				asset_out: native_asset,
			});

			let native_reserve = T::Currency::free_balance(native_asset, &native_pair_account);
			let asset_reserve = T::Currency::free_balance(assets.asset_out, &native_pair_account);

			let native_fee_spot_price =
				hydra_dx_math::xyk::calculate_spot_price(asset_reserve, native_reserve, transfer_fee)
					.map_err(|_| Error::<T>::CannotApplyDiscount)?;

			ensure!(
				T::Currency::free_balance(native_asset, who) >= native_fee_spot_price,
				Error::<T>::InsufficientNativeCurrencyBalance
			);
			native_fee_spot_price
		} else {
			Balance::zero()
		};

		let transfer = AMMTransfer {
			origin: who.clone(),
			assets,
			amount,
			amount_b: buy_price,
			discount,
			discount_amount: discount_fee,
			fee: (assets.asset_in, transfer_fee),
		};

		Ok(transfer)
	}

	/// Execute buy. validate_buy must be called first.
	/// Perform necessary storage/state changes.
	/// Note : the execution should not return error as everything was previously verified and validated.
	#[transactional]
	fn execute_buy(transfer: &AMMTransfer<T::AccountId, AssetId, AssetPair, Balance>) -> DispatchResult {
		let pair_account = Self::get_pair_id(transfer.assets);

		if transfer.discount && transfer.discount_amount > 0 {
			let native_asset = T::NativeAssetId::get();
			T::Currency::withdraw(native_asset, &transfer.origin, transfer.discount_amount)?;
		}

		T::Currency::transfer(
			transfer.assets.asset_out,
			&pair_account,
			&transfer.origin,
			transfer.amount,
		)?;
		T::Currency::transfer(
			transfer.assets.asset_in,
			&transfer.origin,
			&pair_account,
			transfer.amount_b + transfer.fee.1,
		)?;

		let liquidity_in = T::Currency::total_balance(transfer.assets.asset_in, &pair_account);
		let liquidity_out = T::Currency::total_balance(transfer.assets.asset_out, &pair_account);
		T::AMMHandler::on_trade(
			SOURCE,
			transfer.assets.asset_in,
			transfer.assets.asset_out,
			transfer.amount,
			transfer.amount_b,
			liquidity_in,
			liquidity_out,
		)
		.map_err(|(_w, e)| e)?;

		Self::deposit_event(Event::<T>::BuyExecuted {
			who: transfer.origin.clone(),
			asset_out: transfer.assets.asset_out,
			asset_in: transfer.assets.asset_in,
			amount: transfer.amount,
			buy_price: transfer.amount_b,
			fee_asset: transfer.fee.0,
			fee_amount: transfer.fee.1,
			pool: pair_account,
		});

		Ok(())
	}

	fn get_min_trading_limit() -> Balance {
		T::MinTradingLimit::get()
	}

	fn get_min_pool_liquidity() -> Balance {
		T::MinPoolLiquidity::get()
	}

	fn get_max_in_ratio() -> u128 {
		T::MaxInRatio::get()
	}

	fn get_max_out_ratio() -> u128 {
		T::MaxOutRatio::get()
	}

	fn get_fee(_pool_account_id: &T::AccountId) -> (u32, u32) {
		T::GetExchangeFee::get()
	}
}

pub struct AllowAllPools();

impl CanCreatePool<AssetId> for AllowAllPools {
	fn can_create(_asset_a: AssetId, _asset_b: AssetId) -> bool {
		true
	}
}

impl<T: Config> AMMPosition<AssetId, Balance> for Pallet<T> {
	type Error = DispatchError;

	fn get_liquidity_behind_shares(
		asset_a: AssetId,
		asset_b: AssetId,
		shares_amount: Balance,
	) -> Result<(Balance, Balance), Self::Error> {
		let asset_pair = AssetPair {
			asset_in: asset_a,
			asset_out: asset_b,
		};

		let pair_account = Self::get_pair_id(asset_pair);

		let total_shares = Self::total_liquidity(&pair_account);

		let asset_a_reserve = T::Currency::free_balance(asset_a, &pair_account);
		let asset_b_reserve = T::Currency::free_balance(asset_b, &pair_account);

		hydra_dx_math::xyk::calculate_liquidity_out(asset_a_reserve, asset_b_reserve, shares_amount, total_shares)
			.map_err(|_| Error::<T>::RemoveAssetAmountInvalid.into())
	}
}