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
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
//! # XYK pallet

//! Provides functions for token operations, swapping tokens, creating token pools, minting and burning liquidity and supporting public functions
//!
//! ### Token operation functions:
//! - create_pool
//! - mint_liquidity
//! - burn_liquidity
//! - sell_asset
//! - buy_asset
//! - compound_rewards
//! - provide_liquidity_with_conversion
//!
//! ### Supporting public functions:
//! - calculate_sell_price
//! - calculate_buy_price
//! - calculate_sell_price_id
//! - calculate_buy_price_id
//! - get_liquidity_token
//! - get_burn_amount
//! - account_id
//! - settle_treasury_buy_and_burn
//! - calculate_balanced_sell_amount
//! - get_liq_tokens_for_trading
//!
//! # fn create_pool
//! -Sets the initial ratio/price of both assets to each other depending on amounts of each assets when creating pool.
//!
//! -Transfers assets from user to vault and makes appropriate entry to pools map, where are assets amounts kept.
//!
//! -Issues new liquidity asset in amount corresponding to amounts creating the pool, marks them as liquidity assets corresponding to this pool and transfers them to user.
//! first_token_amount
//! ### arguments
//! `origin` - sender of a fn, user creating the pool
//!
//! `first_token_id` - id of first token which will be directly inter-tradeable in a pair of first_token_id-second_token_id
//!
//! `first_token_amount` - amount of first token in which the pool will be initiated, which will set their initial ratio/price
//!
//! `second_token_id` - id of second token which will be directly inter-tradeable in a pair of first_token_id-second_token_id
//!
//! `second_token_amount` - amount of second token in which the pool will be initiated, which will set their initial ratio/price
//!
//! ### Example
//! ```ignore
//! create_pool(
//!    Origin::signed(1),
//!    0,
//!    1000,
//!    1,
//!    2000,
//! )
//! ```
//! Account_id 1 created pool with tokens 0 and 1, with amounts 1000, 2000. Initial ratio is 1:2. Liquidity token with new id created in an amount of 1500 and transfered to user 1.
//!
//! ### Errors
//! `ZeroAmount` - creating pool with 0 amount of first or second token
//!
//! `PoolAlreadyExists` - creating pool which already exists
//!
//! `NotEnoughTokens` - creating pool with amounts higher then user owns
//!
//! `SameToken` - creating pool with same token
//!
//! # fn sell_token
//! -Sells/exchanges set amount of sold token for corresponding amount by xyk formula of bought token
//! ### arguments
//! `origin` - sender of a fn, user creating the pool
//!
//! `sold_token_id` - token which will be sold
//!
//! `bought_token_id` - token which will be bought
//!
//! `sold_token_amount` - amount of token to be sold
//!
//! `min_amount_out` - minimal acceptable amount of bought token received after swap
//!
//! ### Example
//! ```ignore
//! sell_token (
//!    Origin::signed(1),
//!    0,
//!    1,
//!    1000,
//!    800,
//!)
//! ```
//! Account_id 1 sells/exchanges 1000 token 0 for corresponding amount of token 1, while requiring at least 800 token 1
//!
//! ### Errors
//! `ZeroAmount` - buying 0 tokens
//!
//! `NoSuchPool` - pool sold_token_id - bought_token_id does not exist
//!
//! `NotEnoughTokens` - selling more tokens then user owns
//!
//! `InsufficientOutputAmount` - bought tokens to receive amount is lower then required min_amount_out
//!
//! # fn buy_token
//! -Buys/exchanges set amount of bought token for corresponding amount by xyk formula of sold token
//! ### arguments
//! `origin` - sender of a fn, user creating the pool
//!
//! `sold_token_id` - token which will be sold
//!
//! `bought_token_id` - token which will be bought
//!
//! `bought_token_amount` - amount of token to be bought
//!
//! `max_amount_in` - maximal acceptable amount of sold token to pay for requested bought amount
//!
//! ### Example
//! ```ignore
//! buy_token (
//!    Origin::signed(1),
//!    0,
//!    1,
//!    1000,
//!    800,
//!)
//! ```
//! Account_id 1 buys/exchanges 1000 tokens 1 by paying corresponding amount by xyk formula of tokens 0
//!
//! ### Errors
//! `ZeroAmount` - selling 0 tokens
//!
//! `NoSuchPool` - pool sold_token_id - bought_token_id does not exist
//!
//! `NotEnoughTokens` - selling more tokens then user owns
//!
//! `InsufficientInputAmount` - sold tokens to pay is higher then maximum acceptable value of max_amount_in
//!
//! # fn mint_liquidity
//! -Adds liquidity to pool, providing both tokens in actual ratio
//! -First token amount is provided by user, second token amount is calculated by function, depending on actual ratio
//! -Mints and transfers corresponding amount of liquidity token to mintin user
//!
//! ### arguments
//! `origin` - sender of a fn, user creating the pool
//!
//! first_token_id - first token in pair
//!
//! second_token_id - second token in pair
//!
//! first_token_amount - amount of first_token_id, second token amount will be calculated
//!
//! ### Example
//! ```ignore
//! mint_liquidity (
//!    Origin::signed(1),
//!    0,
//!    1,
//!    1000,
//!)
//! ```
//! If pool token 0 - token 1 has tokens in amounts 9000:18000 (total liquidity tokens 27000)
//!
//! Account_id 1 added liquidity to pool token 0 - token 1, by providing 1000 token 0 and corresponding amount of token 1. In this case 2000, as the ratio in pool is 1:2.
//! Account_id 1 also receives corresponding liquidity tokens in corresponding amount. In this case he gets 10% of all corresponding liquidity tokens, as he is providing 10% of all provided liquidity in pool.
//! 3000 out of total 30000 liquidity tokens is now owned by Account_id 1
//!
//! ### Errors
//! `ZeroAmount` - minting with 0 tokens
//!
//! `NoSuchPool` - pool first_token_id - second_token_id does not exist
//!
//! `NotEnoughTokens` -  minting with more tokens then user owns, either first_token_id or second_token_id
//!
//! # fn burn_liquidity
//! -Removes tokens from liquidity pool and transfers them to user, by burning user owned liquidity tokens
//! -Amount of tokens is determined by their ratio in pool and amount of liq tokens burned
//!
//! ### arguments
//! `origin` - sender of a fn, user creating the pool
//!
//! first_token_id - first token in pair
//!
//! second_token_id - second token in pair
//!
//! liquidity_token_amount - amount of liquidity token amount to burn
//!
//! ### Example
//! ```ignore
//! burn_liquidity (
//!    Origin::signed(1),
//!    0,
//!    1,
//!    3000,
//!)
//! ```
//! If pool token 0 - token 1 has tokens in amounts 10000:20000 (total liquidity tokens 30000)
//!
//! Account_id 1 is burning 3000 liquidity tokens of pool token 0 - token 1
//! As Account_id 1 is burning 10% of total liquidity tokens for this pool, user receives in this case 1000 token 0 and 2000 token 1
//!
//! ### Errors
//! `ZeroAmount` - burning 0 liquidity tokens
//!
//! `NoSuchPool` - pool first_token_id - second_token_id does not exist
//!
//! `NotEnoughTokens` -  burning more liquidity tokens than user owns
//!
//! # fn compound_rewards
//! - Claims a specified portion of rewards, and provides them back into the selected pool.
//! - Wraps claim_rewards, sell_asset and mint_liquidity, so that there is minimal surplus of reward asset left after operation.
//! - Current impl assumes a MGX-ASSET pool & rewards in MGX asset
//!
//! ### arguments
//! `origin` - sender of a fn, user claiming rewards and providing liquidity to the pool
//!
//! liquidity_asset_id - the pool where we provide the liquidity
//!
//! amount_permille - portion of rewards to claim
//!
//! ### Example
//! ```ignore
//! compound_rewards (
//!    Origin::signed(1),
//!    2,
//!    1_000,
//!)
//! ```
//! Claim all of the rewards, currently in MGX, and use them to provide liquidity for the pool with asset id 2
//!
//! ### Errors
//! - inherits all of the errors from `claim_rewards`, `sell_asset` and `mint_liquidity`
//!
//! `NoSuchLiquidityAsset` - pool with given asset id does not exist
//!
//! `FunctionNotAvailableForThisToken` - not available for this asset id
//!
//! `NotEnoughRewardsEarned` - not enough rewards available
//!
//! # fn provide_liquidity_with_conversion
//! - Given one of the liquidity pool asset, computes balanced sell amount and provides liquidity into the pool
//! - Wraps sell_asset and mint_liquidity
//!
//! ### arguments
//! `origin` - sender of a fn, user claiming rewards and providing liquidity to the pool
//!
//! liquidity_asset_id - the pool where we provide the liquidity
//!
//! provided_asset_id - which asset of the pool
//!
//! provided_asset_amount - amount of the provided asset to use
//!
//! ### Example
//! ```ignore
//! provide_liquidity_with_conversion (
//!    Origin::signed(1),
//!    2,
//!    1,
//!    1_000_000,
//!)
//! ```
//! Given the liquidity pool with asset id 2, we assume that asset id 1 is one of the pool's pair, compute balanced swap and provide liquidity into the pool
//!
//! ### Errors
//! - inherits all of the errors from `sell_asset` and `mint_liquidity`
//!
//! `NoSuchLiquidityAsset` - pool wiht given asset id does not exist
//!
//! `FunctionNotAvailableForThisToken` - not available for this asset id
//!
//! # calculate_sell_price
//! - Supporting public function accessible through rpc call which calculates and returns bought_token_amount while providing sold_token_amount and respective reserves
//! # calculate_buy_price
//! - Supporting public function accessible through rpc call which calculates and returns sold_token_amount while providing bought_token_amount and respective reserves
//! # calculate_sell_price_id
//! - Same as calculate_sell_price, but providing token_id instead of reserves. Reserves are fetched by function.
//! # calculate_buy_price_id
//! - Same as calculate_buy_price, but providing token_id instead of reserves. Reserves are fetched by function.
//! # get_liquidity_token
//! - Supporting public function accessible through rpc call which returns liquidity_token_id while providing pair token ids
//! # get_burn_amount
//! - Supporting public function accessible through rpc call which returns amounts of tokens received by burning provided liquidity_token_amount in pool of provided token ids
//! # account_id
//! - Returns palled account_id
//! # settle_treasury_buy_and_burn
//! - Supporting function which takes tokens to alocate to treasury and tokens to be used to burn mangata
//! - First step is deciding whether we are using sold or bought token id, depending which is closer to mangata token
//! - In second step, if tokens are mangata, they are placed to treasury and removed from corresponding pool. If tokens are not mangata, but are available in mangata pool,
//!   they are swapped to mangata and placed to treasury and removed from corresponding pool. If token is not connected to mangata, token is temporarily placed to treasury and burn treasury.
//! # calculate_balanced_sell_amount
//! - Supporting public function accessible through rpc call which calculates how much amount x we need to swap from total_amount, so that after `y = swap(x)`, the resulting balance equals `(total_amount - x) / y = pool_x / pool_y`
//! - the resulting amounts can then be used to `mint_liquidity` with minimal leftover after operation
//! # get_liq_tokens_for_trading
//! - Supporting public function accessible through rpc call which lists all of the liquidity pool token ids that are available for trading

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

use frame_support::{
	assert_ok,
	dispatch::{DispatchErrorWithPostInfo, DispatchResult, PostDispatchInfo},
	ensure,
	traits::Contains,
	PalletId,
};
use frame_system::ensure_signed;
use sp_core::U256;

use frame_support::{
	pallet_prelude::*,
	traits::{
		tokens::currency::{MultiTokenCurrency, MultiTokenVestingLocks},
		ExistenceRequirement, Get, WithdrawReasons,
	},
	transactional,
};
use frame_system::pallet_prelude::*;
use mangata_support::traits::{
	ActivationReservesProviderTrait, GetMaintenanceStatusTrait, PoolCreateApi, PreValidateSwaps,
	ProofOfStakeRewardsApi, Valuate, XykFunctionsTrait,
};
use mangata_types::multipurpose_liquidity::ActivateKind;
use orml_tokens::{MultiTokenCurrencyExtended, MultiTokenReservableCurrency};
use sp_arithmetic::{helpers_128bit::multiply_by_rational_with_rounding, per_things::Rounding};
use sp_runtime::{
	traits::{
		AccountIdConversion, Bounded, CheckedAdd, CheckedDiv, CheckedSub, One, Saturating, Zero,
	},
	DispatchError, ModuleError, Permill, SaturatedConversion,
};
use sp_std::{
	collections::btree_set::BTreeSet,
	convert::{TryFrom, TryInto},
	ops::Div,
	prelude::*,
	vec,
};

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

pub(crate) const LOG_TARGET: &str = "xyk";

// syntactic sugar for logging.
#[macro_export]
macro_rules! log {
	($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
		log::$level!(
			target: $crate::LOG_TARGET,
			concat!("[{:?}] 💸 ", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
		)
	};
}

const PALLET_ID: PalletId = PalletId(*b"79b14c96");

// Keywords for asset_info
const LIQUIDITY_TOKEN_IDENTIFIER: &[u8] = b"LiquidityPoolToken";
const HEX_INDICATOR: &[u8] = b"0x";
const TOKEN_SYMBOL: &[u8] = b"TKN";
const TOKEN_SYMBOL_SEPARATOR: &[u8] = b"-";
const DEFAULT_DECIMALS: u32 = 18u32;

pub use pallet::*;

mod benchmarking;
pub mod weights;
pub use weights::WeightInfo;

type AccountIdOf<T> = <T as frame_system::Config>::AccountId;

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

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

// type LiquidityMiningRewardsOf<T> = <T as ::Config>::AccountId;
#[derive(Eq, PartialEq, Encode, Decode)]
pub enum SwapKind {
	Sell,
	Buy,
}

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

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

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

	#[cfg(feature = "runtime-benchmarks")]
	pub trait XykBenchmarkingConfig:
		pallet_issuance::Config + pallet_proof_of_stake::Config
	{
	}

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

	// #[cfg(feature = "runtime-benchmarks")]
	// pub trait XykRewardsApi<AccountIdT>: ProofOfStakeRewardsApi<AccountIdT, Balance = Balance, CurrencyId = CurrencyIdOf<T>> + LiquidityMiningApi{}
	// #[cfg(feature = "runtime-benchmarks")]
	// impl<K,AccountIdT> XykRewardsApi<AccountIdT> for K where
	// 	K: ProofOfStakeRewardsApi<AccountIdT, Balance = Balance, CurrencyId = CurrencyIdOf<T>>,
	// 	K: LiquidityMiningApi,
	// {
	// }
	//
	// #[cfg(not(feature = "runtime-benchmarks"))]
	// pub trait XykRewardsApi<AccountIdT>: ProofOfStakeRewardsApi<AccountIdT, Balance = Balance, CurrencyId = CurrencyIdOf<T>>{}
	// #[cfg(not(feature = "runtime-benchmarks"))]
	// impl<K,AccountIdT> XykRewardsApi<AccountIdT> for K where
	// 	K: ProofOfStakeRewardsApi<AccountIdT, Balance = Balance, CurrencyId = CurrencyIdOf<T>>,
	// {
	// }

	#[pallet::config]
	pub trait Config: frame_system::Config + XykBenchmarkingConfig {
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
		type MaintenanceStatusProvider: GetMaintenanceStatusTrait;
		type ActivationReservesProvider: ActivationReservesProviderTrait<
			Self::AccountId,
			BalanceOf<Self>,
			CurrencyIdOf<Self>,
		>;
		type Currency: MultiTokenCurrencyExtended<Self::AccountId>
			+ MultiTokenReservableCurrency<Self::AccountId>;
		type NativeCurrencyId: Get<CurrencyIdOf<Self>>;
		type TreasuryPalletId: Get<PalletId>;
		type BnbTreasurySubAccDerive: Get<[u8; 4]>;
		type LiquidityMiningRewards: ProofOfStakeRewardsApi<
			Self::AccountId,
			BalanceOf<Self>,
			CurrencyIdOf<Self>,
		>;
		#[pallet::constant]
		type PoolFeePercentage: Get<u128>;
		#[pallet::constant]
		type TreasuryFeePercentage: Get<u128>;
		#[pallet::constant]
		type BuyAndBurnFeePercentage: Get<u128>;
		type DisallowedPools: Contains<(CurrencyIdOf<Self>, CurrencyIdOf<Self>)>;
		type DisabledTokens: Contains<CurrencyIdOf<Self>>;
		type VestingProvider: MultiTokenVestingLocks<
			Self::AccountId,
			Currency = <Self as pallet::Config>::Currency,
			Moment = BlockNumberFor<Self>,
		>;
		type AssetMetadataMutation: AssetMetadataMutationTrait<CurrencyIdOf<Self>>;
		type WeightInfo: WeightInfo;
	}

	#[pallet::error]
	/// Errors
	pub enum Error<T> {
		/// Pool already Exists
		PoolAlreadyExists,
		/// Not enought assets
		NotEnoughAssets,
		/// No such pool exists
		NoSuchPool,
		/// No such liquidity asset exists
		NoSuchLiquidityAsset,
		/// Not enought reserve
		NotEnoughReserve,
		/// Zero amount is not supported
		ZeroAmount,
		/// Insufficient input amount
		InsufficientInputAmount,
		/// Insufficient output amount
		InsufficientOutputAmount,
		/// Asset ids cannot be the same
		SameAsset,
		/// Asset already exists
		AssetAlreadyExists,
		/// Asset does not exists
		AssetDoesNotExists,
		/// Division by zero
		DivisionByZero,
		/// Unexpected failure
		UnexpectedFailure,
		/// Unexpected failure
		NotMangataLiquidityAsset,
		/// Second asset amount exceeded expectations
		SecondAssetAmountExceededExpectations,
		/// Math overflow
		MathOverflow,
		/// Liquidity token creation failed
		LiquidityTokenCreationFailed,
		/// Not enough rewards earned
		NotEnoughRewardsEarned,
		/// Not a promoted pool
		NotAPromotedPool,
		/// Past time calculation
		PastTimeCalculation,
		/// Pool already promoted
		PoolAlreadyPromoted,
		/// Sold Amount too low
		SoldAmountTooLow,
		/// Asset id is blacklisted
		FunctionNotAvailableForThisToken,
		/// Pool considting of passed tokens id is blacklisted
		DisallowedPool,
		LiquidityCheckpointMathError,
		CalculateRewardsMathError,
		CalculateCumulativeWorkMaxRatioMathError,
		CalculateRewardsAllMathError,
		NoRights,
		MultiswapShouldBeAtleastTwoHops,
		MultiBuyAssetCantHaveSamePoolAtomicSwaps,
		MultiSwapCantHaveSameTokenConsequetively,
		/// Trading blocked by maintenance mode
		TradingBlockedByMaintenanceMode,
		PoolIsEmpty,
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
	pub enum Event<T: Config> {
		PoolCreated(T::AccountId, CurrencyIdOf<T>, BalanceOf<T>, CurrencyIdOf<T>, BalanceOf<T>),
		AssetsSwapped(T::AccountId, Vec<CurrencyIdOf<T>>, BalanceOf<T>, BalanceOf<T>),
		SellAssetFailedDueToSlippage(
			T::AccountId,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			BalanceOf<T>,
		),
		BuyAssetFailedDueToSlippage(
			T::AccountId,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			BalanceOf<T>,
		),
		LiquidityMinted(
			T::AccountId,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
			BalanceOf<T>,
		),
		LiquidityBurned(
			T::AccountId,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
			BalanceOf<T>,
		),
		PoolPromotionUpdated(CurrencyIdOf<T>, Option<u8>),
		LiquidityActivated(T::AccountId, CurrencyIdOf<T>, BalanceOf<T>),
		LiquidityDeactivated(T::AccountId, CurrencyIdOf<T>, BalanceOf<T>),
		RewardsClaimed(T::AccountId, CurrencyIdOf<T>, BalanceOf<T>),
		MultiSwapAssetFailedOnAtomicSwap(
			T::AccountId,
			Vec<CurrencyIdOf<T>>,
			BalanceOf<T>,
			ModuleError,
		),
	}

	#[pallet::storage]
	#[pallet::getter(fn asset_pool)]
	pub type Pools<T: Config> = StorageMap<
		_,
		Blake2_256,
		(CurrencyIdOf<T>, CurrencyIdOf<T>),
		(BalanceOf<T>, BalanceOf<T>),
		ValueQuery,
	>;

	#[pallet::storage]
	#[pallet::getter(fn liquidity_asset)]
	pub type LiquidityAssets<T: Config> = StorageMap<
		_,
		Blake2_256,
		(CurrencyIdOf<T>, CurrencyIdOf<T>),
		Option<CurrencyIdOf<T>>,
		ValueQuery,
	>;

	#[pallet::storage]
	#[pallet::getter(fn liquidity_pool)]
	pub type LiquidityPools<T: Config> = StorageMap<
		_,
		Blake2_256,
		CurrencyIdOf<T>,
		Option<(CurrencyIdOf<T>, CurrencyIdOf<T>)>,
		ValueQuery,
	>;

	#[pallet::genesis_config]
	pub struct GenesisConfig<T: Config> {
		pub created_pools_for_staking: Vec<(
			T::AccountId,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
		)>,
	}

	impl<T: Config> Default for GenesisConfig<T> {
		fn default() -> Self {
			GenesisConfig { created_pools_for_staking: vec![] }
		}
	}

	#[pallet::genesis_build]
	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
		fn build(&self) {
			self.created_pools_for_staking.iter().for_each(
				|(
					account_id,
					native_token_id,
					native_token_amount,
					pooled_token_id,
					pooled_token_amount,
					liquidity_token_id,
				)| {
					if <T as Config>::Currency::exists({ *liquidity_token_id }.into()) {
						assert!(
							<Pallet<T> as XykFunctionsTrait<
								T::AccountId,
								BalanceOf<T>,
								CurrencyIdOf<T>,
							>>::mint_liquidity(
								account_id.clone(),
								*native_token_id,
								*pooled_token_id,
								*native_token_amount,
								*pooled_token_amount,
								true,
							)
							.is_ok(),
							"Pool mint failed"
						);
					} else {
						let created_liquidity_token_id: CurrencyIdOf<T> =
							<T as Config>::Currency::get_next_currency_id().into();
						assert_eq!(
							created_liquidity_token_id, *liquidity_token_id,
							"Assets not initialized in the expected sequence",
						);
						assert_ok!(<Pallet<T> as XykFunctionsTrait<
							T::AccountId,
							BalanceOf<T>,
							CurrencyIdOf<T>,
						>>::create_pool(
							account_id.clone(),
							*native_token_id,
							*native_token_amount,
							*pooled_token_id,
							*pooled_token_amount
						));
					}
				},
			)
		}
	}

	// XYK extrinsics.
	#[pallet::call]
	impl<T: Config> Pallet<T> {
		#[pallet::call_index(0)]
		#[pallet::weight(<<T as Config>::WeightInfo>::create_pool())]
		pub fn create_pool(
			origin: OriginFor<T>,
			first_asset_id: CurrencyIdOf<T>,
			first_asset_amount: BalanceOf<T>,
			second_asset_id: CurrencyIdOf<T>,
			second_asset_amount: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			ensure!(
				!T::DisabledTokens::contains(&first_asset_id) &&
					!T::DisabledTokens::contains(&second_asset_id),
				Error::<T>::FunctionNotAvailableForThisToken
			);

			ensure!(
				!T::DisallowedPools::contains(&(first_asset_id, second_asset_id)),
				Error::<T>::DisallowedPool,
			);

			<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::create_pool(
				sender,
				first_asset_id,
				first_asset_amount,
				second_asset_id,
				second_asset_amount,
			)?;

			Ok(().into())
		}

		/// Executes sell_asset swap.
		/// First the swap is prevalidated, if it is successful then the extrinsic is accepted. Beyond this point the exchange commission will be charged.
		/// The sold amount of the sold asset is used to determine the bought asset amount.
		/// If the bought asset amount is lower than the min_amount_out then it will fail on slippage.
		/// The percentage exchange commission is still charged even if the swap fails on slippage. Though the swap itself will be a no-op.
		/// The slippage is calculated based upon the sold_asset_amount.
		/// Upon slippage failure, the extrinsic is marked "successful", but an event for the failure is emitted
		///
		///
		/// # Args:
		/// - `sold_asset_id` - The token being sold
		/// - `bought_asset_id` - The token being bought
		/// - `sold_asset_amount`: The amount of the sold token being sold
		/// - `min_amount_out` - The minimum amount of bought asset that must be bought in order to not fail on slippage. Slippage failures still charge exchange commission.
		#[pallet::call_index(1)]
		#[pallet::weight((<<T as Config>::WeightInfo>::sell_asset(), DispatchClass::Operational, Pays::No))]
		#[deprecated(note = "multiswap_sell_asset should be used instead")]
		pub fn sell_asset(
			origin: OriginFor<T>,
			sold_asset_id: CurrencyIdOf<T>,
			bought_asset_id: CurrencyIdOf<T>,
			sold_asset_amount: BalanceOf<T>,
			min_amount_out: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::sell_asset(
				sender,
				sold_asset_id,
				bought_asset_id,
				sold_asset_amount,
				min_amount_out,
				false,
			)
			.map_err(|err| DispatchErrorWithPostInfo {
				post_info: PostDispatchInfo {
					actual_weight: Some(<<T as Config>::WeightInfo>::sell_asset()),
					pays_fee: Pays::Yes,
				},
				error: err,
			})?;
			Ok(Pays::No.into())
		}

		/// Executes a multiswap sell asset in a series of sell asset atomic swaps.
		///
		/// Multiswaps must fee lock instead of paying transaction fees.
		///
		/// First the multiswap is prevalidated, if it is successful then the extrinsic is accepted
		/// and the exchange commission will be charged upon execution on the **first** swap using **sold_asset_amount**.
		///
		/// Upon failure of an atomic swap or bad slippage, all the atomic swaps are reverted and the exchange commission is charged.
		/// Upon such a failure, the extrinsic is marked "successful", but an event for the failure is emitted
		///
		/// # Args:
		/// - `swap_token_list` - This list of tokens is the route of the atomic swaps, starting with the asset sold and ends with the asset finally bought
		/// - `sold_asset_amount`: The amount of the first asset sold
		/// - `min_amount_out` - The minimum amount of last asset that must be bought in order to not fail on slippage. Slippage failures still charge exchange commission.
		#[pallet::call_index(2)]
		#[pallet::weight((<<T as Config>::WeightInfo>::multiswap_sell_asset(swap_token_list.len() as u32), DispatchClass::Operational, Pays::No))]
		pub fn multiswap_sell_asset(
			origin: OriginFor<T>,
			swap_token_list: Vec<CurrencyIdOf<T>>,
			sold_asset_amount: BalanceOf<T>,
			min_amount_out: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			if let (Some(sold_asset_id), Some(bought_asset_id), 2) =
				(swap_token_list.get(0), swap_token_list.get(1), swap_token_list.len())
			{
				<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::sell_asset(
					sender,
					*sold_asset_id,
					*bought_asset_id,
					sold_asset_amount,
					min_amount_out,
					false,
				)
			} else {
				<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::multiswap_sell_asset(
					sender,
					swap_token_list.clone(),
					sold_asset_amount,
					min_amount_out,
					false,
					false,
				)
			}
			.map_err(|err| DispatchErrorWithPostInfo {
				post_info: PostDispatchInfo {
					actual_weight: Some(<<T as Config>::WeightInfo>::multiswap_sell_asset(
						swap_token_list.len() as u32,
					)),
					pays_fee: Pays::Yes,
				},
				error: err,
			})?;
			Ok(Pays::No.into())
		}

		/// Executes buy_asset swap.
		/// First the swap is prevalidated, if it is successful then the extrinsic is accepted. Beyond this point the exchange commission will be charged.
		/// The bought of the bought asset is used to determine the sold asset amount.
		/// If the sold asset amount is higher than the max_amount_in then it will fail on slippage.
		/// The percentage exchange commission is still charged even if the swap fails on slippage. Though the swap itself will be a no-op.
		/// The slippage is calculated based upon the sold asset amount.
		/// Upon slippage failure, the extrinsic is marked "successful", but an event for the failure is emitted
		///
		///
		/// # Args:
		/// - `sold_asset_id` - The token being sold
		/// - `bought_asset_id` - The token being bought
		/// - `bought_asset_amount`: The amount of the bought token being bought
		/// - `max_amount_in` - The maximum amount of sold asset that must be sold in order to not fail on slippage. Slippage failures still charge exchange commission.
		#[pallet::call_index(3)]
		#[pallet::weight((<<T as Config>::WeightInfo>::buy_asset(), DispatchClass::Operational, Pays::No))]
		#[deprecated(note = "multiswap_buy_asset should be used instead")]
		pub fn buy_asset(
			origin: OriginFor<T>,
			sold_asset_id: CurrencyIdOf<T>,
			bought_asset_id: CurrencyIdOf<T>,
			bought_asset_amount: BalanceOf<T>,
			max_amount_in: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::buy_asset(
				sender,
				sold_asset_id,
				bought_asset_id,
				bought_asset_amount,
				max_amount_in,
				false,
			)
			.map_err(|err| DispatchErrorWithPostInfo {
				post_info: PostDispatchInfo {
					actual_weight: Some(<<T as Config>::WeightInfo>::buy_asset()),
					pays_fee: Pays::Yes,
				},
				error: err,
			})?;
			Ok(Pays::No.into())
		}

		/// Executes a multiswap buy asset in a series of buy asset atomic swaps.
		///
		/// Multiswaps must fee lock instead of paying transaction fees.
		///
		/// First the multiswap is prevalidated, if it is successful then the extrinsic is accepted
		/// and the exchange commission will be charged upon execution on the *first* swap using *max_amount_in*.
		/// multiswap_buy_asset cannot have two (or more) atomic swaps on the same pool.
		/// multiswap_buy_asset prevaildation only checks for whether there are enough funds to pay for the exchange commission.
		/// Failure to have the required amount of first asset funds will result in failure (and charging of the exchange commission).
		///
		/// Upon failure of an atomic swap or bad slippage, all the atomic swaps are reverted and the exchange commission is charged.
		/// Upon such a failure, the extrinsic is marked "successful", but an event for the failure is emitted
		///
		/// # Args:
		/// - `swap_token_list` - This list of tokens is the route of the atomic swaps, starting with the asset sold and ends with the asset finally bought
		/// - `bought_asset_amount`: The amount of the last asset bought
		/// - `max_amount_in` - The maximum amount of first asset that can be sold in order to not fail on slippage. Slippage failures still charge exchange commission.
		#[pallet::call_index(4)]
		#[pallet::weight((<<T as Config>::WeightInfo>::multiswap_buy_asset(swap_token_list.len() as u32), DispatchClass::Operational, Pays::No))]
		pub fn multiswap_buy_asset(
			origin: OriginFor<T>,
			swap_token_list: Vec<CurrencyIdOf<T>>,
			bought_asset_amount: BalanceOf<T>,
			max_amount_in: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			if let (Some(sold_asset_id), Some(bought_asset_id), 2) =
				(swap_token_list.get(0), swap_token_list.get(1), swap_token_list.len())
			{
				<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::buy_asset(
					sender,
					*sold_asset_id,
					*bought_asset_id,
					bought_asset_amount,
					max_amount_in,
					false,
				)
			} else {
				<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::multiswap_buy_asset(
					sender,
					swap_token_list.clone(),
					bought_asset_amount,
					max_amount_in,
					false,
					false,
				)
			}
			.map_err(|err| DispatchErrorWithPostInfo {
				post_info: PostDispatchInfo {
					actual_weight: Some(<<T as Config>::WeightInfo>::multiswap_buy_asset(
						swap_token_list.len() as u32,
					)),
					pays_fee: Pays::Yes,
				},
				error: err,
			})?;
			Ok(Pays::No.into())
		}

		#[pallet::call_index(5)]
		#[pallet::weight(<<T as Config>::WeightInfo>::mint_liquidity_using_vesting_native_tokens())]
		#[transactional]
		pub fn mint_liquidity_using_vesting_native_tokens_by_vesting_index(
			origin: OriginFor<T>,
			native_asset_vesting_index: u32,
			vesting_native_asset_unlock_some_amount_or_all: Option<BalanceOf<T>>,
			second_asset_id: CurrencyIdOf<T>,
			expected_second_asset_amount: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			let liquidity_asset_id =
				Pallet::<T>::get_liquidity_asset(Self::native_token_id(), second_asset_id)?;

			ensure!(
				<T::LiquidityMiningRewards as ProofOfStakeRewardsApi<
					T::AccountId,
					BalanceOf<T>,
					CurrencyIdOf<T>,
				>>::is_enabled(liquidity_asset_id),
				Error::<T>::NotAPromotedPool
			);

			let (unlocked_amount, vesting_starting_block, vesting_ending_block_as_balance): (
				BalanceOf<T>,
				BlockNumberFor<T>,
				BalanceOf<T>,
			) = <<T as Config>::VestingProvider>::unlock_tokens_by_vesting_index(
				&sender,
				Self::native_token_id().into(),
				native_asset_vesting_index,
				vesting_native_asset_unlock_some_amount_or_all,
			)
			.map(|x| (x.0, x.1, x.2))?;

			let (liquidity_token_id, liquidity_assets_minted) = <Self as XykFunctionsTrait<
				T::AccountId,
				BalanceOf<T>,
				CurrencyIdOf<T>,
			>>::mint_liquidity(
				sender.clone(),
				Self::native_token_id(),
				second_asset_id,
				unlocked_amount,
				expected_second_asset_amount,
				false,
			)?;

			<<T as Config>::VestingProvider>::lock_tokens(
				&sender,
				liquidity_token_id.into(),
				liquidity_assets_minted,
				Some(vesting_starting_block),
				vesting_ending_block_as_balance,
			)?;

			Ok(().into())
		}

		#[pallet::call_index(6)]
		#[pallet::weight(<<T as Config>::WeightInfo>::mint_liquidity_using_vesting_native_tokens())]
		#[transactional]
		pub fn mint_liquidity_using_vesting_native_tokens(
			origin: OriginFor<T>,
			vesting_native_asset_amount: BalanceOf<T>,
			second_asset_id: CurrencyIdOf<T>,
			expected_second_asset_amount: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			let liquidity_asset_id =
				Pallet::<T>::get_liquidity_asset(Self::native_token_id(), second_asset_id)?;

			ensure!(
				<T::LiquidityMiningRewards as ProofOfStakeRewardsApi<
					T::AccountId,
					BalanceOf<T>,
					CurrencyIdOf<T>,
				>>::is_enabled(liquidity_asset_id),
				Error::<T>::NotAPromotedPool
			);

			let (vesting_starting_block, vesting_ending_block_as_balance): (
				BlockNumberFor<T>,
				BalanceOf<T>,
			) = <<T as Config>::VestingProvider>::unlock_tokens(
				&sender,
				Self::native_token_id().into(),
				vesting_native_asset_amount,
			)
			.map(|x| (x.0, x.1))?;

			let (liquidity_token_id, liquidity_assets_minted) = <Self as XykFunctionsTrait<
				T::AccountId,
				BalanceOf<T>,
				CurrencyIdOf<T>,
			>>::mint_liquidity(
				sender.clone(),
				Self::native_token_id(),
				second_asset_id,
				vesting_native_asset_amount,
				expected_second_asset_amount,
				false,
			)?;

			<<T as Config>::VestingProvider>::lock_tokens(
				&sender,
				liquidity_token_id.into(),
				liquidity_assets_minted,
				Some(vesting_starting_block),
				vesting_ending_block_as_balance,
			)?;

			Ok(().into())
		}

		#[pallet::call_index(7)]
		#[pallet::weight(<<T as Config>::WeightInfo>::mint_liquidity())]
		pub fn mint_liquidity(
			origin: OriginFor<T>,
			first_asset_id: CurrencyIdOf<T>,
			second_asset_id: CurrencyIdOf<T>,
			first_asset_amount: BalanceOf<T>,
			expected_second_asset_amount: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			ensure!(
				!T::DisabledTokens::contains(&first_asset_id) &&
					!T::DisabledTokens::contains(&second_asset_id),
				Error::<T>::FunctionNotAvailableForThisToken
			);

			<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::mint_liquidity(
				sender,
				first_asset_id,
				second_asset_id,
				first_asset_amount,
				expected_second_asset_amount,
				true,
			)?;

			Ok(().into())
		}

		#[pallet::call_index(8)]
		#[pallet::weight(<<T as Config>::WeightInfo>::compound_rewards())]
		#[transactional]
		pub fn compound_rewards(
			origin: OriginFor<T>,
			liquidity_asset_id: CurrencyIdOf<T>,
			amount_permille: Permill,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::do_compound_rewards(
				sender,
				liquidity_asset_id,
				amount_permille,
			)?;

			Ok(().into())
		}

		#[pallet::call_index(9)]
		#[pallet::weight(<<T as Config>::WeightInfo>::provide_liquidity_with_conversion())]
		#[transactional]
		pub fn provide_liquidity_with_conversion(
			origin: OriginFor<T>,
			liquidity_asset_id: CurrencyIdOf<T>,
			provided_asset_id: CurrencyIdOf<T>,
			provided_asset_amount: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			let (first_asset_id, second_asset_id) = LiquidityPools::<T>::get(liquidity_asset_id)
				.ok_or(Error::<T>::NoSuchLiquidityAsset)?;

			ensure!(
				!T::DisabledTokens::contains(&first_asset_id) &&
					!T::DisabledTokens::contains(&second_asset_id),
				Error::<T>::FunctionNotAvailableForThisToken
			);

			<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::provide_liquidity_with_conversion(
				sender,
				first_asset_id,
				second_asset_id,
				provided_asset_id,
				provided_asset_amount,
				true,
			)?;

			Ok(().into())
		}

		#[pallet::call_index(10)]
		#[pallet::weight(<<T as Config>::WeightInfo>::burn_liquidity())]
		pub fn burn_liquidity(
			origin: OriginFor<T>,
			first_asset_id: CurrencyIdOf<T>,
			second_asset_id: CurrencyIdOf<T>,
			liquidity_asset_amount: BalanceOf<T>,
		) -> DispatchResultWithPostInfo {
			let sender = ensure_signed(origin)?;

			<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::burn_liquidity(
				sender,
				first_asset_id,
				second_asset_id,
				liquidity_asset_amount,
			)?;

			Ok(().into())
		}
	}
}

impl<T: Config> Pallet<T> {
	fn total_fee() -> u128 {
		T::PoolFeePercentage::get() +
			T::TreasuryFeePercentage::get() +
			T::BuyAndBurnFeePercentage::get()
	}

	pub fn get_max_instant_burn_amount(
		user: &AccountIdOf<T>,
		liquidity_asset_id: CurrencyIdOf<T>,
	) -> BalanceOf<T> {
		Self::get_max_instant_unreserve_amount(user, liquidity_asset_id).saturating_add(
			<T as Config>::Currency::available_balance(liquidity_asset_id.into(), user),
		)
	}

	pub fn get_max_instant_unreserve_amount(
		user: &AccountIdOf<T>,
		liquidity_asset_id: CurrencyIdOf<T>,
	) -> BalanceOf<T> {
		<T as pallet::Config>::ActivationReservesProvider::get_max_instant_unreserve_amount(
			liquidity_asset_id,
			user,
		)
	}

	// Sets the liquidity token's info
	// May fail if liquidity_asset_id does not exsist
	// Should not fail otherwise as the parameters for the max and min length in pallet_assets_info should be set appropriately
	pub fn set_liquidity_asset_info(
		liquidity_asset_id: CurrencyIdOf<T>,
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
	) -> DispatchResult {
		let mut name: Vec<u8> = Vec::<u8>::new();
		name.extend_from_slice(LIQUIDITY_TOKEN_IDENTIFIER);
		name.extend_from_slice(HEX_INDICATOR);
		for bytes in liquidity_asset_id.saturated_into::<u32>().to_be_bytes().iter() {
			match (bytes >> 4) as u8 {
				x @ 0u8..=9u8 => name.push(x.saturating_add(48u8)),
				x => name.push(x.saturating_add(55u8)),
			}
			match (bytes & 0b0000_1111) as u8 {
				x @ 0u8..=9u8 => name.push(x.saturating_add(48u8)),
				x => name.push(x.saturating_add(55u8)),
			}
		}

		let mut symbol: Vec<u8> = Vec::<u8>::new();
		symbol.extend_from_slice(TOKEN_SYMBOL);
		symbol.extend_from_slice(HEX_INDICATOR);
		for bytes in first_asset_id.saturated_into::<u32>().to_be_bytes().iter() {
			match (bytes >> 4) as u8 {
				x @ 0u8..=9u8 => symbol.push(x.saturating_add(48u8)),
				x => symbol.push(x.saturating_add(55u8)),
			}
			match (bytes & 0b0000_1111) as u8 {
				x @ 0u8..=9u8 => symbol.push(x.saturating_add(48u8)),
				x => symbol.push(x.saturating_add(55u8)),
			}
		}
		symbol.extend_from_slice(TOKEN_SYMBOL_SEPARATOR);
		symbol.extend_from_slice(TOKEN_SYMBOL);
		symbol.extend_from_slice(HEX_INDICATOR);
		for bytes in second_asset_id.saturated_into::<u32>().to_be_bytes().iter() {
			match (bytes >> 4) as u8 {
				x @ 0u8..=9u8 => symbol.push(x.saturating_add(48u8)),
				x => symbol.push(x.saturating_add(55u8)),
			}
			match (bytes & 0b0000_1111) as u8 {
				x @ 0u8..=9u8 => symbol.push(x.saturating_add(48u8)),
				x => symbol.push(x.saturating_add(55u8)),
			}
		}

		T::AssetMetadataMutation::set_asset_info(
			liquidity_asset_id,
			name,
			symbol,
			DEFAULT_DECIMALS,
		)?;
		Ok(())
	}

	// Calculate amount of tokens to be bought by sellling sell_amount
	pub fn calculate_sell_price(
		input_reserve: BalanceOf<T>,
		output_reserve: BalanceOf<T>,
		sell_amount: BalanceOf<T>,
	) -> Result<BalanceOf<T>, DispatchError> {
		let after_fee_percentage: u128 = 10000_u128
			.checked_sub(Self::total_fee())
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;
		let input_reserve_saturated: U256 = input_reserve.into().into();
		let output_reserve_saturated: U256 = output_reserve.into().into();
		let sell_amount_saturated: U256 = sell_amount.into().into();

		let input_amount_with_fee: U256 =
			sell_amount_saturated.saturating_mul(after_fee_percentage.into());

		let numerator: U256 = input_amount_with_fee
			.checked_mul(output_reserve_saturated)
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		let denominator: U256 = input_reserve_saturated
			.saturating_mul(10000.into())
			.checked_add(input_amount_with_fee)
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		let result_u256 = numerator
			.checked_div(denominator)
			.ok_or_else(|| DispatchError::from(Error::<T>::DivisionByZero))?;

		let result_u128 = u128::try_from(result_u256)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;

		let result = BalanceOf::<T>::try_from(result_u128)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;
		log!(
			info,
			"calculate_sell_price: ({:?}, {:?}, {:?}) -> {:?}",
			input_reserve,
			output_reserve,
			sell_amount,
			result
		);
		Ok(result)
	}

	pub fn calculate_sell_price_no_fee(
		// Callculate amount of tokens to be received by sellling sell_amount, without fee
		input_reserve: BalanceOf<T>,
		output_reserve: BalanceOf<T>,
		sell_amount: BalanceOf<T>,
	) -> Result<BalanceOf<T>, DispatchError> {
		let input_reserve_saturated: U256 = input_reserve.into().into();
		let output_reserve_saturated: U256 = output_reserve.into().into();
		let sell_amount_saturated: U256 = sell_amount.into().into();

		let numerator: U256 = sell_amount_saturated.saturating_mul(output_reserve_saturated);
		let denominator: U256 = input_reserve_saturated.saturating_add(sell_amount_saturated);
		let result_u256 = numerator
			.checked_div(denominator)
			.ok_or_else(|| DispatchError::from(Error::<T>::DivisionByZero))?;
		let result_u128 = u128::try_from(result_u256)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;
		let result = BalanceOf::<T>::try_from(result_u128)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;
		log!(
			info,
			"calculate_sell_price_no_fee: ({:?}, {:?}, {:?}) -> {:?}",
			input_reserve,
			output_reserve,
			sell_amount,
			result
		);
		Ok(result)
	}

	// Calculate amount of tokens to be paid, when buying buy_amount
	pub fn calculate_buy_price(
		input_reserve: BalanceOf<T>,
		output_reserve: BalanceOf<T>,
		buy_amount: BalanceOf<T>,
	) -> Result<BalanceOf<T>, DispatchError> {
		let after_fee_percentage: u128 = 10000_u128
			.checked_sub(Self::total_fee())
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;
		let input_reserve_saturated: U256 = input_reserve.into().into();
		let output_reserve_saturated: U256 = output_reserve.into().into();
		let buy_amount_saturated: U256 = buy_amount.into().into();

		let numerator: U256 = input_reserve_saturated
			.saturating_mul(buy_amount_saturated)
			.checked_mul(10000.into())
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		let denominator: U256 = output_reserve_saturated
			.checked_sub(buy_amount_saturated)
			.ok_or_else(|| DispatchError::from(Error::<T>::NotEnoughReserve))?
			.checked_mul(after_fee_percentage.into())
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		let result_u256 = numerator
			.checked_div(denominator)
			.ok_or_else(|| DispatchError::from(Error::<T>::DivisionByZero))?
			.checked_add(1.into())
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		let result_u128 = u128::try_from(result_u256)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;

		let result = BalanceOf::<T>::try_from(result_u128)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;
		log!(
			info,
			"calculate_buy_price: ({:?}, {:?}, {:?}) -> {:?}",
			input_reserve,
			output_reserve,
			buy_amount,
			result
		);
		Ok(result)
	}

	pub fn calculate_balanced_sell_amount(
		total_amount: BalanceOf<T>,
		reserve_amount: BalanceOf<T>,
	) -> Result<BalanceOf<T>, DispatchError> {
		let multiplier: U256 = 10_000.into();
		let multiplier_sq: U256 = multiplier.pow(2.into());
		let non_pool_fees: U256 = Self::total_fee()
			.checked_sub(T::PoolFeePercentage::get())
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?
			.into(); // npf
		let total_fee: U256 = Self::total_fee().into(); // tf
		let total_amount_saturated: U256 = total_amount.into().into(); // z
		let reserve_amount_saturated: U256 = reserve_amount.into().into(); // a

		// n: 2*10_000^2*a - 10_000*tf*a - sqrt( (-2*10_000^2*a + 10_000*tf*a)^2 - 4*10_000^2*a*z*(10_000tf - npf*tf + 10_000npf - 10_000^2) )
		// d: 2 * (10_000tf - npf*tf + 10_000npf - 10_000^2)
		// x = n / d

		// fee_rate: 2*10_000^2 - 10_000*tf
		// simplify n: fee_rate*a - sqrt( fee_rate^2*s^2 - 2*10_000^2*(-d)*a*z )
		let fee_rate = multiplier_sq
			.saturating_mul(2.into())
			.checked_sub(total_fee.saturating_mul(multiplier))
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		// 2*(10_000tf - npf*tf + 10_000npf - 10_000^2) -> negative number
		// change to: d = (10_000^2 + npf*tf - 10_000tf - 10_000npf) * 2
		let denominator_negative = multiplier_sq
			.checked_add(non_pool_fees.saturating_mul(total_fee))
			.and_then(|v| v.checked_sub(total_fee.saturating_mul(multiplier)))
			.and_then(|v| v.checked_sub(non_pool_fees.saturating_mul(multiplier)))
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?
			.saturating_mul(2.into());

		// fee_rate^2*a^2 - 2*10_000^2*(-den)*a*z
		let sqrt_arg = reserve_amount_saturated
			.checked_pow(2.into())
			.and_then(|v| v.checked_mul(fee_rate.pow(2.into())))
			.and_then(|v| {
				v.checked_add(
					total_amount_saturated
						.saturating_mul(reserve_amount_saturated)
						.saturating_mul(denominator_negative)
						.saturating_mul(multiplier_sq)
						.saturating_mul(2.into()),
				)
			})
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		// n: fee_rate*a - sqrt(...) -> negative
		// sqrt(..) - fee_rate*a
		let numerator_negative = sqrt_arg
			.integer_sqrt()
			.checked_sub(reserve_amount_saturated.saturating_mul(fee_rate))
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		// -n/-d == n/d
		let result_u256 = numerator_negative
			.checked_div(denominator_negative)
			.ok_or_else(|| DispatchError::from(Error::<T>::DivisionByZero))?;
		let result_u128 = u128::try_from(result_u256)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;
		let result = BalanceOf::<T>::try_from(result_u128)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;

		Ok(result)
	}

	pub fn get_liq_tokens_for_trading() -> Result<Vec<CurrencyIdOf<T>>, DispatchError> {
		let result = LiquidityAssets::<T>::iter_values()
			.filter_map(|v| v)
			.filter(|v| !<T as Config>::Currency::total_issuance((*v).into()).is_zero())
			.collect();

		Ok(result)
	}

	// MAX: 2R
	pub fn get_liquidity_asset(
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
	) -> Result<CurrencyIdOf<T>, DispatchError> {
		if LiquidityAssets::<T>::contains_key((first_asset_id, second_asset_id)) {
			LiquidityAssets::<T>::get((first_asset_id, second_asset_id))
				.ok_or_else(|| Error::<T>::UnexpectedFailure.into())
		} else {
			LiquidityAssets::<T>::get((second_asset_id, first_asset_id))
				.ok_or_else(|| Error::<T>::NoSuchPool.into())
		}
	}

	pub fn calculate_sell_price_id(
		sold_token_id: CurrencyIdOf<T>,
		bought_token_id: CurrencyIdOf<T>,
		sell_amount: BalanceOf<T>,
	) -> Result<BalanceOf<T>, DispatchError> {
		let (input_reserve, output_reserve) =
			Pallet::<T>::get_reserves(sold_token_id, bought_token_id)?;

		ensure!(!(Self::is_pool_empty(sold_token_id, bought_token_id)?), Error::<T>::PoolIsEmpty);

		Self::calculate_sell_price(input_reserve, output_reserve, sell_amount)
	}

	pub fn calculate_buy_price_id(
		sold_token_id: CurrencyIdOf<T>,
		bought_token_id: CurrencyIdOf<T>,
		buy_amount: BalanceOf<T>,
	) -> Result<BalanceOf<T>, DispatchError> {
		let (input_reserve, output_reserve) =
			Pallet::<T>::get_reserves(sold_token_id, bought_token_id)?;

		ensure!(!(Self::is_pool_empty(sold_token_id, bought_token_id)?), Error::<T>::PoolIsEmpty);

		Self::calculate_buy_price(input_reserve, output_reserve, buy_amount)
	}

	pub fn get_reserves(
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
	) -> Result<(BalanceOf<T>, BalanceOf<T>), DispatchError> {
		let mut reserves = Pools::<T>::get((first_asset_id, second_asset_id));

		if Pools::<T>::contains_key((first_asset_id, second_asset_id)) {
			Ok((reserves.0, reserves.1))
		} else if Pools::<T>::contains_key((second_asset_id, first_asset_id)) {
			reserves = Pools::<T>::get((second_asset_id, first_asset_id));
			Ok((reserves.1, reserves.0))
		} else {
			Err(DispatchError::from(Error::<T>::NoSuchPool))
		}
	}

	/// worst case scenario
	/// MAX: 2R 1W
	pub fn set_reserves(
		first_asset_id: CurrencyIdOf<T>,
		first_asset_amount: BalanceOf<T>,
		second_asset_id: CurrencyIdOf<T>,
		second_asset_amount: BalanceOf<T>,
	) -> DispatchResult {
		if Pools::<T>::contains_key((first_asset_id, second_asset_id)) {
			Pools::<T>::insert(
				(first_asset_id, second_asset_id),
				(first_asset_amount, second_asset_amount),
			);
		} else if Pools::<T>::contains_key((second_asset_id, first_asset_id)) {
			Pools::<T>::insert(
				(second_asset_id, first_asset_id),
				(second_asset_amount, first_asset_amount),
			);
		} else {
			return Err(DispatchError::from(Error::<T>::NoSuchPool))
		}

		Ok(())
	}

	// Calculate first and second token amounts depending on liquidity amount to burn
	pub fn get_burn_amount(
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
		liquidity_asset_amount: BalanceOf<T>,
	) -> Result<(BalanceOf<T>, BalanceOf<T>), DispatchError> {
		// Get token reserves and liquidity asset id
		let liquidity_asset_id = Self::get_liquidity_asset(first_asset_id, second_asset_id)?;
		let (first_asset_reserve, second_asset_reserve) =
			Pallet::<T>::get_reserves(first_asset_id, second_asset_id)?;

		ensure!(!(Self::is_pool_empty(first_asset_id, second_asset_id)?), Error::<T>::PoolIsEmpty);

		let (first_asset_amount, second_asset_amount) = Self::get_burn_amount_reserves(
			first_asset_reserve,
			second_asset_reserve,
			liquidity_asset_id,
			liquidity_asset_amount,
		)?;

		log!(
			info,
			"get_burn_amount: ({:?}, {:?}, {:?}) -> ({:?}, {:?})",
			first_asset_id,
			second_asset_id,
			liquidity_asset_amount,
			first_asset_amount,
			second_asset_amount
		);

		Ok((first_asset_amount, second_asset_amount))
	}

	pub fn get_burn_amount_reserves(
		first_asset_reserve: BalanceOf<T>,
		second_asset_reserve: BalanceOf<T>,
		liquidity_asset_id: CurrencyIdOf<T>,
		liquidity_asset_amount: BalanceOf<T>,
	) -> Result<(BalanceOf<T>, BalanceOf<T>), DispatchError> {
		// Get token reserves and liquidity asset id

		let total_liquidity_assets: BalanceOf<T> =
			<T as Config>::Currency::total_issuance(liquidity_asset_id.into());

		// Calculate first and second token amount to be withdrawn
		ensure!(!total_liquidity_assets.is_zero(), Error::<T>::DivisionByZero);
		let first_asset_amount = multiply_by_rational_with_rounding(
			first_asset_reserve.into(),
			liquidity_asset_amount.into(),
			total_liquidity_assets.into(),
			Rounding::Down,
		)
		.map(SaturatedConversion::saturated_into)
		.ok_or(Error::<T>::UnexpectedFailure)?;
		let second_asset_amount = multiply_by_rational_with_rounding(
			second_asset_reserve.into(),
			liquidity_asset_amount.into(),
			total_liquidity_assets.into(),
			Rounding::Down,
		)
		.map(SaturatedConversion::saturated_into)
		.ok_or(Error::<T>::UnexpectedFailure)?;

		Ok((first_asset_amount, second_asset_amount))
	}

	fn settle_treasury_and_burn(
		sold_asset_id: CurrencyIdOf<T>,
		burn_amount: BalanceOf<T>,
		treasury_amount: BalanceOf<T>,
	) -> DispatchResult {
		let vault = Self::account_id();
		let mangata_id: CurrencyIdOf<T> = Self::native_token_id();
		let treasury_account: T::AccountId = Self::treasury_account_id();
		let bnb_treasury_account: T::AccountId = Self::bnb_treasury_account_id();

		// If settling token is mangata, treasury amount is added to treasury and burn amount is burned from corresponding pool
		if sold_asset_id == mangata_id {
			// treasury_amount of MGA is already in treasury at this point

			// MGA burned from bnb_treasury_account
			// MAX: 3R 1W
			<T as Config>::Currency::burn_and_settle(
				sold_asset_id.into(),
				&bnb_treasury_account,
				burn_amount,
			)?;
		}
		//If settling token is connected to mangata, token is swapped in corresponding pool to mangata without fee
		else if Pools::<T>::contains_key((sold_asset_id, mangata_id)) ||
			Pools::<T>::contains_key((mangata_id, sold_asset_id))
		{
			// MAX: 2R (from if cond)

			// Getting token reserves
			let (input_reserve, output_reserve) =
				Pallet::<T>::get_reserves(sold_asset_id, mangata_id)?;

			// Calculating swapped mangata amount
			let settle_amount_in_mangata = Self::calculate_sell_price_no_fee(
				input_reserve,
				output_reserve,
				treasury_amount
					.checked_add(&burn_amount)
					.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?,
			)?;

			let treasury_amount_in_mangata: BalanceOf<T> = settle_amount_in_mangata
				.into()
				.checked_mul(T::TreasuryFeePercentage::get())
				.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?
				.checked_div(
					T::TreasuryFeePercentage::get()
						.checked_add(T::BuyAndBurnFeePercentage::get())
						.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?,
				)
				.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?
				.try_into()
				.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;

			let burn_amount_in_mangata: BalanceOf<T> = settle_amount_in_mangata
				.into()
				.checked_sub(treasury_amount_in_mangata.into())
				.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?
				.try_into()
				.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;

			// Apply changes in token pools, adding treasury and burn amounts of settling token, removing  treasury and burn amounts of mangata

			// MAX: 2R 1W
			Pallet::<T>::set_reserves(
				sold_asset_id,
				input_reserve.saturating_add(treasury_amount).saturating_add(burn_amount),
				mangata_id,
				output_reserve
					.saturating_sub(treasury_amount_in_mangata)
					.saturating_sub(burn_amount_in_mangata),
			)?;

			<T as Config>::Currency::transfer(
				sold_asset_id.into(),
				&treasury_account,
				&vault,
				treasury_amount,
				ExistenceRequirement::KeepAlive,
			)?;

			<T as Config>::Currency::transfer(
				mangata_id.into(),
				&vault,
				&treasury_account,
				treasury_amount_in_mangata,
				ExistenceRequirement::KeepAlive,
			)?;

			<T as Config>::Currency::transfer(
				sold_asset_id.into(),
				&bnb_treasury_account,
				&vault,
				burn_amount,
				ExistenceRequirement::KeepAlive,
			)?;

			// Mangata burned from pool
			<T as Config>::Currency::burn_and_settle(
				mangata_id.into(),
				&vault,
				burn_amount_in_mangata,
			)?;
		}
		// Settling token has no mangata connection, settling token is added to treasuries
		else {
			// Both treasury_amount and buy_and_burn_amount of sold_asset are in their respective treasuries
		}
		Ok(())
	}

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

	fn treasury_account_id() -> T::AccountId {
		T::TreasuryPalletId::get().into_account_truncating()
	}

	fn bnb_treasury_account_id() -> T::AccountId {
		T::TreasuryPalletId::get().into_sub_account_truncating(T::BnbTreasurySubAccDerive::get())
	}

	fn native_token_id() -> CurrencyIdOf<T> {
		<T as Config>::NativeCurrencyId::get()
	}

	fn calculate_initial_liquidity(
		first_asset_amount: BalanceOf<T>,
		second_asset_amount: BalanceOf<T>,
	) -> Result<BalanceOf<T>, DispatchError> {
		let initial_liquidity = first_asset_amount
			.checked_div(&2_u32.into())
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?
			.checked_add(
				&second_asset_amount
					.checked_div(&2_u32.into())
					.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?,
			)
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		return Ok(if initial_liquidity == BalanceOf::<T>::zero() {
			BalanceOf::<T>::one()
		} else {
			initial_liquidity
		})
	}

	fn is_pool_empty(
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
	) -> Result<bool, DispatchError> {
		let liquidity_asset_id = Pallet::<T>::get_liquidity_asset(first_asset_id, second_asset_id)?;
		let total_liquidity_assets: BalanceOf<T> =
			<T as Config>::Currency::total_issuance(liquidity_asset_id.into());

		return Ok(total_liquidity_assets.is_zero())
	}
}

impl<T: Config> PreValidateSwaps<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>> for Pallet<T> {
	fn pre_validate_sell_asset(
		sender: &T::AccountId,
		sold_asset_id: CurrencyIdOf<T>,
		bought_asset_id: CurrencyIdOf<T>,
		sold_asset_amount: BalanceOf<T>,
		_min_amount_out: BalanceOf<T>,
	) -> Result<
		(BalanceOf<T>, BalanceOf<T>, BalanceOf<T>, BalanceOf<T>, BalanceOf<T>, BalanceOf<T>),
		DispatchError,
	> {
		ensure!(
			!T::MaintenanceStatusProvider::is_maintenance(),
			Error::<T>::TradingBlockedByMaintenanceMode
		);

		// Ensure not selling zero amount
		ensure!(!sold_asset_amount.is_zero(), Error::<T>::ZeroAmount,);

		ensure!(
			!T::DisabledTokens::contains(&sold_asset_id) &&
				!T::DisabledTokens::contains(&bought_asset_id),
			Error::<T>::FunctionNotAvailableForThisToken
		);

		ensure!(!(Self::is_pool_empty(sold_asset_id, bought_asset_id)?), Error::<T>::PoolIsEmpty);

		let buy_and_burn_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			sold_asset_amount.into(),
			T::BuyAndBurnFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let treasury_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			sold_asset_amount.into(),
			T::TreasuryFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let pool_fee_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			sold_asset_amount.into(),
			T::PoolFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let total_fees: BalanceOf<T> = buy_and_burn_amount
			.checked_add(&treasury_amount)
			.and_then(|v| v.checked_add(&pool_fee_amount))
			.ok_or(Error::<T>::MathOverflow)?;

		// MAX: 2R
		let (input_reserve, output_reserve) =
			Pallet::<T>::get_reserves(sold_asset_id, bought_asset_id)?;

		ensure!(input_reserve.checked_add(&sold_asset_amount).is_some(), Error::<T>::MathOverflow);

		// Calculate bought asset amount to be received by paying sold asset amount
		let bought_asset_amount =
			Pallet::<T>::calculate_sell_price(input_reserve, output_reserve, sold_asset_amount)?;

		// Ensure user has enough tokens to sell
		<T as Config>::Currency::ensure_can_withdraw(
			sold_asset_id.into(),
			sender,
			total_fees,
			WithdrawReasons::all(),
			// Does not fail due to earlier ensure
			Default::default(),
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		Ok((
			buy_and_burn_amount,
			treasury_amount,
			pool_fee_amount,
			input_reserve,
			output_reserve,
			bought_asset_amount,
		))
	}

	/// We only validate the first atomic swap's ability to accept fees
	fn pre_validate_multiswap_sell_asset(
		sender: &T::AccountId,
		swap_token_list: Vec<CurrencyIdOf<T>>,
		sold_asset_amount: BalanceOf<T>,
		_min_amount_out: BalanceOf<T>,
	) -> Result<
		(
			BalanceOf<T>,
			BalanceOf<T>,
			BalanceOf<T>,
			BalanceOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
			CurrencyIdOf<T>,
		),
		DispatchError,
	> {
		ensure!(
			!T::MaintenanceStatusProvider::is_maintenance(),
			Error::<T>::TradingBlockedByMaintenanceMode
		);
		ensure!(swap_token_list.len() > 2_usize, Error::<T>::MultiswapShouldBeAtleastTwoHops);
		let sold_asset_id =
			*swap_token_list.get(0).ok_or(Error::<T>::MultiswapShouldBeAtleastTwoHops)?;
		let bought_asset_id =
			*swap_token_list.get(1).ok_or(Error::<T>::MultiswapShouldBeAtleastTwoHops)?;

		// Ensure not selling zero amount
		ensure!(!sold_asset_amount.is_zero(), Error::<T>::ZeroAmount,);

		let atomic_pairs: Vec<(CurrencyIdOf<T>, CurrencyIdOf<T>)> = swap_token_list
			.clone()
			.into_iter()
			.zip(swap_token_list.clone().into_iter().skip(1))
			.collect();

		for (x, y) in atomic_pairs.iter() {
			ensure!(!(Self::is_pool_empty(*x, *y)?), Error::<T>::PoolIsEmpty);

			if x == y {
				return Err(Error::<T>::MultiSwapCantHaveSameTokenConsequetively.into())
			}
		}

		ensure!(
			!T::DisabledTokens::contains(&sold_asset_id) &&
				!T::DisabledTokens::contains(&bought_asset_id),
			Error::<T>::FunctionNotAvailableForThisToken
		);

		let buy_and_burn_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			sold_asset_amount.into(),
			T::BuyAndBurnFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let treasury_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			sold_asset_amount.into(),
			T::TreasuryFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let pool_fee_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			sold_asset_amount.into(),
			T::PoolFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let total_fees = buy_and_burn_amount
			.checked_add(&treasury_amount)
			.and_then(|v| v.checked_add(&pool_fee_amount))
			.ok_or(Error::<T>::MathOverflow)?;

		// Get token reserves

		// MAX: 2R
		let (input_reserve, output_reserve) =
			Pallet::<T>::get_reserves(sold_asset_id, bought_asset_id)?;

		ensure!(input_reserve.checked_add(&pool_fee_amount).is_some(), Error::<T>::MathOverflow);

		// Ensure user has enough tokens to sell
		<T as Config>::Currency::ensure_can_withdraw(
			sold_asset_id.into(),
			sender,
			total_fees,
			WithdrawReasons::all(),
			// Does not fail due to earlier ensure
			Default::default(),
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		Ok((
			buy_and_burn_amount,
			treasury_amount,
			pool_fee_amount,
			input_reserve,
			output_reserve,
			sold_asset_id,
			bought_asset_id,
		))
	}

	fn pre_validate_buy_asset(
		sender: &T::AccountId,
		sold_asset_id: CurrencyIdOf<T>,
		bought_asset_id: CurrencyIdOf<T>,
		bought_asset_amount: BalanceOf<T>,
		_max_amount_in: BalanceOf<T>,
	) -> Result<
		(BalanceOf<T>, BalanceOf<T>, BalanceOf<T>, BalanceOf<T>, BalanceOf<T>, BalanceOf<T>),
		DispatchError,
	> {
		ensure!(
			!T::MaintenanceStatusProvider::is_maintenance(),
			Error::<T>::TradingBlockedByMaintenanceMode
		);

		ensure!(
			!T::DisabledTokens::contains(&sold_asset_id) &&
				!T::DisabledTokens::contains(&bought_asset_id),
			Error::<T>::FunctionNotAvailableForThisToken
		);

		ensure!(!(Self::is_pool_empty(sold_asset_id, bought_asset_id)?), Error::<T>::PoolIsEmpty);

		// Get token reserves
		let (input_reserve, output_reserve) =
			Pallet::<T>::get_reserves(sold_asset_id, bought_asset_id)?;

		// Ensure there are enough tokens in reserves
		ensure!(output_reserve > bought_asset_amount, Error::<T>::NotEnoughReserve,);

		// Ensure not buying zero amount
		ensure!(!bought_asset_amount.is_zero(), Error::<T>::ZeroAmount,);

		// Calculate amount to be paid from bought amount
		let sold_asset_amount =
			Pallet::<T>::calculate_buy_price(input_reserve, output_reserve, bought_asset_amount)?;

		let buy_and_burn_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			sold_asset_amount.into(),
			T::BuyAndBurnFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let treasury_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			sold_asset_amount.into(),
			T::TreasuryFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let pool_fee_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			sold_asset_amount.into(),
			T::PoolFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		// for future implementation of min fee if necessary
		// let min_fee: u128 = 0;
		// if buy_and_burn_amount + treasury_amount + pool_fee_amount < min_fee {
		//     buy_and_burn_amount = min_fee * Self::total_fee() / T::BuyAndBurnFeePercentage::get();
		//     treasury_amount = min_fee * Self::total_fee() / T::TreasuryFeePercentage::get();
		//     pool_fee_amount = min_fee - buy_and_burn_amount - treasury_amount;
		// }

		ensure!(input_reserve.checked_add(&sold_asset_amount).is_some(), Error::<T>::MathOverflow);

		// Ensure user has enough tokens to sell
		<T as Config>::Currency::ensure_can_withdraw(
			sold_asset_id.into(),
			sender,
			sold_asset_amount,
			WithdrawReasons::all(),
			// Does not fail due to earlier ensure
			Default::default(),
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		Ok((
			buy_and_burn_amount,
			treasury_amount,
			pool_fee_amount,
			input_reserve,
			output_reserve,
			sold_asset_amount,
		))
	}

	/// We only validate the first atomic swap's ability to accept fees
	fn pre_validate_multiswap_buy_asset(
		sender: &T::AccountId,
		swap_token_list: Vec<CurrencyIdOf<T>>,
		final_bought_asset_amount: BalanceOf<T>,
		max_amount_in: BalanceOf<T>,
	) -> Result<
		(
			BalanceOf<T>,
			BalanceOf<T>,
			BalanceOf<T>,
			BalanceOf<T>,
			BalanceOf<T>,
			CurrencyIdOf<T>,
			CurrencyIdOf<T>,
		),
		DispatchError,
	> {
		ensure!(
			!T::MaintenanceStatusProvider::is_maintenance(),
			Error::<T>::TradingBlockedByMaintenanceMode
		);
		ensure!(swap_token_list.len() > 2_usize, Error::<T>::MultiswapShouldBeAtleastTwoHops);
		// Ensure not buying zero amount
		ensure!(!final_bought_asset_amount.is_zero(), Error::<T>::ZeroAmount,);
		ensure!(!max_amount_in.is_zero(), Error::<T>::ZeroAmount,);

		// Unwraps are fine due to above ensure
		let sold_asset_id =
			*swap_token_list.get(0).ok_or(Error::<T>::MultiswapShouldBeAtleastTwoHops)?;
		let bought_asset_id =
			*swap_token_list.get(1).ok_or(Error::<T>::MultiswapShouldBeAtleastTwoHops)?;

		ensure!(
			!T::DisabledTokens::contains(&sold_asset_id) &&
				!T::DisabledTokens::contains(&bought_asset_id),
			Error::<T>::FunctionNotAvailableForThisToken
		);

		// Cannot use multiswap twice on the same pool
		let atomic_pairs: Vec<(CurrencyIdOf<T>, CurrencyIdOf<T>)> = swap_token_list
			.clone()
			.into_iter()
			.zip(swap_token_list.clone().into_iter().skip(1))
			.collect();

		let mut atomic_pairs_hashset = BTreeSet::new();

		for (x, y) in atomic_pairs.iter() {
			ensure!(!(Self::is_pool_empty(*x, *y)?), Error::<T>::PoolIsEmpty);

			if x == y {
				return Err(Error::<T>::MultiSwapCantHaveSameTokenConsequetively.into())
			} else if x > y {
				if !atomic_pairs_hashset.insert((x, y)) {
					return Err(Error::<T>::MultiBuyAssetCantHaveSamePoolAtomicSwaps.into())
				};
			} else
			// x < y
			{
				if !atomic_pairs_hashset.insert((y, x)) {
					return Err(Error::<T>::MultiBuyAssetCantHaveSamePoolAtomicSwaps.into())
				};
			}
		}

		// Get token reserves
		let (input_reserve, output_reserve) =
			Pallet::<T>::get_reserves(sold_asset_id, bought_asset_id)?;

		let buy_and_burn_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			max_amount_in.into(),
			T::BuyAndBurnFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let treasury_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			max_amount_in.into(),
			T::TreasuryFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let pool_fee_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			max_amount_in.into(),
			T::PoolFeePercentage::get(),
			10000,
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or(Error::<T>::MathOverflow)?
		.try_into()
		.map_err(|_| Error::<T>::MathOverflow)?;

		let total_fees = buy_and_burn_amount
			.checked_add(&treasury_amount)
			.and_then(|v| v.checked_add(&pool_fee_amount))
			.ok_or(Error::<T>::MathOverflow)?;

		ensure!(input_reserve.checked_add(&pool_fee_amount).is_some(), Error::<T>::MathOverflow);

		// Ensure user has enough tokens to sell
		<T as Config>::Currency::ensure_can_withdraw(
			sold_asset_id.into(),
			sender,
			total_fees,
			WithdrawReasons::all(),
			// Does not fail due to earlier ensure
			Default::default(),
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		Ok((
			buy_and_burn_amount,
			treasury_amount,
			pool_fee_amount,
			input_reserve,
			output_reserve,
			sold_asset_id,
			bought_asset_id,
		))
	}
}

impl<T: Config> XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>> for Pallet<T> {
	fn create_pool(
		sender: T::AccountId,
		first_asset_id: CurrencyIdOf<T>,
		first_asset_amount: BalanceOf<T>,
		second_asset_id: CurrencyIdOf<T>,
		second_asset_amount: BalanceOf<T>,
	) -> DispatchResult {
		let vault: T::AccountId = Pallet::<T>::account_id();

		// Ensure pool is not created with zero amount
		ensure!(
			!first_asset_amount.is_zero() && !second_asset_amount.is_zero(),
			Error::<T>::ZeroAmount,
		);

		// Ensure pool does not exists yet
		ensure!(
			!Pools::<T>::contains_key((first_asset_id, second_asset_id)),
			Error::<T>::PoolAlreadyExists,
		);

		// Ensure pool does not exists yet
		ensure!(
			!Pools::<T>::contains_key((second_asset_id, first_asset_id)),
			Error::<T>::PoolAlreadyExists,
		);

		// Ensure user has enough withdrawable tokens to create pool in amounts required

		<T as Config>::Currency::ensure_can_withdraw(
			first_asset_id.into(),
			&sender,
			first_asset_amount,
			WithdrawReasons::all(),
			// Does not fail due to earlier ensure
			Default::default(),
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		<T as Config>::Currency::ensure_can_withdraw(
			second_asset_id.into(),
			&sender,
			second_asset_amount,
			WithdrawReasons::all(),
			// Does not fail due to earlier ensure
			Default::default(),
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		// Ensure pool is not created with same token in pair
		ensure!(first_asset_id != second_asset_id, Error::<T>::SameAsset,);

		// Liquidity token amount calculation
		let initial_liquidity =
			Pallet::<T>::calculate_initial_liquidity(first_asset_amount, second_asset_amount)?;

		Pools::<T>::insert(
			(first_asset_id, second_asset_id),
			(first_asset_amount, second_asset_amount),
		);

		// Pools::insert((second_asset_id, first_asset_id), second_asset_amount);

		// Moving tokens from user to vault
		<T as Config>::Currency::transfer(
			first_asset_id.into(),
			&sender,
			&vault,
			first_asset_amount,
			ExistenceRequirement::AllowDeath,
		)?;

		<T as Config>::Currency::transfer(
			second_asset_id.into(),
			&sender,
			&vault,
			second_asset_amount,
			ExistenceRequirement::AllowDeath,
		)?;

		// Creating new liquidity token and transfering it to user
		let liquidity_asset_id: CurrencyIdOf<T> =
			<T as Config>::Currency::create(&sender, initial_liquidity)
				.map_err(|_| Error::<T>::LiquidityTokenCreationFailed)?
				.into();

		// Adding info about liquidity asset
		LiquidityAssets::<T>::insert((first_asset_id, second_asset_id), Some(liquidity_asset_id));
		LiquidityPools::<T>::insert(liquidity_asset_id, Some((first_asset_id, second_asset_id)));

		log!(
			info,
			"create_pool: ({:?}, {:?}, {:?}, {:?}, {:?}) -> ({:?}, {:?})",
			sender,
			first_asset_id,
			first_asset_amount,
			second_asset_id,
			second_asset_amount,
			liquidity_asset_id,
			initial_liquidity
		);

		log!(
			info,
			"pool-state: [({:?}, {:?}) -> {:?}, ({:?}, {:?}) -> {:?}]",
			first_asset_id,
			second_asset_id,
			first_asset_amount,
			second_asset_id,
			first_asset_id,
			second_asset_amount
		);
		// This, will and should, never fail
		Pallet::<T>::set_liquidity_asset_info(liquidity_asset_id, first_asset_id, second_asset_id)?;

		Pallet::<T>::deposit_event(Event::PoolCreated(
			sender,
			first_asset_id,
			first_asset_amount,
			second_asset_id,
			second_asset_amount,
		));

		Ok(())
	}

	// To put it comprehensively the only reason that the user should lose out on swap fee
	// is if the mistake is theirs, which in the context of swaps is bad slippage besides pre_validation.
	// In this implementation, once pre_validation passes the swap fee mechanism that follows should suceed.
	// And if the function fails beyond pre_validation but not on slippage then the user is free from blame.
	// Further internals calls, might determine the slippage themselves before calling this swap function,
	// in which case again the user must not be charged the swap fee.
	fn sell_asset(
		sender: T::AccountId,
		sold_asset_id: CurrencyIdOf<T>,
		bought_asset_id: CurrencyIdOf<T>,
		sold_asset_amount: BalanceOf<T>,
		min_amount_out: BalanceOf<T>,
		err_upon_bad_slippage: bool,
	) -> Result<BalanceOf<T>, DispatchError> {
		let (
			buy_and_burn_amount,
			treasury_amount,
			pool_fee_amount,
			input_reserve,
			output_reserve,
			bought_asset_amount,
		) = <Pallet<T> as PreValidateSwaps<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::pre_validate_sell_asset(
			&sender,
			sold_asset_id,
			bought_asset_id,
			sold_asset_amount,
			min_amount_out,
		)?;

		let vault = Pallet::<T>::account_id();
		let treasury_account: T::AccountId = Self::treasury_account_id();
		let bnb_treasury_account: T::AccountId = Self::bnb_treasury_account_id();

		// Transfer of fees, before tx can fail on min amount out
		<T as Config>::Currency::transfer(
			sold_asset_id.into(),
			&sender,
			&vault,
			pool_fee_amount,
			ExistenceRequirement::KeepAlive,
		)?;

		<T as Config>::Currency::transfer(
			sold_asset_id.into(),
			&sender,
			&treasury_account,
			treasury_amount,
			ExistenceRequirement::KeepAlive,
		)?;

		<T as Config>::Currency::transfer(
			sold_asset_id.into(),
			&sender,
			&bnb_treasury_account,
			buy_and_burn_amount,
			ExistenceRequirement::KeepAlive,
		)?;

		// Add pool fee to pool
		// 2R 1W
		Pallet::<T>::set_reserves(
			sold_asset_id,
			input_reserve.saturating_add(pool_fee_amount),
			bought_asset_id,
			output_reserve,
		)?;

		// Ensure bought token amount is higher then requested minimal amount
		if bought_asset_amount >= min_amount_out {
			// Transfer the rest of sold token amount from user to vault and bought token amount from vault to user
			<T as Config>::Currency::transfer(
				sold_asset_id.into(),
				&sender,
				&vault,
				sold_asset_amount
					.checked_sub(
						&buy_and_burn_amount
							.checked_add(&treasury_amount)
							.and_then(|v| v.checked_add(&pool_fee_amount))
							.ok_or_else(|| DispatchError::from(Error::<T>::SoldAmountTooLow))?,
					)
					.ok_or_else(|| DispatchError::from(Error::<T>::SoldAmountTooLow))?,
				ExistenceRequirement::KeepAlive,
			)?;

			<T as Config>::Currency::transfer(
				bought_asset_id.into(),
				&vault,
				&sender,
				bought_asset_amount,
				ExistenceRequirement::KeepAlive,
			)?;

			// Apply changes in token pools, adding sold amount and removing bought amount
			// Neither should fall to zero let alone underflow, due to how pool destruction works
			// Won't overflow due to earlier ensure
			let input_reserve_updated = input_reserve.saturating_add(
				sold_asset_amount
					.checked_sub(&treasury_amount)
					.and_then(|v| v.checked_sub(&buy_and_burn_amount))
					.ok_or_else(|| DispatchError::from(Error::<T>::SoldAmountTooLow))?,
			);
			let output_reserve_updated = output_reserve.saturating_sub(bought_asset_amount);

			// MAX 2R 1W
			Pallet::<T>::set_reserves(
				sold_asset_id,
				input_reserve_updated,
				bought_asset_id,
				output_reserve_updated,
			)?;

			log!(
				info,
				"sell_asset: ({:?}, {:?}, {:?}, {:?}, {:?}) -> {:?}",
				sender,
				sold_asset_id,
				bought_asset_id,
				sold_asset_amount,
				min_amount_out,
				bought_asset_amount
			);

			log!(
				info,
				"pool-state: [({:?}, {:?}) -> {:?}, ({:?}, {:?}) -> {:?}]",
				sold_asset_id,
				bought_asset_id,
				input_reserve_updated,
				bought_asset_id,
				sold_asset_id,
				output_reserve_updated
			);

			Pallet::<T>::deposit_event(Event::AssetsSwapped(
				sender.clone(),
				vec![sold_asset_id, bought_asset_id],
				sold_asset_amount,
				bought_asset_amount,
			));
		}

		// Settle tokens which goes to treasury and for buy and burn purpose
		Pallet::<T>::settle_treasury_and_burn(sold_asset_id, buy_and_burn_amount, treasury_amount)?;

		if bought_asset_amount < min_amount_out {
			if err_upon_bad_slippage {
				return Err(DispatchError::from(Error::<T>::InsufficientOutputAmount))
			} else {
				Pallet::<T>::deposit_event(Event::SellAssetFailedDueToSlippage(
					sender,
					sold_asset_id,
					sold_asset_amount,
					bought_asset_id,
					bought_asset_amount,
					min_amount_out,
				));
				return Ok(Default::default())
			}
		}

		Ok(bought_asset_amount)
	}

	fn do_multiswap_sell_asset(
		sender: T::AccountId,
		swap_token_list: Vec<CurrencyIdOf<T>>,
		sold_asset_amount: BalanceOf<T>,
		min_amount_out: BalanceOf<T>,
	) -> Result<BalanceOf<T>, DispatchError> {
		frame_support::storage::with_storage_layer(|| -> Result<BalanceOf<T>, DispatchError> {
			// Ensure user has enough tokens to sell
			<T as Config>::Currency::ensure_can_withdraw(
				// Naked unwrap is fine due to pre validation len check
				{ *swap_token_list.get(0).ok_or(Error::<T>::MultiswapShouldBeAtleastTwoHops)? }
					.into(),
				&sender,
				sold_asset_amount,
				WithdrawReasons::all(),
				Default::default(),
			)
			.or(Err(Error::<T>::NotEnoughAssets))?;

			// pre_validate has already confirmed that swap_token_list.len()>1
			let atomic_pairs: Vec<(CurrencyIdOf<T>, CurrencyIdOf<T>)> = swap_token_list
				.clone()
				.into_iter()
				.zip(swap_token_list.clone().into_iter().skip(1))
				.collect();

			let mut atomic_sold_asset_amount = sold_asset_amount;
			let mut atomic_bought_asset_amount = BalanceOf::<T>::zero();

			for (atomic_sold_asset, atomic_bought_asset) in atomic_pairs.iter() {
				atomic_bought_asset_amount = <Self as XykFunctionsTrait<
					T::AccountId,
					BalanceOf<T>,
					CurrencyIdOf<T>,
				>>::sell_asset(
					sender.clone(),
					*atomic_sold_asset,
					*atomic_bought_asset,
					atomic_sold_asset_amount,
					BalanceOf::<T>::zero(),
					// We using most possible slippage so this should be irrelevant
					true,
				)?;

				// Prep the next loop
				atomic_sold_asset_amount = atomic_bought_asset_amount;
			}

			// fail/error and revert if bad final slippage
			if atomic_bought_asset_amount < min_amount_out {
				return Err(Error::<T>::InsufficientOutputAmount.into())
			} else {
				return Ok(atomic_bought_asset_amount)
			}
		})
	}

	fn multiswap_sell_asset(
		sender: T::AccountId,
		swap_token_list: Vec<CurrencyIdOf<T>>,
		sold_asset_amount: BalanceOf<T>,
		min_amount_out: BalanceOf<T>,
		_err_upon_bad_slippage: bool,
		_err_upon_non_slippage_fail: bool,
	) -> Result<BalanceOf<T>, DispatchError> {
		let (
			fee_swap_buy_and_burn_amount,
			fee_swap_treasury_amount,
			fee_swap_pool_fee_amount,
			fee_swap_input_reserve,
			fee_swap_output_reserve,
			fee_swap_sold_asset_id,
			fee_swap_bought_asset_id,
		) = <Pallet<T> as PreValidateSwaps<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::pre_validate_multiswap_sell_asset(
			&sender,
			swap_token_list.clone(),
			sold_asset_amount,
			min_amount_out,
		)?;

		// First execute all atomic swaps in a storage layer
		// And then the finally bought amount is compared
		// The bool in error represents if the fail is due to bad final slippage
		match <Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::do_multiswap_sell_asset(
			sender.clone(),
			swap_token_list.clone(),
			sold_asset_amount,
			min_amount_out,
		) {
			Ok(bought_asset_amount) => {
				Pallet::<T>::deposit_event(Event::AssetsSwapped(
					sender.clone(),
					swap_token_list.clone(),
					sold_asset_amount,
					bought_asset_amount,
				));
				Ok(bought_asset_amount)
			},
			Err(e) => {
				// Charge fee

				let vault = Pallet::<T>::account_id();
				let treasury_account: T::AccountId = Self::treasury_account_id();
				let bnb_treasury_account: T::AccountId = Self::bnb_treasury_account_id();

				// Transfer of fees, before tx can fail on min amount out
				<T as Config>::Currency::transfer(
					fee_swap_sold_asset_id,
					&sender,
					&vault,
					fee_swap_pool_fee_amount,
					ExistenceRequirement::KeepAlive,
				)?;

				<T as Config>::Currency::transfer(
					fee_swap_sold_asset_id,
					&sender,
					&treasury_account,
					fee_swap_treasury_amount,
					ExistenceRequirement::KeepAlive,
				)?;

				<T as Config>::Currency::transfer(
					fee_swap_sold_asset_id,
					&sender,
					&bnb_treasury_account,
					fee_swap_buy_and_burn_amount,
					ExistenceRequirement::KeepAlive,
				)?;

				// Add pool fee to pool
				// 2R 1W
				Pallet::<T>::set_reserves(
					fee_swap_sold_asset_id,
					fee_swap_input_reserve.saturating_add(fee_swap_pool_fee_amount),
					fee_swap_bought_asset_id,
					fee_swap_output_reserve,
				)?;

				// Settle tokens which goes to treasury and for buy and burn purpose
				Pallet::<T>::settle_treasury_and_burn(
					fee_swap_sold_asset_id,
					fee_swap_buy_and_burn_amount,
					fee_swap_treasury_amount,
				)?;

				if let DispatchError::Module(module_err) = e {
					Pallet::<T>::deposit_event(Event::MultiSwapAssetFailedOnAtomicSwap(
						sender.clone(),
						swap_token_list.clone(),
						sold_asset_amount,
						module_err,
					));
					Ok(Default::default())
				} else {
					Err(DispatchError::from(Error::<T>::UnexpectedFailure))
				}
			},
		}
	}

	// To put it comprehensively the only reason that the user should lose out on swap fee
	// is if the mistake is theirs, which in the context of swaps is bad slippage besides pre_validation.
	// In this implementation, once pre_validation passes the swap fee mechanism that follows should suceed.
	// And if the function fails beyond pre_validation but not on slippage then the user is free from blame.
	// Further internals calls, might determine the slippage themselves before calling this swap function,
	// in which case again the user must not be charged the swap fee.
	fn buy_asset(
		sender: T::AccountId,
		sold_asset_id: CurrencyIdOf<T>,
		bought_asset_id: CurrencyIdOf<T>,
		bought_asset_amount: BalanceOf<T>,
		max_amount_in: BalanceOf<T>,
		err_upon_bad_slippage: bool,
	) -> Result<BalanceOf<T>, DispatchError> {
		let (
			buy_and_burn_amount,
			treasury_amount,
			pool_fee_amount,
			input_reserve,
			output_reserve,
			sold_asset_amount,
		) = <Pallet<T> as PreValidateSwaps<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::pre_validate_buy_asset(
			&sender,
			sold_asset_id,
			bought_asset_id,
			bought_asset_amount,
			max_amount_in,
		)?;

		let vault = Pallet::<T>::account_id();
		let treasury_account: T::AccountId = Self::treasury_account_id();
		let bnb_treasury_account: T::AccountId = Self::bnb_treasury_account_id();

		// Transfer of fees, before tx can fail on min amount out
		<T as Config>::Currency::transfer(
			sold_asset_id,
			&sender,
			&vault,
			pool_fee_amount,
			ExistenceRequirement::KeepAlive,
		)?;

		<T as Config>::Currency::transfer(
			sold_asset_id,
			&sender,
			&treasury_account,
			treasury_amount,
			ExistenceRequirement::KeepAlive,
		)?;

		<T as Config>::Currency::transfer(
			sold_asset_id,
			&sender,
			&bnb_treasury_account,
			buy_and_burn_amount,
			ExistenceRequirement::KeepAlive,
		)?;

		// Add pool fee to pool
		Pallet::<T>::set_reserves(
			sold_asset_id,
			input_reserve.saturating_add(pool_fee_amount),
			bought_asset_id,
			output_reserve,
		)?;

		// Ensure paid amount is less then maximum allowed price
		if sold_asset_amount <= max_amount_in {
			// Transfer sold token amount from user to vault and bought token amount from vault to user
			<T as Config>::Currency::transfer(
				sold_asset_id.into(),
				&sender,
				&vault,
				sold_asset_amount
					.checked_sub(
						&buy_and_burn_amount
							.checked_add(&treasury_amount)
							.and_then(|v| v.checked_add(&pool_fee_amount))
							.ok_or_else(|| DispatchError::from(Error::<T>::SoldAmountTooLow))?,
					)
					.ok_or_else(|| DispatchError::from(Error::<T>::SoldAmountTooLow))?,
				ExistenceRequirement::KeepAlive,
			)?;
			<T as Config>::Currency::transfer(
				bought_asset_id,
				&vault,
				&sender,
				bought_asset_amount,
				ExistenceRequirement::KeepAlive,
			)?;

			// Apply changes in token pools, adding sold amount and removing bought amount
			// Neither should fall to zero let alone underflow, due to how pool destruction works
			// Won't overflow due to earlier ensure
			let input_reserve_updated = input_reserve.saturating_add(
				sold_asset_amount
					.checked_sub(&treasury_amount)
					.and_then(|v| v.checked_sub(&buy_and_burn_amount))
					.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?,
			);

			let output_reserve_updated = output_reserve.saturating_sub(bought_asset_amount);
			Pallet::<T>::set_reserves(
				sold_asset_id,
				input_reserve_updated,
				bought_asset_id,
				output_reserve_updated,
			)?;

			log!(
				info,
				"buy_asset: ({:?}, {:?}, {:?}, {:?}, {:?}) -> {:?}",
				sender,
				sold_asset_id,
				bought_asset_id,
				bought_asset_amount,
				max_amount_in,
				sold_asset_amount
			);

			log!(
				info,
				"pool-state: [({:?}, {:?}) -> {:?}, ({:?}, {:?}) -> {:?}]",
				sold_asset_id,
				bought_asset_id,
				input_reserve_updated,
				bought_asset_id,
				sold_asset_id,
				output_reserve_updated
			);

			Pallet::<T>::deposit_event(Event::AssetsSwapped(
				sender.clone(),
				vec![sold_asset_id, bought_asset_id],
				sold_asset_amount,
				bought_asset_amount,
			));
		}
		// Settle tokens which goes to treasury and for buy and burn purpose
		Pallet::<T>::settle_treasury_and_burn(sold_asset_id, buy_and_burn_amount, treasury_amount)?;

		if sold_asset_amount > max_amount_in {
			if err_upon_bad_slippage {
				return Err(DispatchError::from(Error::<T>::InsufficientInputAmount))
			} else {
				Pallet::<T>::deposit_event(Event::BuyAssetFailedDueToSlippage(
					sender,
					sold_asset_id,
					sold_asset_amount,
					bought_asset_id,
					bought_asset_amount,
					max_amount_in,
				));
			}
		}

		Ok(sold_asset_amount)
	}

	fn do_multiswap_buy_asset(
		sender: T::AccountId,
		swap_token_list: Vec<CurrencyIdOf<T>>,
		bought_asset_amount: BalanceOf<T>,
		max_amount_in: BalanceOf<T>,
	) -> Result<BalanceOf<T>, DispatchError> {
		frame_support::storage::with_storage_layer(|| -> Result<BalanceOf<T>, DispatchError> {
			// pre_validate has already confirmed that swap_token_list.len()>1
			let atomic_pairs: Vec<(CurrencyIdOf<T>, CurrencyIdOf<T>)> = swap_token_list
				.clone()
				.into_iter()
				.zip(swap_token_list.clone().into_iter().skip(1))
				.collect();

			let mut atomic_sold_asset_amount = BalanceOf::<T>::zero();
			let mut atomic_bought_asset_amount = bought_asset_amount;

			let mut atomic_swap_buy_amounts_rev: Vec<BalanceOf<T>> = Default::default();
			// Calc
			// We can do this using calculate_buy_price_id chain due to the check in pre_validation
			// that ensures that no pool is touched twice. So the reserves in question are consistent
			for (atomic_sold_asset, atomic_bought_asset) in atomic_pairs.iter().rev() {
				atomic_sold_asset_amount = Self::calculate_buy_price_id(
					*atomic_sold_asset,
					*atomic_bought_asset,
					atomic_bought_asset_amount,
				)?;

				atomic_swap_buy_amounts_rev.push(atomic_bought_asset_amount);
				// Prep the next loop
				atomic_bought_asset_amount = atomic_sold_asset_amount;
			}

			ensure!(atomic_sold_asset_amount <= max_amount_in, Error::<T>::InsufficientInputAmount);

			// Ensure user has enough tokens to sell
			<T as Config>::Currency::ensure_can_withdraw(
				// Naked unwrap is fine due to pre validation len check
				{ *swap_token_list.get(0).ok_or(Error::<T>::MultiswapShouldBeAtleastTwoHops)? }
					.into(),
				&sender,
				atomic_sold_asset_amount,
				WithdrawReasons::all(),
				Default::default(),
			)
			.or(Err(Error::<T>::NotEnoughAssets))?;

			// Execute here
			for ((atomic_sold_asset, atomic_bought_asset), atomic_swap_buy_amount) in
				atomic_pairs.iter().zip(atomic_swap_buy_amounts_rev.iter().rev())
			{
				let _ = <Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::buy_asset(
					sender.clone(),
					*atomic_sold_asset,
					*atomic_bought_asset,
					*atomic_swap_buy_amount,
					BalanceOf::<T>::max_value(),
					// We using most possible slippage so this should be irrelevant
					true,
				)?;
			}

			return Ok(atomic_sold_asset_amount)
		})
	}

	fn multiswap_buy_asset(
		sender: T::AccountId,
		swap_token_list: Vec<CurrencyIdOf<T>>,
		bought_asset_amount: BalanceOf<T>,
		max_amount_in: BalanceOf<T>,
		_err_upon_bad_slippage: bool,
		_err_upon_non_slippage_fail: bool,
	) -> Result<BalanceOf<T>, DispatchError> {
		let (
			fee_swap_buy_and_burn_amount,
			fee_swap_treasury_amount,
			fee_swap_pool_fee_amount,
			fee_swap_input_reserve,
			fee_swap_output_reserve,
			fee_swap_sold_asset_id,
			fee_swap_bought_asset_id,
		) = <Pallet<T> as PreValidateSwaps<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::pre_validate_multiswap_buy_asset(
			&sender,
			swap_token_list.clone(),
			bought_asset_amount,
			max_amount_in,
		)?;

		// First execute all atomic swaps in a storage layer
		// And then the finally sold amount is compared
		// The bool in error represents if the fail is due to bad final slippage
		match <Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::do_multiswap_buy_asset(
			sender.clone(),
			swap_token_list.clone(),
			bought_asset_amount,
			max_amount_in,
		) {
			Ok(sold_asset_amount) => {
				Pallet::<T>::deposit_event(Event::AssetsSwapped(
					sender.clone(),
					swap_token_list.clone(),
					sold_asset_amount,
					bought_asset_amount,
				));
				Ok(sold_asset_amount)
			},
			Err(e) => {
				let vault = Pallet::<T>::account_id();
				let treasury_account: T::AccountId = Self::treasury_account_id();
				let bnb_treasury_account: T::AccountId = Self::bnb_treasury_account_id();

				// Transfer of fees, before tx can fail on min amount out
				<T as Config>::Currency::transfer(
					fee_swap_sold_asset_id,
					&sender,
					&vault,
					fee_swap_pool_fee_amount,
					ExistenceRequirement::KeepAlive,
				)?;

				<T as Config>::Currency::transfer(
					fee_swap_sold_asset_id,
					&sender,
					&treasury_account,
					fee_swap_treasury_amount,
					ExistenceRequirement::KeepAlive,
				)?;

				<T as Config>::Currency::transfer(
					fee_swap_sold_asset_id,
					&sender,
					&bnb_treasury_account,
					fee_swap_buy_and_burn_amount,
					ExistenceRequirement::KeepAlive,
				)?;

				// Add pool fee to pool
				// 2R 1W
				Pallet::<T>::set_reserves(
					fee_swap_sold_asset_id,
					fee_swap_input_reserve.saturating_add(fee_swap_pool_fee_amount),
					fee_swap_bought_asset_id,
					fee_swap_output_reserve,
				)?;

				// Settle tokens which goes to treasury and for buy and burn purpose
				Pallet::<T>::settle_treasury_and_burn(
					fee_swap_sold_asset_id,
					fee_swap_buy_and_burn_amount,
					fee_swap_treasury_amount,
				)?;

				if let DispatchError::Module(module_err) = e {
					Pallet::<T>::deposit_event(Event::MultiSwapAssetFailedOnAtomicSwap(
						sender.clone(),
						swap_token_list.clone(),
						bought_asset_amount,
						module_err,
					));
					Ok(Default::default())
				} else {
					Err(DispatchError::from(Error::<T>::UnexpectedFailure))
				}
			},
		}
	}

	fn mint_liquidity(
		sender: T::AccountId,
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
		first_asset_amount: BalanceOf<T>,
		expected_second_asset_amount: BalanceOf<T>,
		activate_minted_liquidity: bool,
	) -> Result<(CurrencyIdOf<T>, BalanceOf<T>), DispatchError> {
		let vault = Pallet::<T>::account_id();

		// Ensure pool exists
		ensure!(
			(LiquidityAssets::<T>::contains_key((first_asset_id, second_asset_id)) ||
				LiquidityAssets::<T>::contains_key((second_asset_id, first_asset_id))),
			Error::<T>::NoSuchPool,
		);

		// Get liquidity token id
		let liquidity_asset_id = Pallet::<T>::get_liquidity_asset(first_asset_id, second_asset_id)?;

		// Get token reserves
		let (first_asset_reserve, second_asset_reserve) =
			Pallet::<T>::get_reserves(first_asset_id, second_asset_id)?;
		let total_liquidity_assets: BalanceOf<T> =
			<T as Config>::Currency::total_issuance(liquidity_asset_id.into());

		// The pool is empty and we are basically creating a new pool and reusing the existing one
		let second_asset_amount = if !(first_asset_reserve.is_zero() &&
			second_asset_reserve.is_zero()) &&
			!total_liquidity_assets.is_zero()
		{
			// Calculation of required second asset amount and received liquidity token amount
			ensure!(!first_asset_reserve.is_zero(), Error::<T>::DivisionByZero);

			multiply_by_rational_with_rounding(
				first_asset_amount.into(),
				second_asset_reserve.into(),
				first_asset_reserve.into(),
				Rounding::Down,
			)
			.ok_or(Error::<T>::UnexpectedFailure)?
			.checked_add(1)
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?
			.try_into()
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?
		} else {
			expected_second_asset_amount
		};

		ensure!(
			second_asset_amount <= expected_second_asset_amount,
			Error::<T>::SecondAssetAmountExceededExpectations,
		);

		// Ensure minting amounts are not zero
		ensure!(
			!first_asset_amount.is_zero() && !second_asset_amount.is_zero(),
			Error::<T>::ZeroAmount,
		);

		// We calculate the required liquidity token amount and also validate asset amounts
		let liquidity_assets_minted = if total_liquidity_assets.is_zero() {
			Pallet::<T>::calculate_initial_liquidity(first_asset_amount, second_asset_amount)?
		} else {
			multiply_by_rational_with_rounding(
				first_asset_amount.into(),
				total_liquidity_assets.into(),
				first_asset_reserve.into(),
				Rounding::Down,
			)
			.ok_or(Error::<T>::UnexpectedFailure)?
			.try_into()
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?
		};

		// Ensure user has enough withdrawable tokens to create pool in amounts required

		<T as Config>::Currency::ensure_can_withdraw(
			first_asset_id.into(),
			&sender,
			first_asset_amount,
			WithdrawReasons::all(),
			// Does not fail due to earlier ensure
			Default::default(),
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		<T as Config>::Currency::ensure_can_withdraw(
			second_asset_id,
			&sender,
			second_asset_amount,
			WithdrawReasons::all(),
			// Does not fail due to earlier ensure
			Default::default(),
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		// Transfer of token amounts from user to vault
		<T as Config>::Currency::transfer(
			first_asset_id,
			&sender,
			&vault,
			first_asset_amount,
			ExistenceRequirement::KeepAlive,
		)?;
		<T as Config>::Currency::transfer(
			second_asset_id,
			&sender,
			&vault,
			second_asset_amount,
			ExistenceRequirement::KeepAlive,
		)?;

		// Creating new liquidity tokens to user
		<T as Config>::Currency::mint(liquidity_asset_id, &sender, liquidity_assets_minted)?;

		if <T::LiquidityMiningRewards as ProofOfStakeRewardsApi<
			T::AccountId,
			BalanceOf<T>,
			CurrencyIdOf<T>,
		>>::is_enabled(liquidity_asset_id) &&
			activate_minted_liquidity
		{
			// The reserve from free_balance will not fail the asset were just minted into free_balance
			<T::LiquidityMiningRewards as ProofOfStakeRewardsApi<
				T::AccountId,
				BalanceOf<T>,
				CurrencyIdOf<T>,
			>>::activate_liquidity(
				sender.clone(),
				liquidity_asset_id,
				liquidity_assets_minted,
				Some(ActivateKind::AvailableBalance),
			)?;
		}

		// Apply changes in token pools, adding minted amounts
		// Won't overflow due earlier ensure
		let first_asset_reserve_updated = first_asset_reserve.saturating_add(first_asset_amount);
		let second_asset_reserve_updated = second_asset_reserve.saturating_add(second_asset_amount);
		Pallet::<T>::set_reserves(
			first_asset_id,
			first_asset_reserve_updated,
			second_asset_id,
			second_asset_reserve_updated,
		)?;

		log!(
			info,
			"mint_liquidity: ({:?}, {:?}, {:?}, {:?}) -> ({:?}, {:?}, {:?})",
			sender,
			first_asset_id,
			second_asset_id,
			first_asset_amount,
			second_asset_amount,
			liquidity_asset_id,
			liquidity_assets_minted
		);

		log!(
			info,
			"pool-state: [({:?}, {:?}) -> {:?}, ({:?}, {:?}) -> {:?}]",
			first_asset_id,
			second_asset_id,
			first_asset_reserve_updated,
			second_asset_id,
			first_asset_id,
			second_asset_reserve_updated
		);

		Pallet::<T>::deposit_event(Event::LiquidityMinted(
			sender,
			first_asset_id,
			first_asset_amount,
			second_asset_id,
			second_asset_amount,
			liquidity_asset_id,
			liquidity_assets_minted,
		));

		Ok((liquidity_asset_id, liquidity_assets_minted))
	}

	fn do_compound_rewards(
		sender: T::AccountId,
		liquidity_asset_id: CurrencyIdOf<T>,
		amount_permille: Permill,
	) -> DispatchResult {
		let (first_asset_id, second_asset_id) =
			LiquidityPools::<T>::get(liquidity_asset_id).ok_or(Error::<T>::NoSuchLiquidityAsset)?;

		ensure!(
			!T::DisabledTokens::contains(&first_asset_id) &&
				!T::DisabledTokens::contains(&second_asset_id),
			Error::<T>::FunctionNotAvailableForThisToken
		);

		let rewards_id: CurrencyIdOf<T> = Self::native_token_id();
		ensure!(
			first_asset_id == rewards_id || second_asset_id == rewards_id,
			Error::<T>::FunctionNotAvailableForThisToken
		);

		let rewards_claimed = <T::LiquidityMiningRewards as ProofOfStakeRewardsApi<
			T::AccountId,
			BalanceOf<T>,
			CurrencyIdOf<T>,
		>>::claim_rewards_all(sender.clone(), liquidity_asset_id)?;

		let rewards_256 = U256::from(rewards_claimed.into())
			.saturating_mul(amount_permille.deconstruct().into())
			.div(Permill::one().deconstruct());
		let rewards_128 = u128::try_from(rewards_256)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;
		let rewards = BalanceOf::<T>::try_from(rewards_128)
			.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;

		<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::provide_liquidity_with_conversion(
			sender,
			first_asset_id,
			second_asset_id,
			rewards_id,
			rewards,
			true,
		)?;

		Ok(())
	}

	fn provide_liquidity_with_conversion(
		sender: T::AccountId,
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
		provided_asset_id: CurrencyIdOf<T>,
		provided_asset_amount: BalanceOf<T>,
		activate_minted_liquidity: bool,
	) -> Result<(CurrencyIdOf<T>, BalanceOf<T>), DispatchError> {
		// checks
		ensure!(!provided_asset_amount.is_zero(), Error::<T>::ZeroAmount,);

		ensure!(!(Self::is_pool_empty(first_asset_id, second_asset_id)?), Error::<T>::PoolIsEmpty);

		let (first_reserve, second_reserve) =
			Pallet::<T>::get_reserves(first_asset_id, second_asset_id)?;

		let (reserve, other_reserve, other_asset_id) = if provided_asset_id == first_asset_id {
			(first_reserve, second_reserve, second_asset_id)
		} else if provided_asset_id == second_asset_id {
			(second_reserve, first_reserve, first_asset_id)
		} else {
			return Err(DispatchError::from(Error::<T>::FunctionNotAvailableForThisToken))
		};

		// Ensure user has enough tokens to sell
		<T as Config>::Currency::ensure_can_withdraw(
			provided_asset_id,
			&sender,
			provided_asset_amount,
			WithdrawReasons::all(),
			// Does not fail due to earlier ensure
			Default::default(),
		)
		.or(Err(Error::<T>::NotEnoughAssets))?;

		// calculate sell
		let swap_amount =
			Pallet::<T>::calculate_balanced_sell_amount(provided_asset_amount, reserve)?;

		let bought_amount = Pallet::<T>::calculate_sell_price(reserve, other_reserve, swap_amount)?;

		let _ =
			<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::sell_asset(
				sender.clone(),
				provided_asset_id,
				other_asset_id,
				swap_amount,
				bought_amount,
				true,
			)?;

		let mint_amount = provided_asset_amount
			.checked_sub(&swap_amount)
			.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?;

		log!(
			info,
			"provide_liquidity_with_conversion: ({:?}, {:?}, {:?}, {:?}, {:?}) -> ({:?}, {:?})",
			sender,
			first_asset_id,
			second_asset_id,
			provided_asset_id,
			provided_asset_amount,
			mint_amount,
			bought_amount
		);

		// we swap the order of the pairs to handle rounding
		// we spend all of the Y
		// and have some surplus amount of X that equals to the rounded part of Y
		<Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::mint_liquidity(
			sender,
			other_asset_id,
			provided_asset_id,
			bought_amount,
			BalanceOf::<T>::max_value(),
			activate_minted_liquidity,
		)
	}

	fn burn_liquidity(
		sender: T::AccountId,
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
		liquidity_asset_amount: BalanceOf<T>,
	) -> DispatchResult {
		let vault = Pallet::<T>::account_id();

		ensure!(
			!T::DisabledTokens::contains(&first_asset_id) &&
				!T::DisabledTokens::contains(&second_asset_id),
			Error::<T>::FunctionNotAvailableForThisToken
		);

		let liquidity_asset_id = Pallet::<T>::get_liquidity_asset(first_asset_id, second_asset_id)?;

		// First let's check how much we can actually burn
		let max_instant_unreserve_amount =
			<T as pallet::Config>::ActivationReservesProvider::get_max_instant_unreserve_amount(
				liquidity_asset_id,
				&sender,
			);

		// Get token reserves and liquidity asset id
		let (first_asset_reserve, second_asset_reserve) =
			Pallet::<T>::get_reserves(first_asset_id, second_asset_id)?;

		// Ensure user has enought liquidity tokens to burn
		let liquidity_token_available_balance =
			<T as Config>::Currency::available_balance(liquidity_asset_id.into(), &sender);

		ensure!(
			liquidity_token_available_balance
				.checked_add(&max_instant_unreserve_amount)
				.ok_or(Error::<T>::MathOverflow)? >=
				liquidity_asset_amount,
			Error::<T>::NotEnoughAssets,
		);

		// Given the above ensure passes we only need to know how much to deactivate before burning
		// Because once deactivated we will be burning the entire liquidity_asset_amount from available balance
		// to_be_deactivated will ofcourse then also be greater than max_instant_unreserve_amount
		// If pool is not promoted max_instant_unreserve_amount is 0, so liquidity_token_available_balance >= liquidity_asset_amount
		// which would mean to_be_deactivated is 0, skipping deactivation
		let to_be_deactivated =
			liquidity_asset_amount.saturating_sub(liquidity_token_available_balance);

		// deactivate liquidity
		<T::LiquidityMiningRewards as ProofOfStakeRewardsApi<
			T::AccountId,
			BalanceOf<T>,
			CurrencyIdOf<T>,
		>>::deactivate_liquidity(sender.clone(), liquidity_asset_id, to_be_deactivated)?;

		// Calculate first and second token amounts depending on liquidity amount to burn
		let (first_asset_amount, second_asset_amount) = Pallet::<T>::get_burn_amount_reserves(
			first_asset_reserve,
			second_asset_reserve,
			liquidity_asset_id,
			liquidity_asset_amount,
		)?;

		let total_liquidity_assets: BalanceOf<T> =
			<T as Config>::Currency::total_issuance(liquidity_asset_id.into());

		// If all liquidity assets are being burned then
		// both asset amounts must be equal to their reserve values
		// All storage values related to this pool must be destroyed
		if liquidity_asset_amount == total_liquidity_assets {
			ensure!(
				(first_asset_reserve == first_asset_amount) &&
					(second_asset_reserve == second_asset_amount),
				Error::<T>::UnexpectedFailure
			);
		} else {
			ensure!(
				(first_asset_reserve >= first_asset_amount) &&
					(second_asset_reserve >= second_asset_amount),
				Error::<T>::UnexpectedFailure
			);
		}
		// If all liquidity assets are not being burned then
		// both asset amounts must be less than their reserve values

		// Ensure not withdrawing zero amounts
		ensure!(
			!first_asset_amount.is_zero() && !second_asset_amount.is_zero(),
			Error::<T>::ZeroAmount,
		);

		// Transfer withdrawn amounts from vault to user
		<T as Config>::Currency::transfer(
			first_asset_id,
			&vault,
			&sender,
			first_asset_amount,
			ExistenceRequirement::KeepAlive,
		)?;
		<T as Config>::Currency::transfer(
			second_asset_id,
			&vault,
			&sender,
			second_asset_amount,
			ExistenceRequirement::KeepAlive,
		)?;

		log!(
			info,
			"burn_liquidity: ({:?}, {:?}, {:?}, {:?}) -> ({:?}, {:?})",
			sender,
			first_asset_id,
			second_asset_id,
			liquidity_asset_amount,
			first_asset_amount,
			second_asset_amount
		);

		// Is liquidity asset amount empty?
		if liquidity_asset_amount == total_liquidity_assets {
			log!(
				info,
				"pool-state: [({:?}, {:?}) -> Removed, ({:?}, {:?}) -> Removed]",
				first_asset_id,
				second_asset_id,
				second_asset_id,
				first_asset_id,
			);
			Pallet::<T>::set_reserves(
				first_asset_id,
				BalanceOf::<T>::zero(),
				second_asset_id,
				BalanceOf::<T>::zero(),
			)?;
		} else {
			// Apply changes in token pools, removing withdrawn amounts
			// Cannot underflow due to earlier ensure
			// check was executed in get_reserves call
			let first_asset_reserve_updated =
				first_asset_reserve.saturating_sub(first_asset_amount);
			let second_asset_reserve_updated =
				second_asset_reserve.saturating_sub(second_asset_amount);
			Pallet::<T>::set_reserves(
				first_asset_id,
				first_asset_reserve_updated,
				second_asset_id,
				second_asset_reserve_updated,
			)?;

			log!(
				info,
				"pool-state: [({:?}, {:?}) -> {:?}, ({:?}, {:?}) -> {:?}]",
				first_asset_id,
				second_asset_id,
				first_asset_reserve_updated,
				second_asset_id,
				first_asset_id,
				second_asset_reserve_updated
			);
		}

		// Destroying burnt liquidity tokens
		// MAX: 3R 1W
		<T as Config>::Currency::burn_and_settle(
			liquidity_asset_id.into(),
			&sender,
			liquidity_asset_amount,
		)?;

		Pallet::<T>::deposit_event(Event::LiquidityBurned(
			sender,
			first_asset_id,
			first_asset_amount,
			second_asset_id,
			second_asset_amount,
			liquidity_asset_id,
			liquidity_asset_amount,
		));

		Ok(())
	}

	// This function has not been verified
	fn get_tokens_required_for_minting(
		liquidity_asset_id: CurrencyIdOf<T>,
		liquidity_token_amount: BalanceOf<T>,
	) -> Result<(CurrencyIdOf<T>, BalanceOf<T>, CurrencyIdOf<T>, BalanceOf<T>), DispatchError> {
		let (first_asset_id, second_asset_id) =
			LiquidityPools::<T>::get(liquidity_asset_id).ok_or(Error::<T>::NoSuchLiquidityAsset)?;
		let (first_asset_reserve, second_asset_reserve) =
			Pallet::<T>::get_reserves(first_asset_id, second_asset_id)?;
		let total_liquidity_assets: BalanceOf<T> =
			<T as Config>::Currency::total_issuance(liquidity_asset_id.into());

		ensure!(!total_liquidity_assets.is_zero(), Error::<T>::DivisionByZero);
		let second_asset_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			liquidity_token_amount.into(),
			second_asset_reserve.into(),
			total_liquidity_assets.into(),
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?
		.try_into()
		.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;

		let first_asset_amount: BalanceOf<T> = multiply_by_rational_with_rounding(
			liquidity_token_amount.into(),
			first_asset_reserve.into(),
			total_liquidity_assets.into(),
			Rounding::Down,
		)
		.ok_or(Error::<T>::UnexpectedFailure)?
		.checked_add(1)
		.ok_or_else(|| DispatchError::from(Error::<T>::MathOverflow))?
		.try_into()
		.map_err(|_| DispatchError::from(Error::<T>::MathOverflow))?;

		log!(
			info,
			"get_tokens_required_for_minting: ({:?}, {:?}) -> ({:?}, {:?}, {:?}, {:?})",
			liquidity_asset_id,
			liquidity_token_amount,
			first_asset_id,
			first_asset_amount,
			second_asset_id,
			second_asset_amount,
		);

		Ok((first_asset_id, first_asset_amount, second_asset_id, second_asset_amount))
	}

	fn is_liquidity_token(liquidity_asset_id: CurrencyIdOf<T>) -> bool {
		LiquidityPools::<T>::get(liquidity_asset_id).is_some()
	}
}

pub trait AssetMetadataMutationTrait<CurrencyId> {
	fn set_asset_info(
		asset: CurrencyId,
		name: Vec<u8>,
		symbol: Vec<u8>,
		decimals: u32,
	) -> DispatchResult;
}

impl<T: Config> Valuate<BalanceOf<T>, CurrencyIdOf<T>> for Pallet<T> {
	fn get_liquidity_asset(
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
	) -> Result<CurrencyIdOf<T>, DispatchError> {
		Pallet::<T>::get_liquidity_asset(first_asset_id, second_asset_id)
	}

	fn get_liquidity_token_mga_pool(
		liquidity_token_id: CurrencyIdOf<T>,
	) -> Result<(CurrencyIdOf<T>, CurrencyIdOf<T>), DispatchError> {
		let (first_token_id, second_token_id) =
			LiquidityPools::<T>::get(liquidity_token_id).ok_or(Error::<T>::NoSuchLiquidityAsset)?;
		let native_currency_id = Self::native_token_id();
		match native_currency_id {
			_ if native_currency_id == first_token_id => Ok((first_token_id, second_token_id)),
			_ if native_currency_id == second_token_id => Ok((second_token_id, first_token_id)),
			_ => Err(Error::<T>::NotMangataLiquidityAsset.into()),
		}
	}

	fn valuate_liquidity_token(
		liquidity_token_id: CurrencyIdOf<T>,
		liquidity_token_amount: BalanceOf<T>,
	) -> BalanceOf<T> {
		let (mga_token_id, other_token_id) =
			match Self::get_liquidity_token_mga_pool(liquidity_token_id) {
				Ok(pool) => pool,
				Err(_) => return Default::default(),
			};

		let mga_token_reserve = match Pallet::<T>::get_reserves(mga_token_id, other_token_id) {
			Ok(reserves) => reserves.0,
			Err(_) => return Default::default(),
		};

		let liquidity_token_reserve: BalanceOf<T> =
			<T as Config>::Currency::total_issuance(liquidity_token_id.into());

		if liquidity_token_reserve.is_zero() {
			return Default::default()
		}

		multiply_by_rational_with_rounding(
			mga_token_reserve.into(),
			liquidity_token_amount.into(),
			liquidity_token_reserve.into(),
			Rounding::Down,
		)
		.map(SaturatedConversion::saturated_into)
		.unwrap_or(BalanceOf::<T>::max_value())
	}

	fn valuate_non_liquidity_token(
		non_liquidity_token_id: CurrencyIdOf<T>,
		amount: BalanceOf<T>,
	) -> BalanceOf<T> {
		let native_token_id = Pallet::<T>::native_token_id();

		let (native_reserves, token_reserves) =
			match Pallet::<T>::get_reserves(native_token_id, non_liquidity_token_id) {
				Ok(reserves) => reserves,
				Err(_) => return Default::default(),
			};
		Pallet::<T>::calculate_sell_price_no_fee(token_reserves, native_reserves, amount)
			.unwrap_or_default()
	}

	fn scale_liquidity_by_mga_valuation(
		mga_valuation: BalanceOf<T>,
		liquidity_token_amount: BalanceOf<T>,
		mga_token_amount: BalanceOf<T>,
	) -> BalanceOf<T> {
		if mga_valuation.is_zero() {
			return Default::default()
		}

		multiply_by_rational_with_rounding(
			liquidity_token_amount.into(),
			mga_token_amount.into(),
			mga_valuation.into(),
			Rounding::Down,
		)
		.map(SaturatedConversion::saturated_into)
		.unwrap_or(BalanceOf::<T>::max_value())
	}

	fn get_pool_state(liquidity_token_id: CurrencyIdOf<T>) -> Option<(BalanceOf<T>, BalanceOf<T>)> {
		let (mga_token_id, other_token_id) =
			match Self::get_liquidity_token_mga_pool(liquidity_token_id) {
				Ok(pool) => pool,
				Err(_) => return None,
			};

		let mga_token_reserve = match Pallet::<T>::get_reserves(mga_token_id, other_token_id) {
			Ok(reserves) => reserves.0,
			Err(_) => return None,
		};

		let liquidity_token_reserve: BalanceOf<T> =
			<T as Config>::Currency::total_issuance(liquidity_token_id.into());

		if liquidity_token_reserve.is_zero() {
			return None
		}

		Some((mga_token_reserve, liquidity_token_reserve))
	}

	fn get_reserves(
		first_asset_id: CurrencyIdOf<T>,
		second_asset_id: CurrencyIdOf<T>,
	) -> Result<(BalanceOf<T>, BalanceOf<T>), DispatchError> {
		Pallet::<T>::get_reserves(first_asset_id, second_asset_id)
	}

	fn is_liquidity_token(liquidity_asset_id: CurrencyIdOf<T>) -> bool {
		LiquidityPools::<T>::get(liquidity_asset_id).is_some()
	}
}

impl<T: Config> PoolCreateApi<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>> for Pallet<T> {
	fn pool_exists(first: CurrencyIdOf<T>, second: CurrencyIdOf<T>) -> bool {
		Pools::<T>::contains_key((first, second)) || Pools::<T>::contains_key((second, first))
	}

	fn pool_create(
		account: T::AccountId,
		first: CurrencyIdOf<T>,
		first_amount: BalanceOf<T>,
		second: CurrencyIdOf<T>,
		second_amount: BalanceOf<T>,
	) -> Option<(CurrencyIdOf<T>, BalanceOf<T>)> {
		match <Self as XykFunctionsTrait<T::AccountId, BalanceOf<T>, CurrencyIdOf<T>>>::create_pool(
			account,
			first,
			first_amount,
			second,
			second_amount,
		) {
			Ok(_) => LiquidityAssets::<T>::get((first, second)).map(|asset_id| {
				(asset_id, <T as Config>::Currency::total_issuance(asset_id.into()))
			}),
			Err(e) => {
				log!(error, "cannot create pool {:?}!", e);
				None
			},
		}
	}
}