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
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
// Copyright 2021-2022 Zenlink.
// Licensed under Apache 2.0.

//! # Stable AMM Pallet
//!
//! Based on the Curve V1 StableSwap architecture.
//!
//! There are two categories of pool:
//! - Basic: pairs two or more stablecoins
//! - Meta: pairs stablecoins with the LP token of another base pool
//!
//! ## Overview
//!
//! This pallet provides functionality for:
//!
//! - Creating pools
//! - Adding / removing liquidity
//! - Swapping currencies
//! - Ramping of A
//!
//! ### Terminology
//!
//! - **Amplification Coefficient:** This determines a pool's tolerance for imbalance.
//!
//! - **Swap Fee:** The fee taken from the output currency.
//!
//! - **Admin Fee:** The percentage of the fee taken from the swap fee, claimable by the pool owner.

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

pub mod rpc;
pub mod traits;

#[cfg(test)]
mod base_pool_tests;
#[cfg(any(feature = "runtime-benchmarks", test))]
pub mod benchmarking;
#[cfg(test)]
mod meta_pool_tests;
#[cfg(test)]
mod mock;

mod base_pool;
mod default_weights;
mod meta_pool;
mod primitives;
mod utils;

use frame_support::{
    dispatch::{Codec, DispatchResult},
    pallet_prelude::*,
    traits::UnixTime,
    transactional, PalletId,
};
use orml_traits::MultiCurrency;
use sp_arithmetic::traits::{checked_pow, AtLeast32BitUnsigned, CheckedAdd, One, Zero};
use sp_core::U256;
use sp_runtime::traits::{AccountIdConversion, StaticLookup};
use sp_std::{ops::Sub, vec, vec::Vec};

pub use default_weights::WeightInfo;
pub use pallet::*;
use primitives::*;
use traits::{StablePoolLpCurrencyIdGenerate, ValidateCurrency};

#[allow(type_alias_bounds)]
type AccountIdOf<T: Config> = <T as frame_system::Config>::AccountId;

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

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

        /// The currency ID type
        type CurrencyId: Parameter + Member + Copy + MaybeSerializeDeserialize + Ord + TypeInfo + MaxEncodedLen;

        /// The trait control all currencies
        type MultiCurrency: MultiCurrency<AccountIdOf<Self>, CurrencyId = Self::CurrencyId, Balance = Balance>;

        /// The pool ID type
        type PoolId: Parameter + Codec + Copy + Ord + AtLeast32BitUnsigned + Zero + One + Default + MaxEncodedLen;

        /// Verify that the currencies can be used in a pool.
        type EnsurePoolAsset: ValidateCurrency<Self::CurrencyId>;

        /// Generate the CurrencyId for the pool.
        type LpGenerate: StablePoolLpCurrencyIdGenerate<Self::CurrencyId, Self::PoolId>;

        /// The trait get timestamp of chain.
        type TimeProvider: UnixTime;

        #[pallet::constant]
        type PoolCurrencyLimit: Get<u32>;

        #[pallet::constant]
        type PoolCurrencySymbolLimit: Get<u32>;

        /// This pallet ID.
        #[pallet::constant]
        type PalletId: Get<PalletId>;

        /// Weight information for extrinsics in this pallet.
        type WeightInfo: WeightInfo;
    }

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

    /// The id of next pool
    #[pallet::storage]
    #[pallet::getter(fn next_pool_id)]
    pub type NextPoolId<T: Config> = StorageValue<_, T::PoolId, ValueQuery>;

    /// Info of a pool.
    #[pallet::storage]
    #[pallet::getter(fn pools)]
    pub type Pools<T: Config> = StorageMap<
        _,
        Blake2_128Concat,
        T::PoolId,
        Pool<T::PoolId, T::CurrencyId, T::AccountId, T::PoolCurrencyLimit, T::PoolCurrencySymbolLimit>,
    >;

    /// The pool id corresponding to lp currency
    #[pallet::storage]
    #[pallet::getter(fn lp_currencies)]
    pub type LpCurrencies<T: Config> = StorageMap<_, Blake2_128Concat, T::CurrencyId, T::PoolId>;

    #[pallet::event]
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
    pub enum Event<T: Config> {
        /// A pool was created.
        CreatePool {
            pool_id: T::PoolId,
            currency_ids: Vec<T::CurrencyId>,
            lp_currency_id: T::CurrencyId,
            a: Number,
            account: T::AccountId,
            swap_fee: Number,
            admin_fee: Number,
            admin_fee_receiver: T::AccountId,
        },
        /// A pool's admin_fee_receiver was updated.
        UpdateAdminFeeReceiver {
            pool_id: T::PoolId,
            admin_fee_receiver: T::AccountId,
        },
        /// Supply some liquidity to a pool.
        AddLiquidity {
            pool_id: T::PoolId,
            who: T::AccountId,
            to: T::AccountId,
            supply_amounts: Vec<Balance>,
            fees: Vec<Balance>,
            new_d: Balance,
            mint_amount: Balance,
        },
        /// Swap a amounts of currency to get other.
        CurrencyExchange {
            pool_id: T::PoolId,
            who: T::AccountId,
            to: T::AccountId,
            in_index: u32,
            in_amount: Balance,
            out_index: u32,
            out_amount: Balance,
        },
        /// Remove some liquidity from a pool.
        RemoveLiquidity {
            pool_id: T::PoolId,
            who: T::AccountId,
            to: T::AccountId,
            amounts: Vec<Balance>,
            fees: Vec<Balance>,
            new_total_supply: Balance,
        },
        /// Remove some liquidity from a pool to get only one currency.
        RemoveLiquidityOneCurrency {
            pool_id: T::PoolId,
            who: T::AccountId,
            to: T::AccountId,
            out_index: u32,
            burn_amount: Balance,
            out_amount: Balance,
        },
        /// Remove liquidity from a pool with specify the amounts of currencies to be obtained.
        RemoveLiquidityImbalance {
            pool_id: T::PoolId,
            who: T::AccountId,
            to: T::AccountId,
            amounts: Vec<Balance>,
            fees: Vec<Balance>,
            new_d: Balance,
            new_total_supply: Balance,
        },
        /// A pool's swap fee parameters was updated
        NewSwapFee { pool_id: T::PoolId, new_swap_fee: Number },
        /// A pool's admin fee parameters was updated
        NewAdminFee { pool_id: T::PoolId, new_admin_fee: Number },
        /// A pool's 'A' was ramped.
        RampA {
            pool_id: T::PoolId,
            initial_a_precise: Number,
            future_a_precise: Number,
            now: Number,
            future_a_time: Number,
        },
        /// A pool's ramping A was stopped.
        StopRampA {
            pool_id: T::PoolId,
            current_a: Number,
            now: Number,
        },
        /// A pool's admin fee was collected.
        CollectProtocolFee {
            pool_id: T::PoolId,
            currency_id: T::CurrencyId,
            fee_amount: Balance,
        },

        CurrencyExchangeUnderlying {
            pool_id: T::PoolId,
            account: T::AccountId,
            in_amount: Balance,
            out_amount: Balance,
            currency_index_from: u32,
            currency_index_to: u32,
            to: T::AccountId,
        },
    }

    #[pallet::error]
    pub enum Error<T> {
        /// The currency id can't join stable amm pool.
        InvalidPooledCurrency,
        /// The currency id can't become the lp currency id of stable amm pool.
        InvalidLpCurrency,
        /// The parameters of a call are contradictory.
        MismatchParameter,
        /// The decimal of currency is invalid when create pool.
        InvalidCurrencyDecimal,
        /// The pool id is invalid.
        InvalidPoolId,
        /// The base pool mismatch this pool.
        InvalidBasePool,
        /// The error generate by some arithmetic function.
        Arithmetic,
        /// The call already expired.
        Deadline,
        /// The caller does not have enough currencies.
        InsufficientSupply,
        /// The pool does not have enough currencies.
        InsufficientReserve,
        /// The new d below then older.
        CheckDFailed,
        /// Slippage is too large.
        AmountSlippage,
        /// Forbid swap same currency.
        SwapSameCurrency,
        /// The index of currency id bigger the length of pool's currencies.
        CurrencyIndexOutRange,
        /// The pool does not have enough lp currency.
        InsufficientLpReserve,
        /// The setting value exceed threshold.
        ExceedThreshold,
        /// The A of this pool is already ramped in current period.
        RampADelay,
        /// The value of feature_a_time is too small.
        MinRampTime,
        /// Forbid change A of a pool bigger than MAX_A.
        ExceedMaxAChange,
        /// The ramping A of this pool is already stopped.
        AlreadyStoppedRampA,
        /// The fee parameter exceeds MAX_SWAP_FEE when creating the pool.
        ExceedMaxFee,
        /// The admin fee parameter exceeds MAX_ADMIN_FEE when creating the pool.
        ExceedMaxAdminFee,
        /// The A parameter cannot be zero when creating the pool.
        ZeroA,
        /// The A parameter exceed MAX_A when creating the pool.
        ExceedMaxA,
        /// The lp currency id is already used when create pool.
        LpCurrencyAlreadyUsed,
        /// Require all currencies of this pool when first supply.
        RequireAllCurrencies,
        /// The number of currencies exceeds the length limit.
        TooManyCurrencies,
        /// The symbol of created pool exceeds the length limit.
        BadPoolCurrencySymbol,
        /// The transaction change nothing.
        InvalidTransaction,
        /// The base pool lp currency is invalid when create meta pool.
        InvalidBasePoolLpCurrency,
        /// The token index out of range.
        TokenIndexOutOfRange,
    }

    #[pallet::call]
    impl<T: Config> Pallet<T> {
        /// Create a stable amm pool.
        ///
        /// Only admin can create pool.
        ///
        /// # Argument
        ///
        /// - `currency_ids`: The currencies will be join the created pool.
        /// - `currency_decimals`: The currencies corresponding decimals.
        /// - `lp_currency_id`: The specify lp currency id of the created pool.
        /// - `a`: The initial A of created pool.
        /// - `fee`: The swap fee of created pool.
        /// - `admin_fee`: The admin fee of created pool.
        /// - `admin_fee_receiver`: The admin fee receiver of created pool.
        /// - `lp_currency_symbol`: The symbol of created pool lp currency.
        /// - `lp_currency_decimal`: The decimal of created pool lp currency.
        #[pallet::call_index(0)]
        #[pallet::weight(T::WeightInfo::create_base_pool(
            currency_ids.len() as u32,
            T::PoolCurrencySymbolLimit::get()
        ))]
        #[transactional]
        pub fn create_base_pool(
            origin: OriginFor<T>,
            currency_ids: Vec<T::CurrencyId>,
            currency_decimals: Vec<u32>,
            a: Number,
            fee: Number,
            admin_fee: Number,
            admin_fee_receiver: T::AccountId,
            lp_currency_symbol: Vec<u8>,
        ) -> DispatchResult {
            ensure_root(origin)?;

            let (new_pool, pool_id) = Self::inner_create_base_pool(
                &currency_ids,
                currency_decimals,
                a,
                fee,
                admin_fee,
                &admin_fee_receiver,
                lp_currency_symbol,
            )?;

            LpCurrencies::<T>::insert(new_pool.lp_currency_id, pool_id);

            NextPoolId::<T>::try_mutate(|pool_id| -> DispatchResult {
                *pool_id = pool_id.checked_add(&One::one()).ok_or(Error::<T>::Arithmetic)?;
                Ok(())
            })?;

            Pools::<T>::try_mutate(pool_id, |pool_info| -> DispatchResult {
                ensure!(pool_info.is_none(), Error::<T>::InvalidPoolId);
                let lp_currency_id = new_pool.lp_currency_id;
                let pool_account = new_pool.account.clone();

                *pool_info = Some(Pool::Base(new_pool));

                Self::deposit_event(Event::CreatePool {
                    pool_id,
                    currency_ids,
                    lp_currency_id,
                    a,
                    account: pool_account,
                    swap_fee: fee,
                    admin_fee,
                    admin_fee_receiver,
                });

                Ok(())
            })
        }

        /// Create a stable amm meta pool.
        ///
        /// Only admin can create pool.
        ///
        /// # Argument
        ///
        /// - `currency_ids`: The currencies will be join the created pool.
        /// - `currency_decimals`: The currencies corresponding decimals.
        /// - `lp_currency_id`: The specify lp currency id of the created pool.
        /// - `a`: The initial A of created pool.
        /// - `fee`: The swap fee of created pool.
        /// - `admin_fee`: The admin fee of created pool.
        /// - `admin_fee_receiver`: The admin fee receiver of created pool.
        /// - `lp_currency_symbol`: The symbol of created pool lp currency.
        /// - `lp_currency_decimal`: The decimal of created pool lp currency.
        #[pallet::call_index(1)]
        #[pallet::weight(T::WeightInfo::create_meta_pool(
            currency_ids.len() as u32,
            T::PoolCurrencySymbolLimit::get()
        ))]
        #[transactional]
        pub fn create_meta_pool(
            origin: OriginFor<T>,
            currency_ids: Vec<T::CurrencyId>,
            currency_decimals: Vec<u32>,
            a: Number,
            fee: Number,
            admin_fee: Number,
            admin_fee_receiver: T::AccountId,
            lp_currency_symbol: Vec<u8>,
        ) -> DispatchResult {
            ensure_root(origin)?;
            let base_pool_lp_currency = currency_ids.last().ok_or(Error::<T>::MismatchParameter)?;
            let base_pool_id =
                Self::lp_currencies(base_pool_lp_currency).ok_or(Error::<T>::InvalidBasePoolLpCurrency)?;

            let (meta_pool_info, pool_id) = Self::inner_create_base_pool(
                &currency_ids,
                currency_decimals,
                a,
                fee,
                admin_fee,
                &admin_fee_receiver,
                lp_currency_symbol,
            )?;

            let base_pool = Self::pools(base_pool_id).ok_or(Error::<T>::InvalidBasePoolLpCurrency)?;

            let base_pool_virtual_price = Self::get_pool_virtual_price(&base_pool).ok_or(Error::<T>::Arithmetic)?;

            let meta_pool = MetaPool {
                base_pool_id,
                base_virtual_price: base_pool_virtual_price,
                base_cache_last_updated: T::TimeProvider::now().as_secs(),
                base_currencies: base_pool.get_currency_ids(),
                info: meta_pool_info,
            };

            LpCurrencies::<T>::insert(meta_pool.info.lp_currency_id, pool_id);

            NextPoolId::<T>::try_mutate(|pool_id| -> DispatchResult {
                *pool_id = pool_id.checked_add(&One::one()).ok_or(Error::<T>::Arithmetic)?;
                Ok(())
            })?;

            Pools::<T>::try_mutate(pool_id, |pool_info| -> DispatchResult {
                ensure!(pool_info.is_none(), Error::<T>::InvalidPoolId);
                let lp_currency_id = meta_pool.info.lp_currency_id;
                let pool_account = meta_pool.info.account.clone();

                *pool_info = Some(Pool::Meta(meta_pool));

                Self::deposit_event(Event::CreatePool {
                    pool_id,
                    currency_ids,
                    lp_currency_id,
                    a,
                    account: pool_account,
                    swap_fee: fee,
                    admin_fee,
                    admin_fee_receiver,
                });
                Ok(())
            })
        }

        /// Supply amounts of currencies to the pool.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `amounts`: Supply amounts of currencies.
        /// - `min_mint_amount`: The min amount of lp currency get.
        /// - `deadline`: Height of the cutoff block of this transaction
        #[pallet::call_index(2)]
        #[pallet::weight(T::WeightInfo::add_liquidity(amounts.len() as u32))]
        #[transactional]
        pub fn add_liquidity(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            amounts: Vec<Balance>,
            min_mint_amount: Balance,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;

            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_add_liquidity(&who, pool_id, &amounts, min_mint_amount, &to)?;

            Ok(())
        }

        /// Swap a amounts of currencies to get other.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `from_index`: The index of swap currency id.
        /// - `to_index`: The index of receive currency id.
        /// - `in_amount`: The amounts of currencies swap.
        /// - `min_mint_amount`: The min amount of receive currency.
        /// - `deadline`: Height of the cutoff block of this transaction
        #[pallet::call_index(3)]
        #[pallet::weight(T::WeightInfo::swap())]
        #[transactional]
        pub fn swap(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            from_index: u32,
            to_index: u32,
            in_amount: Balance,
            min_out_amount: Balance,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;

            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_swap(
                &who,
                pool_id,
                from_index as usize,
                to_index as usize,
                in_amount,
                min_out_amount,
                &to,
            )?;

            Ok(())
        }

        /// Remove liquidity from a pool.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `lp_amount`: The amounts of lp currency.
        /// - `min_amounts`: The min amounts of pool's currencies to get.
        /// - `deadline`: Height of the cutoff block of this transaction
        #[pallet::call_index(4)]
        #[pallet::weight(T::WeightInfo::remove_liquidity(min_amounts.len() as u32))]
        #[transactional]
        pub fn remove_liquidity(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            lp_amount: Balance,
            min_amounts: Vec<Balance>,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;

            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_remove_liquidity(pool_id, &who, lp_amount, &min_amounts, &to)?;

            Ok(())
        }

        /// Remove liquidity from a pool to get one currency.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `lp_amount`: The amounts of lp currency.
        /// - `index`: The index of receive currency.
        /// - `min_amount`: The min amounts of received currency;
        /// - `deadline`: Height of the cutoff block of this transaction
        #[pallet::call_index(5)]
        #[pallet::weight(T::WeightInfo::remove_liquidity_one_currency())]
        #[transactional]
        pub fn remove_liquidity_one_currency(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            lp_amount: Balance,
            index: u32,
            min_amount: Balance,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;

            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_remove_liquidity_one_currency(pool_id, &who, lp_amount, index, min_amount, &to)?;

            Ok(())
        }

        /// Remove liquidity from a pool to the specify amounts of currencies.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `amounts`: The specify amounts of receive currencies.
        /// - `max_burn_amount`: The max amount of burned lp currency.
        /// - `deadline`: Height of the cutoff block of this transaction
        #[pallet::call_index(6)]
        #[pallet::weight(T::WeightInfo::remove_liquidity_imbalance(amounts.len() as u32))]
        #[transactional]
        pub fn remove_liquidity_imbalance(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            amounts: Vec<Balance>,
            max_burn_amount: Balance,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;

            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_remove_liquidity_imbalance(&who, pool_id, &amounts, max_burn_amount, &to)?;

            Ok(())
        }

        /// Supply amounts of currencies to the pool which contains the lp currency of the base
        /// pool.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `base_pool_id`: The id of base pool.
        /// - `meta_amounts`: Supply amounts of currencies to pool. The last element must be zero.
        /// - `base_amounts`: Supply amounts of currencies to base pool.
        /// - `min_to_mint`: The min amount of pool lp currency get.
        /// - `deadline`: Height of the cutoff block of this transaction.
        #[pallet::call_index(7)]
        #[pallet::weight(T::WeightInfo::add_pool_and_base_pool_liquidity(
            base_amounts.len() as u32,
            meta_amounts.len() as u32
        ))]
        #[transactional]
        pub fn add_pool_and_base_pool_liquidity(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            base_pool_id: T::PoolId,
            meta_amounts: Vec<Balance>,
            base_amounts: Vec<Balance>,
            min_to_mint: Balance,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;
            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_add_pool_and_base_pool_liquidity(
                &who,
                pool_id,
                base_pool_id,
                meta_amounts,
                &base_amounts,
                min_to_mint,
                &to,
            )?;

            Ok(())
        }

        /// Remove liquidity from a pool which contains the lp currency of the base pool.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `base_pool_id`: The id of base pool.
        /// - `amount`: The amounts of lp currency to burn.
        /// - `min_amounts_meta`: The min amounts of pool's currencies to get.
        /// - `min_amounts_base`: The min amounts of basic pool's currencies to get.
        /// - `deadline`: Height of the cutoff block of this transaction.
        #[pallet::call_index(8)]
        #[pallet::weight(T::WeightInfo::remove_pool_and_base_pool_liquidity(
            min_amounts_base.len() as u32,
            min_amounts_meta.len() as u32,
        ))]
        #[transactional]
        pub fn remove_pool_and_base_pool_liquidity(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            base_pool_id: T::PoolId,
            amount: Balance,
            min_amounts_meta: Vec<Balance>,
            min_amounts_base: Vec<Balance>,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;
            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_remove_pool_and_base_pool_liquidity(
                &who,
                pool_id,
                base_pool_id,
                amount,
                &min_amounts_meta,
                &min_amounts_base,
                &to,
            )?;

            Ok(())
        }

        /// Remove liquidity from a pool which contains the lp currency of the base pool
        /// to get one currency.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `base_pool_id`: The id of base pool.
        /// - `amount`: The amounts of lp currency to burn.
        /// - `i`: The index of target currency in basic pool.
        /// - `min_amount`: The min amounts of received currency.
        /// - `deadline`: Height of the cutoff block of this transaction.
        #[pallet::call_index(9)]
        #[pallet::weight(T::WeightInfo::remove_pool_and_base_pool_liquidity_one_currency())]
        #[transactional]
        pub fn remove_pool_and_base_pool_liquidity_one_currency(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            base_pool_id: T::PoolId,
            amount: Balance,
            i: u32,
            min_amount: Balance,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;
            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_remove_pool_and_base_pool_liquidity_one_currency(
                &who,
                pool_id,
                base_pool_id,
                amount,
                i,
                min_amount,
                &to,
            )?;

            Ok(())
        }

        /// Swap the currency from basic pool to get amounts of other currency in pool.
        /// to get one currency.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `base_pool_id`: The id of base pool.
        /// - `in_index`: The index of swap currency in basic pool.
        /// - `out_index`: The index of target currency in pool.
        /// - `dx`: The amounts of swap currency.
        /// - `min_dy`: The min amounts of target currency.
        /// - `deadline`: Height of the cutoff block of this transaction.
        #[pallet::call_index(10)]
        #[pallet::weight(T::WeightInfo::swap_pool_from_base())]
        #[transactional]
        pub fn swap_pool_from_base(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            base_pool_id: T::PoolId,
            in_index: u32,
            out_index: u32,
            dx: Balance,
            min_dy: Balance,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;
            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_swap_pool_from_base(&who, pool_id, base_pool_id, in_index, out_index, dx, min_dy, &to)?;

            Ok(())
        }

        /// Swap the currency from pool to get amounts of other currency in basic pool.
        /// to get one currency.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `base_pool_id`: The id of base pool.
        /// - `in_index`: The index of swap currency in basic pool.
        /// - `out_index`: The index of target currency in pool.
        /// - `dx`: The amounts of swap currency.
        /// - `min_dy`: The min amounts of target currency.
        /// - `deadline`: Height of the cutoff block of this transaction.
        #[pallet::call_index(11)]
        #[pallet::weight(T::WeightInfo::swap_pool_to_base())]
        #[transactional]
        pub fn swap_pool_to_base(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            base_pool_id: T::PoolId,
            in_index: u32,
            out_index: u32,
            dx: Balance,
            min_dy: Balance,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;
            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Self::inner_swap_pool_to_base(&who, pool_id, base_pool_id, in_index, out_index, dx, min_dy, &to)?;

            Ok(())
        }

        #[pallet::call_index(12)]
        #[pallet::weight(T::WeightInfo::swap_meta_pool_underlying())]
        #[transactional]
        pub fn swap_meta_pool_underlying(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            in_index: u32,
            out_index: u32,
            dx: Balance,
            min_dy: Balance,
            to: T::AccountId,
            deadline: BlockNumberFor<T>,
        ) -> DispatchResult {
            let who = ensure_signed(origin)?;
            let now = frame_system::Pallet::<T>::block_number();
            ensure!(deadline > now, Error::<T>::Deadline);

            Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> Result<Balance, DispatchError> {
                let pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
                match pool {
                    Pool::Meta(mp) => Self::meta_pool_swap_underlying(
                        mp,
                        pool_id,
                        &who,
                        &to,
                        dx,
                        min_dy,
                        in_index as usize,
                        out_index as usize,
                    ),
                    _ => Err(Error::<T>::InvalidPoolId.into()),
                }
            })?;

            Ok(())
        }

        /// Update admin fee receiver of the pool.
        ///
        /// Only called by admin.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `fee_receiver`: The new admin fee receiver of this pool.
        #[pallet::call_index(13)]
        #[pallet::weight(T::WeightInfo::update_fee_receiver())]
        #[transactional]
        pub fn update_fee_receiver(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            fee_receiver: <T::Lookup as StaticLookup>::Source,
        ) -> DispatchResult {
            ensure_root(origin)?;
            let admin_fee_receiver = T::Lookup::lookup(fee_receiver)?;
            Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> DispatchResult {
                let pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
                pool.set_admin_fee_receiver(admin_fee_receiver.clone());

                Self::deposit_event(Event::UpdateAdminFeeReceiver {
                    pool_id,
                    admin_fee_receiver,
                });
                Ok(())
            })
        }

        /// Update fee of the pool.
        ///
        /// Only called by admin.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `new_swap_fee`: The new swap fee of this pool.
        #[pallet::call_index(14)]
        #[pallet::weight(T::WeightInfo::set_swap_fee())]
        #[transactional]
        pub fn set_swap_fee(origin: OriginFor<T>, pool_id: T::PoolId, new_swap_fee: Number) -> DispatchResult {
            ensure_root(origin)?;
            Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> DispatchResult {
                let pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
                ensure!(new_swap_fee <= MAX_SWAP_FEE, Error::<T>::ExceedThreshold);

                pool.set_fee(new_swap_fee);

                Self::deposit_event(Event::NewSwapFee { pool_id, new_swap_fee });
                Ok(())
            })
        }

        /// Update admin fee of the pool.
        ///
        /// Only called by admin.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `new_admin_fee`: The new admin fee of this pool.
        #[pallet::call_index(15)]
        #[pallet::weight(T::WeightInfo::set_admin_fee())]
        #[transactional]
        pub fn set_admin_fee(origin: OriginFor<T>, pool_id: T::PoolId, new_admin_fee: Number) -> DispatchResult {
            ensure_root(origin)?;
            Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> DispatchResult {
                let pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
                ensure!(new_admin_fee <= MAX_ADMIN_FEE, Error::<T>::ExceedThreshold);

                pool.set_admin_fee(new_admin_fee);

                Self::deposit_event(Event::NewAdminFee { pool_id, new_admin_fee });
                Ok(())
            })
        }

        /// Start ramping up or down A parameter towards given future_a and future_a_time
        ///
        /// Only called by admin.
        /// Checks if the change is too rapid, and commits the new A value only when it falls under
        /// the limit range.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        /// - `future_a`: The new A to ramp towards.
        /// - `future_a_time`: Timestamp when the new A should be reached
        #[pallet::call_index(16)]
        #[pallet::weight(T::WeightInfo::ramp_a())]
        #[transactional]
        pub fn ramp_a(
            origin: OriginFor<T>,
            pool_id: T::PoolId,
            future_a: Number,
            future_a_time: Number,
        ) -> DispatchResult {
            ensure_root(origin)?;
            let now = T::TimeProvider::now().as_secs() as Number;
            Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> DispatchResult {
                let general_pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
                let pool = match general_pool {
                    Pool::Base(bp) => bp,
                    Pool::Meta(mp) => &mut mp.info,
                };
                ensure!(
                    now >= pool
                        .initial_a_time
                        .checked_add(Number::from(DAY))
                        .ok_or(Error::<T>::Arithmetic)?,
                    Error::<T>::RampADelay
                );

                ensure!(
                    future_a_time
                        >= now
                            .checked_add(Number::from(MIN_RAMP_TIME))
                            .ok_or(Error::<T>::Arithmetic)?,
                    Error::<T>::MinRampTime
                );

                ensure!(future_a > Zero::zero() && future_a < MAX_A, Error::<T>::ExceedThreshold);

                let (initial_a_precise, future_a_precise) = Self::get_a_precise(pool)
                    .and_then(|initial_a_precise| -> Option<(Number, Number)> {
                        let future_a_precise = future_a.checked_mul(A_PRECISION)?;
                        Some((initial_a_precise, future_a_precise))
                    })
                    .ok_or(Error::<T>::Arithmetic)?;

                let max_a_change = Number::from(MAX_A_CHANGE);

                if future_a_precise < initial_a_precise {
                    ensure!(
                        future_a_precise
                            .checked_mul(max_a_change)
                            .ok_or(Error::<T>::Arithmetic)?
                            >= initial_a_precise,
                        Error::<T>::ExceedMaxAChange
                    );
                } else {
                    ensure!(
                        future_a_precise
                            <= initial_a_precise
                                .checked_mul(max_a_change)
                                .ok_or(Error::<T>::Arithmetic)?,
                        Error::<T>::ExceedMaxAChange
                    );
                }

                pool.initial_a = initial_a_precise;
                pool.future_a = future_a_precise;
                pool.initial_a_time = now;
                pool.future_a_time = future_a_time;

                Self::deposit_event(Event::RampA {
                    pool_id,
                    initial_a_precise,
                    future_a_precise,
                    now,
                    future_a_time,
                });

                Ok(())
            })
        }

        /// Stop ramping A parameter.
        ///
        /// Only called by admin.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        #[pallet::call_index(17)]
        #[pallet::weight(T::WeightInfo::stop_ramp_a())]
        #[transactional]
        pub fn stop_ramp_a(origin: OriginFor<T>, pool_id: T::PoolId) -> DispatchResult {
            ensure_root(origin)?;
            Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> DispatchResult {
                let general_pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
                let pool = match general_pool {
                    Pool::Base(bp) => bp,
                    Pool::Meta(mp) => &mut mp.info,
                };

                let now = T::TimeProvider::now().as_secs() as Number;
                ensure!(pool.future_a_time > now, Error::<T>::AlreadyStoppedRampA);

                let current_a = Self::get_a_precise(pool).ok_or(Error::<T>::Arithmetic)?;

                pool.initial_a = current_a;
                pool.future_a = current_a;
                pool.initial_a_time = now;
                pool.future_a_time = now;

                Self::deposit_event(Event::StopRampA {
                    pool_id,
                    current_a,
                    now,
                });
                Ok(())
            })
        }

        /// Withdraw the admin fee from pool to admin fee receiver.
        ///
        /// Can called by anyone.
        ///
        /// # Argument
        ///
        /// - `pool_id`: The id of pool.
        #[pallet::call_index(18)]
        #[pallet::weight(T::WeightInfo::withdraw_admin_fee())]
        #[transactional]
        pub fn withdraw_admin_fee(origin: OriginFor<T>, pool_id: T::PoolId) -> DispatchResult {
            ensure_signed(origin)?;

            Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> DispatchResult {
                let general_pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
                let pool = match general_pool {
                    Pool::Base(bp) => bp,
                    Pool::Meta(mp) => &mut mp.info,
                };

                for (i, reserve) in pool.balances.iter().enumerate() {
                    let balance = T::MultiCurrency::free_balance(pool.currency_ids[i], &pool.account)
                        .checked_sub(*reserve)
                        .ok_or(Error::<T>::Arithmetic)?;

                    if !balance.is_zero() {
                        T::MultiCurrency::transfer(
                            pool.currency_ids[i],
                            &pool.account,
                            &pool.admin_fee_receiver,
                            balance,
                        )?;
                    }
                    Self::deposit_event(Event::CollectProtocolFee {
                        pool_id,
                        currency_id: pool.currency_ids[i],
                        fee_amount: balance,
                    });
                }
                Ok(())
            })
        }
    }
}

impl<T: Config> Pallet<T> {
    /// only use two byte prefix to support 16 byte account id (used by test)
    /// "modl" ++ "dex/stbl" is 12 bytes, and 4 bytes remaining for PoolId
    pub fn pool_account_id(pool_id: &T::PoolId) -> T::AccountId {
        T::PalletId::get().into_sub_account_truncating(pool_id)
    }

    fn inner_add_liquidity(
        who: &T::AccountId,
        pool_id: T::PoolId,
        amounts: &[Balance],
        min_mint_amount: Balance,
        to: &T::AccountId,
    ) -> Result<Balance, DispatchError> {
        Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> Result<Balance, DispatchError> {
            let pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
            match pool {
                Pool::Base(bp) => Self::base_pool_add_liquidity(who, pool_id, bp, amounts, min_mint_amount, to),
                Pool::Meta(mp) => Self::meta_pool_add_liquidity(who, pool_id, mp, amounts, min_mint_amount, to),
            }
        })
    }

    fn inner_swap(
        who: &T::AccountId,
        pool_id: T::PoolId,
        i: usize,
        j: usize,
        in_amount: Balance,
        out_min_amount: Balance,
        to: &T::AccountId,
    ) -> Result<Balance, DispatchError> {
        ensure!(i != j, Error::<T>::SwapSameCurrency);

        Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> Result<Balance, DispatchError> {
            let pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
            match pool {
                Pool::Base(bp) => Self::base_pool_swap(who, pool_id, bp, i, j, in_amount, out_min_amount, to),
                Pool::Meta(mp) => Self::meta_pool_swap(who, pool_id, mp, i, j, in_amount, out_min_amount, to),
            }
        })
    }

    fn inner_remove_liquidity(
        pool_id: T::PoolId,
        who: &T::AccountId,
        lp_amount: Balance,
        min_amounts: &[Balance],
        to: &T::AccountId,
    ) -> DispatchResult {
        Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> DispatchResult {
            ensure!(!lp_amount.is_zero(), Error::<T>::InvalidTransaction);
            let global_pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
            let pool = match global_pool {
                Pool::Base(bp) => bp,
                Pool::Meta(mp) => &mut mp.info,
            };

            let lp_total_supply = T::MultiCurrency::total_issuance(pool.lp_currency_id);

            ensure!(lp_total_supply >= lp_amount, Error::<T>::InsufficientReserve);

            let currencies_length = pool.currency_ids.len();
            let min_amounts_length = min_amounts.len();
            ensure!(currencies_length == min_amounts_length, Error::<T>::MismatchParameter);

            let fees: Vec<Balance> = vec![Zero::zero(); currencies_length];
            let amounts = Self::calculate_base_remove_liquidity(pool, lp_amount).ok_or(Error::<T>::Arithmetic)?;

            for (i, amount) in amounts.iter().enumerate() {
                ensure!(*amount >= min_amounts[i], Error::<T>::AmountSlippage);
                pool.balances[i] = pool.balances[i].checked_sub(*amount).ok_or(Error::<T>::Arithmetic)?;
                T::MultiCurrency::transfer(pool.currency_ids[i], &pool.account, to, *amount)?;
            }

            T::MultiCurrency::withdraw(pool.lp_currency_id, who, lp_amount)?;
            Self::deposit_event(Event::RemoveLiquidity {
                pool_id,
                who: who.clone(),
                to: to.clone(),
                amounts,
                fees,
                new_total_supply: lp_total_supply.saturating_sub(lp_amount),
            });
            Ok(())
        })
    }

    fn inner_remove_liquidity_one_currency(
        pool_id: T::PoolId,
        who: &T::AccountId,
        lp_amount: Balance,
        index: u32,
        min_amount: Balance,
        to: &T::AccountId,
    ) -> Result<Balance, DispatchError> {
        Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> Result<Balance, DispatchError> {
            ensure!(!lp_amount.is_zero(), Error::<T>::InvalidTransaction);
            let pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
            match pool {
                Pool::Base(bp) => {
                    Self::base_pool_remove_liquidity_one_currency(pool_id, bp, who, lp_amount, index, min_amount, to)
                }
                Pool::Meta(mp) => {
                    Self::meta_pool_remove_liquidity_one_currency(pool_id, mp, who, lp_amount, index, min_amount, to)
                }
            }
        })
    }

    fn inner_remove_liquidity_imbalance(
        who: &T::AccountId,
        pool_id: T::PoolId,
        amounts: &[Balance],
        max_burn_amount: Balance,
        to: &T::AccountId,
    ) -> DispatchResult {
        Pools::<T>::try_mutate_exists(pool_id, |optioned_pool| -> DispatchResult {
            let pool = optioned_pool.as_mut().ok_or(Error::<T>::InvalidPoolId)?;
            match pool {
                Pool::Base(bp) => {
                    Self::base_pool_remove_liquidity_imbalance(who, pool_id, bp, amounts, max_burn_amount, to)
                }
                Pool::Meta(mp) => {
                    Self::meta_pool_remove_liquidity_imbalance(who, pool_id, mp, amounts, max_burn_amount, to)
                }
            }
        })
    }

    fn inner_add_pool_and_base_pool_liquidity(
        who: &T::AccountId,
        pool_id: T::PoolId,
        base_pool_id: T::PoolId,
        mut meta_amounts: Vec<Balance>,
        base_amounts: &[Balance],
        min_to_mint: Balance,
        to: &T::AccountId,
    ) -> DispatchResult {
        let base_pool = Self::pools(base_pool_id).ok_or(Error::<T>::InvalidPoolId)?;
        let meta_pool = Self::pools(pool_id).ok_or(Error::<T>::InvalidPoolId)?;
        match meta_pool {
            Pool::Base(_) => Err(Error::<T>::InvalidPoolId),
            Pool::Meta(ref mp) => {
                ensure!(mp.base_pool_id == base_pool_id, Error::<T>::MismatchParameter);
                Ok(())
            }
        }?;

        let base_pool_lp_currency = base_pool.get_lp_currency();
        let meta_pool_currencies = meta_pool.get_currency_ids();
        ensure!(
            meta_amounts.len() == meta_pool_currencies.len(),
            Error::<T>::MismatchParameter
        );

        let mut deposit_base = false;
        for amount in base_amounts.iter() {
            if *amount > Zero::zero() {
                deposit_base = true;
                break;
            }
        }
        let mut base_lp_received: Balance = Balance::default();
        if deposit_base {
            base_lp_received = Self::inner_add_liquidity(who, base_pool_id, base_amounts, 0, who)?;
        }
        let base_lp_prior = <T as Config>::MultiCurrency::free_balance(base_pool_lp_currency, who);

        for (i, c) in meta_pool_currencies.iter().enumerate() {
            if *c == base_pool_lp_currency {
                meta_amounts[i] = base_lp_received;
            }
        }

        Self::inner_add_liquidity(who, pool_id, &meta_amounts, min_to_mint, to)?;

        if deposit_base {
            let base_lp_after = <T as Config>::MultiCurrency::free_balance(base_pool_lp_currency, who);
            ensure!(
                base_lp_after
                    .checked_add(base_lp_received)
                    .and_then(|n| n.checked_sub(base_lp_prior))
                    .ok_or(Error::<T>::Arithmetic)?
                    == Zero::zero(),
                Error::<T>::AmountSlippage
            )
        }

        Ok(())
    }

    fn inner_remove_pool_and_base_pool_liquidity(
        who: &T::AccountId,
        pool_id: T::PoolId,
        base_pool_id: T::PoolId,
        amount: Balance,
        min_amounts_meta: &[Balance],
        min_amounts_base: &[Balance],
        to: &T::AccountId,
    ) -> DispatchResult {
        let base_pool = Self::pools(base_pool_id).ok_or(Error::<T>::InvalidPoolId)?;
        let base_pool_lp_currency = base_pool.get_lp_currency();
        let base_lp_amount_before = <T as Config>::MultiCurrency::free_balance(base_pool_lp_currency, who);

        Self::inner_remove_liquidity(pool_id, who, amount, min_amounts_meta, who)?;

        let base_lp_amount_after = <T as Config>::MultiCurrency::free_balance(base_pool_lp_currency, who);
        let base_lp_amount = base_lp_amount_after
            .checked_sub(base_lp_amount_before)
            .ok_or(Error::<T>::Arithmetic)?;

        Self::inner_remove_liquidity(base_pool_id, who, base_lp_amount, min_amounts_base, to)?;

        Ok(())
    }

    fn inner_remove_pool_and_base_pool_liquidity_one_currency(
        who: &T::AccountId,
        pool_id: T::PoolId,
        base_pool_id: T::PoolId,
        amount: Balance,
        i: u32,
        min_amount: Balance,
        to: &T::AccountId,
    ) -> DispatchResult {
        let base_pool = Self::pools(base_pool_id).ok_or(Error::<T>::InvalidPoolId)?;
        let meta_pool = Self::pools(pool_id).ok_or(Error::<T>::InvalidPoolId)?;
        match meta_pool {
            Pool::Base(_) => Err(Error::<T>::InvalidPoolId),
            Pool::Meta(ref mp) => {
                ensure!(mp.base_pool_id == base_pool_id, Error::<T>::MismatchParameter);
                Ok(())
            }
        }?;

        let base_pool_lp_currency = base_pool.get_lp_currency();
        let meta_pool_currencies = meta_pool.get_currency_ids();

        let mut base_pool_currency_index: Option<u32> = None;
        for (i, c) in meta_pool_currencies.iter().enumerate() {
            if *c == base_pool_lp_currency {
                base_pool_currency_index = Some(i as u32)
            }
        }

        let base_pool_currency_index = base_pool_currency_index.ok_or(Error::<T>::InvalidBasePool)?;

        let base_pool_currency_before = <T as Config>::MultiCurrency::free_balance(base_pool_lp_currency, who);
        Self::inner_remove_liquidity_one_currency(pool_id, who, amount, base_pool_currency_index, 0, who)?;
        let base_pool_currency_after = <T as Config>::MultiCurrency::free_balance(base_pool_lp_currency, who);

        let base_pool_currency_amount = base_pool_currency_after
            .checked_sub(base_pool_currency_before)
            .ok_or(Error::<T>::Arithmetic)?;

        Self::inner_remove_liquidity_one_currency(base_pool_id, who, base_pool_currency_amount, i, min_amount, to)?;

        Ok(())
    }

    fn inner_swap_pool_from_base(
        who: &T::AccountId,
        meta_pool_id: T::PoolId,
        base_pool_id: T::PoolId,
        in_index: u32,
        out_index: u32,
        dx: Balance,
        min_dy: Balance,
        to: &T::AccountId,
    ) -> Result<Balance, DispatchError> {
        let base_pool = Self::pools(base_pool_id).ok_or(Error::<T>::InvalidBasePool)?.info();
        let meta_pool = Self::pools(meta_pool_id).ok_or(Error::<T>::InvalidPoolId)?;

        match meta_pool {
            Pool::Base(_) => Err(Error::<T>::InvalidPoolId),
            Pool::Meta(ref mp) => {
                ensure!(mp.base_pool_id == base_pool_id, Error::<T>::MismatchParameter);
                Ok(())
            }
        }?;

        let meta_pool = meta_pool.info();

        let base_pool_currency = base_pool.lp_currency_id;
        let mut base_pool_lp_currency_in_meta_index = None;

        for (i, c) in meta_pool.currency_ids.iter().enumerate() {
            if *c == base_pool_currency {
                base_pool_lp_currency_in_meta_index = Some(i)
            }
        }
        // ensure meta pool currencies contains the lp currency of base pool
        let base_pool_lp_currency_in_meta_index =
            base_pool_lp_currency_in_meta_index.ok_or(Error::<T>::MismatchParameter)?;

        let base_pool_len = base_pool.currency_ids.len();

        let mut base_amounts = vec![Balance::default(); base_pool_len];
        base_amounts[in_index as usize] = dx;

        let base_lp_amount = Self::inner_add_liquidity(who, base_pool_id, &base_amounts, 0, who)?;

        let mut out_amount: Balance = 0;
        if base_pool_lp_currency_in_meta_index != (out_index as usize) {
            out_amount = Self::inner_swap(
                who,
                meta_pool_id,
                base_pool_lp_currency_in_meta_index,
                out_index as usize,
                base_lp_amount,
                min_dy,
                to,
            )?;
        }

        Ok(out_amount)
    }

    fn inner_swap_pool_to_base(
        who: &T::AccountId,
        pool_id: T::PoolId,
        base_pool_id: T::PoolId,
        in_index: u32,
        out_index: u32,
        dx: Balance,
        min_dy: Balance,
        to: &T::AccountId,
    ) -> Result<Balance, DispatchError> {
        let base_pool_currency = Self::get_lp_currency(base_pool_id).ok_or(Error::<T>::InvalidPoolId)?;
        let base_pool_currency_index =
            Self::get_currency_index(pool_id, base_pool_currency).ok_or(Error::<T>::InvalidBasePool)?;

        let mut base_lp_amount = Balance::default();
        if base_pool_currency_index != in_index {
            base_lp_amount = Self::inner_swap(
                who,
                pool_id,
                in_index as usize,
                base_pool_currency_index as usize,
                dx,
                0,
                who,
            )?;
        }
        let out_amount =
            Self::inner_remove_liquidity_one_currency(base_pool_id, who, base_lp_amount, out_index, min_dy, to)?;

        Ok(out_amount)
    }

    pub(crate) fn calculate_currency_amount(
        pool_id: T::PoolId,
        amounts: Vec<Balance>,
        deposit: bool,
    ) -> Result<Balance, DispatchError> {
        if let Some(pool) = Self::pools(pool_id) {
            match pool {
                Pool::Base(bp) => Self::calculate_base_currency_amount(&bp, amounts, deposit),
                Pool::Meta(mp) => Self::calculate_meta_currency_amount(&mp, amounts, deposit),
            }
        } else {
            Err(Error::<T>::InvalidPoolId.into())
        }
    }

    pub(crate) fn get_admin_balance(pool_id: T::PoolId, currency_index: usize) -> Option<Balance> {
        if let Some(general_pool) = Self::pools(pool_id) {
            let pool = match general_pool {
                Pool::Base(bp) => bp,
                Pool::Meta(mp) => mp.info,
            };
            let currencies_len = pool.currency_ids.len();
            if currency_index >= currencies_len {
                return None;
            }

            let balance = T::MultiCurrency::free_balance(pool.currency_ids[currency_index], &pool.account);

            balance.checked_sub(pool.balances[currency_index])
        } else {
            None
        }
    }
}