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
// Copyright 2021 ChainSafe Systems
// SPDX-License-Identifier: LGPL-3.0-only

//! # AssetIndex Pallet
//!
//! Tracks all the assets in the PINT index, composed of multiple assets
//!
//! The value of the assets is determined depending on their class.
//! The value of liquid assets is calculated by multiplying their current unit price by the amount
//! held in the index. Whereas the value of an asset secured by SAFTs is measured by the total value
//! of all SAFTs.

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

pub use pallet::*;

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub mod traits;
pub mod types;

#[frame_support::pallet]
// this is requires as the #[pallet::event] proc macro generates code that violates this lint
#[allow(clippy::unused_unit, clippy::large_enum_variant, clippy::type_complexity)]
pub mod pallet {
	#[cfg(feature = "runtime-benchmarks")]
	use pallet_price_feed::PriceFeedBenchmarks;
	#[cfg(feature = "runtime-benchmarks")]
	use primitives::traits::AssetRecorderBenchmarks;

	use frame_support::{
		pallet_prelude::*,
		sp_runtime::{
			traits::{AccountIdConversion, AtLeast32BitUnsigned, CheckedAdd, CheckedDiv, CheckedSub, Saturating, Zero},
			ArithmeticError, FixedPointNumber,
		},
		sp_std::{convert::TryInto, prelude::*, result::Result},
		traits::{Currency, ExistenceRequirement, Get, LockIdentifier, LockableCurrency, WithdrawReasons},
		transactional, PalletId,
	};
	use frame_system::pallet_prelude::*;
	use orml_traits::{MultiCurrency, MultiReservableCurrency};
	use sp_core::U256;
	use xcm::v1::MultiLocation;

	use pallet_price_feed::{AssetPricePair, Price, PriceFeed};
	use primitives::{
		fee::{BaseFee, FeeRate, RedemptionFeeRange},
		traits::{AssetRecorder, MultiAssetRegistry, NavProvider, RemoteAssetManager, SaftRegistry},
		AssetAvailability, AssetProportion, AssetProportions, Ratio,
	};

	use crate::{
		traits::LockupPeriodRange,
		types::{AssetMetadata, AssetRedemption, AssetWithdrawal, DepositRange, IndexTokenLock, PendingRedemption},
	};
	use primitives::traits::MaybeAssetIdConvert;

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

	#[pallet::config]
	pub trait Config: frame_system::Config + MaybeAssetIdConvert<u8, Self::AssetId> {
		/// Origin that is allowed to administer the index
		type AdminOrigin: EnsureOrigin<Self::Origin, Success = <Self as frame_system::Config>::AccountId>;
		/// Currency implementation to use as the index token
		type IndexToken: LockableCurrency<Self::AccountId, Balance = Self::Balance>;
		/// The balance type used within this pallet
		type Balance: Parameter
			+ Member
			+ AtLeast32BitUnsigned
			+ Default
			+ Copy
			+ MaybeSerializeDeserialize
			+ Into<u128>
			+ BaseFee;
		/// Period after the minting of the index token for which 100% is locked
		/// up. Only applies to users contributing assets directly to
		/// index
		#[pallet::constant]
		type LockupPeriod: Get<Self::BlockNumber>;
		/// Range of the lockup period
		type LockupPeriodRange: LockupPeriodRange<Self::BlockNumber>;
		/// The identifier for the index token lock.
		/// Used to lock up deposits for `T::LockupPeriod`.
		#[pallet::constant]
		type IndexTokenLockIdentifier: Get<LockIdentifier>;
		/// The minimum amount of the index token that can be redeemed for the
		/// underlying asset in the index
		#[pallet::constant]
		type MinimumRedemption: Get<Self::Balance>;
		/// Minimum amount of time between redeeming index tokens
		/// and being able to withdraw the awarded assets
		#[pallet::constant]
		type WithdrawalPeriod: Get<Self::BlockNumber>;
		/// Type that handles cross chain transfers
		type RemoteAssetManager: RemoteAssetManager<Self::AccountId, Self::AssetId, Self::Balance>;
		/// Type used to identify assets
		type AssetId: Parameter + Member + Copy + MaybeSerializeDeserialize;

		/// Restricts how many deposits can be active
		#[pallet::constant]
		type MaxActiveDeposits: Get<u32>;

		/// Restricts the max limit of decimals in metadata
		#[pallet::constant]
		type MaxDecimals: Get<u8>;

		/// Determines the redemption fee in complete_withdraw
		type RedemptionFee: Get<RedemptionFeeRange<Self::BlockNumber>>;

		/// The native asset id
		#[pallet::constant]
		type SelfAssetId: Get<Self::AssetId>;

		/// Currency type for deposit/withdraw assets to/from the user's
		/// sovereign account
		type Currency: MultiReservableCurrency<Self::AccountId, CurrencyId = Self::AssetId, Balance = Self::Balance>;

		/// The types that provides the necessary asset price pairs
		type PriceFeed: PriceFeed<Self::AssetId>;

		#[cfg(feature = "runtime-benchmarks")]
		/// The type that provides benchmark features of pallet_price_feed
		type PriceFeedBenchmarks: PriceFeedBenchmarks<Self::AccountId, Self::AssetId>;

		/// The type registry that stores all NAV for non liquid assets
		type SaftRegistry: SaftRegistry<Self::AssetId, Self::Balance>;

		/// The basic fees that apply when a withdrawal is executed
		#[pallet::constant]
		type BaseWithdrawalFee: Get<FeeRate>;

		/// The treasury's pallet id, used for deriving its sovereign account
		/// ID.
		#[pallet::constant]
		type TreasuryPalletId: Get<PalletId>;

		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;

		/// The maximum length of a name or symbol stored on-chain.
		#[pallet::constant]
		type StringLimit: Get<u32>;

		/// The weight for this pallet's extrinsics.
		type WeightInfo: WeightInfo;
	}

	#[pallet::pallet]
	#[pallet::generate_store(pub (super) trait Store)]
	pub struct Pallet<T>(_);

	/// stores a range of redemption fee
	#[pallet::storage]
	pub type RedemptionFee<T: Config> = StorageValue<_, RedemptionFeeRange<T::BlockNumber>, ValueQuery>;

	/// (AssetId) -> AssetAvailability
	#[pallet::storage]
	#[pallet::getter(fn assets)]
	pub type Assets<T: Config> = StorageMap<_, Blake2_128Concat, T::AssetId, AssetAvailability, OptionQuery>;

	/// All timestamped deposits of an account.
	///
	/// This tracks all deposits, the index token a LP received upon `deposit`.
	/// This will be used to calculate a withdrawal fee depending on how long the deposit remained
	/// in the index.
	#[pallet::storage]
	#[pallet::getter(fn deposits)]
	pub type Deposits<T: Config> = StorageMap<
		_,
		Blake2_128Concat,
		T::AccountId,
		BoundedVec<(T::Balance, T::BlockNumber), T::MaxActiveDeposits>,
		ValueQuery,
	>;

	/// All currently pending withdrawal sets for an account.
	/// Where a single `PendingRedemption` is the result of a `withdraw` call.
	///
	/// (AccountId) -> Vec<PendingRedemption>
	#[pallet::storage]
	#[pallet::getter(fn pending_withrawals)]
	pub type PendingWithdrawals<T: Config> = StorageMap<
		_,
		Blake2_128Concat,
		T::AccountId,
		Vec<PendingRedemption<T::AssetId, T::Balance, BlockNumberFor<T>>>,
		OptionQuery,
	>;

	/// Tracks the locks of the minted index token that are locked up until
	/// their `LockupPeriod` is over  (AccountId) -> Vec<IndexTokenLockInfo>
	#[pallet::storage]
	#[pallet::getter(fn index_token_locks)]
	pub type IndexTokenLocks<T: Config> =
		StorageMap<_, Blake2_128Concat, T::AccountId, Vec<IndexTokenLock<T::BlockNumber, T::Balance>>, ValueQuery>;

	/// Store a duration (in blocks) of the lockup period
	#[pallet::storage]
	pub type LockupPeriod<T: Config> = StorageValue<_, T::BlockNumber, ValueQuery>;

	/// Tracks the amount of the currently locked index token per user.
	/// This is equal to the sum(IndexTokenLocks[AccountId])
	///  (AccountId) -> Balance
	#[pallet::storage]
	#[pallet::getter(fn locked_index_tokens)]
	pub type LockedIndexToken<T: Config> = StorageMap<_, Blake2_128Concat, T::AccountId, T::Balance, ValueQuery>;

	/// The range of the index token equivalent a deposit must be in in order to be allowed.
	///
	/// A valid deposit lies within `[deposit_bounds.minimum, deposit_bounds.maximum]`.
	#[pallet::storage]
	#[pallet::getter(fn deposit_bounds)]
	pub type IndexTokenDepositRange<T: Config> = StorageValue<_, DepositRange<T::Balance>, ValueQuery>;

	/// Metadata of an asset ( for reversed usage now ).
	#[pallet::storage]
	#[pallet::getter(fn asset_metadata)]
	pub(super) type Metadata<T: Config> = StorageMap<
		_,
		Blake2_128Concat,
		T::AssetId,
		AssetMetadata<BoundedVec<u8, T::StringLimit>>,
		ValueQuery,
		GetDefault,
		ConstU32<300_000>,
	>;

	#[pallet::genesis_config]
	pub struct GenesisConfig<T: Config> {
		/// The range that determines valid deposits.
		pub deposit_range: DepositRange<T::Balance>,
		/// All the liquid assets together with their parachain id known at
		/// genesis
		pub liquid_assets: Vec<(T::AssetId, polkadot_parachain::primitives::Id)>,
		/// ALl safts to register at genesis
		pub saft_assets: Vec<T::AssetId>,
	}

	#[cfg(feature = "std")]
	impl<T: Config> Default for GenesisConfig<T> {
		fn default() -> Self {
			Self {
				deposit_range: Default::default(),
				liquid_assets: Default::default(),
				saft_assets: Default::default(),
			}
		}
	}

	#[pallet::genesis_build]
	impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
		fn build(&self) {
			use xcm::v1::{Junction, Junctions, MultiLocation};

			LockupPeriod::<T>::set(T::LockupPeriod::get());
			RedemptionFee::<T>::set(T::RedemptionFee::get());

			for (asset, id) in self.liquid_assets.iter().cloned() {
				let availability = AssetAvailability::Liquid(MultiLocation {
					parents: 0,
					interior: Junctions::X1(Junction::Parachain(id.into())),
				});
				Assets::<T>::insert(asset, availability)
			}

			for asset in self.saft_assets.iter().cloned() {
				Assets::<T>::insert(asset, AssetAvailability::Saft)
			}

			IndexTokenDepositRange::<T>::put(self.deposit_range.clone());
		}
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub (super) fn deposit_event)]
	pub enum Event<T: Config> {
		/// A new asset was added to the index and some index token paid out
		/// \[AssetIndex, AssetUnits, IndexTokenRecipient, IndexTokenPayout\]
		AssetAdded(T::AssetId, T::Balance, AccountIdFor<T>, T::Balance),
		/// An asset was removed from the index and some index token transferred
		/// or burned \[AssetId, AssetUnits, Account, Recipient,
		/// IndexTokenNAV\]
		AssetRemoved(T::AssetId, T::Balance, AccountIdFor<T>, Option<AccountIdFor<T>>, T::Balance),
		/// A new asset was registered in the index
		/// \[Asset, Availability\]
		AssetRegistered(T::AssetId, AssetAvailability),
		/// A new deposit of an asset into the index has been performed
		/// \[AssetId, AssetUnits, Account, PINTPayout\]
		Deposited(T::AssetId, T::Balance, AccountIdFor<T>, T::Balance),
		/// Started the withdrawal process
		/// \[Account, PINTAmount\]
		WithdrawalInitiated(AccountIdFor<T>, T::Balance),
		/// Completed a single asset withdrawal of the PendingRedemption
		/// \[Account, AssetId, AssetUnits\]
		Withdrawn(AccountIdFor<T>, T::AssetId, T::Balance),
		/// Completed an entire pending asset withdrawal
		/// \[Account, Assets\]
		WithdrawalCompleted(AccountIdFor<T>, Vec<AssetWithdrawal<T::AssetId, T::Balance>>),
		/// New metadata has been set for an asset. \[asset_id, name, symbol,
		/// decimals\]
		MetadataSet(T::AssetId, Vec<u8>, Vec<u8>, u8),
		/// The index token deposit range was updated.\[new_range\]
		IndexTokenDepositRangeUpdated(DepositRange<T::Balance>),
		/// Lockup Period has been updated
		NewLockupPeriod(T::BlockNumber),
		/// RedemptionFeeRange has been updated
		NewRedemptionFeeRange(RedemptionFeeRange<T::BlockNumber>),
	}

	#[pallet::error]
	pub enum Error<T> {
		/// Thrown if the given asset was the native asset and is disallowed
		NativeAssetDisallowed,
		/// Thrown if a SAFT asset operation was requested for a registered
		/// liquid asset.
		ExpectedSAFT,
		/// Thrown if a liquid asset operation was requested for a registered
		/// SAFT asset.
		ExpectedLiquid,
		/// Thrown when trying to remove deposits with no deposits
		NoDeposits,
		/// Invalid metadata given.
		BadMetadata,
		/// Thrown when calculate reademption fee failed
		CalculateRedemptionFeeFailed,
		/// Thrown if no index could be found for an asset identifier.
		UnsupportedAsset,
		/// Thrown if the given amount of PINT to redeem is too low
		MinimumRedemption,
		/// Thrown when the redeemer does not have enough PINT as is requested
		/// for withdrawal.
		InsufficientDeposit,
		/// Thrown when to withdrawals are available to complete
		NoPendingWithdrawals,
		/// Thrown if the asset that should be added is already registered
		AssetAlreadyExists,
		/// Thrown if the asset that should be added has not been registered.
		AssetNotExists,
		/// This gets thrown if the total supply of index tokens is 0 so no NAV can be calculated to
		/// determine the Asset/Index Token rate.
		InsufficientIndexTokens,
		/// Thrown if deposits reach limit
		TooManyDeposits,
		/// Thrown when the given decimals is zero or too high
		InvalidDecimals,
		/// Thrown when the given DepositRange is invalid
		InvalidDepositRange,
		/// Thrown when the given RedemptionFeeRange is invalid
		InvalidRedemptionFeeRange,
		/// Attempted to set LockupPeriod out of the range of 1 day ~ 28 days
		InvalidLockupPeriod,
		/// The deposited amount is below the minimum value required.
		DepositAmountBelowMinimum,
		/// The deposited amount exceeded the cap allowed.
		DepositExceedsMaximum,
	}

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

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// Callable by the governance committee to add new liquid assets to the
		/// index and mint the given amount IndexToken.
		/// The amount of PINT minted and awarded to the LP is specified as part
		/// of the associated proposal
		/// Caller's balance is updated to allocate the correct amount of the
		/// IndexToken.
		/// The given amount of assets must already exist in the caller's account,
		/// they are then transferred to the treasury account.
		///
		/// The Governance committee decides the tokens that comprise the index,
		/// as well as the allocation of each and their value.
		#[pallet::weight(T::WeightInfo::add_asset())]
		pub fn add_asset(
			origin: OriginFor<T>,
			asset_id: T::AssetId,
			units: T::Balance,
			amount: T::Balance,
		) -> DispatchResult {
			Self::do_add_asset(T::AdminOrigin::ensure_origin(origin)?, asset_id, units, amount)
		}

		/// Add liquid asset with root origin, see `add_asset`
		#[pallet::weight(T::WeightInfo::add_asset())]
		pub fn force_add_asset(
			origin: OriginFor<T>,
			asset_id: T::AssetId,
			units: T::Balance,
			amount: T::Balance,
			recipient: T::AccountId,
		) -> DispatchResult {
			ensure_root(origin)?;
			Self::do_add_asset(recipient, asset_id, units, amount)
		}

		/// Dispatches transfer to move assets out of the index’s account,
		/// if a liquid asset is specified
		/// Callable by an admin.
		///
		/// Updates the index to reflect the removed assets (units) by burning
		/// index token accordingly. If the given asset is liquid, an
		/// xcm transfer will be dispatched to transfer the given units
		/// into the sovereign account of either:
		/// - the given `recipient` if provided
		/// - the caller's account if `recipient` is `None`
		#[pallet::weight(T::WeightInfo::remove_asset())]
		pub fn remove_asset(
			origin: OriginFor<T>,
			asset_id: T::AssetId,
			units: T::Balance,
			recipient: Option<T::AccountId>,
		) -> DispatchResult {
			Self::do_remove_asset(T::AdminOrigin::ensure_origin(origin)?, asset_id, units, recipient)
		}

		/// Remove liquid asset with root origin
		#[pallet::weight(T::WeightInfo::remove_asset())]
		pub fn force_remove_asset(
			origin: OriginFor<T>,
			who: T::AccountId,
			asset_id: T::AssetId,
			units: T::Balance,
			recipient: Option<T::AccountId>,
		) -> DispatchResult {
			ensure_root(origin)?;
			Self::do_remove_asset(who, asset_id, units, recipient)
		}

		/// Registers a new asset in the index together with its availability
		///
		/// Only callable by the admin origin and for assets that are not yet
		/// registered.
		#[pallet::weight(T::WeightInfo::register_asset())]
		pub fn register_asset(
			origin: OriginFor<T>,
			asset_id: T::AssetId,
			availability: AssetAvailability,
		) -> DispatchResult {
			T::AdminOrigin::ensure_origin(origin)?;

			// native asset can't be registered
			Self::ensure_not_native_asset(&asset_id)?;

			Assets::<T>::try_mutate(asset_id, |maybe_available| -> DispatchResult {
				// allow new assets only
				ensure!(maybe_available.replace(availability.clone()).is_none(), Error::<T>::AssetAlreadyExists);
				Ok(())
			})?;

			Self::deposit_event(Event::AssetRegistered(asset_id, availability));
			Ok(())
		}

		/// Updates the range for how much a deposit must be worth in index token in order to be
		/// accpedted.
		/// Only callable by the admin origin
		///
		/// Parameters:
		/// - `new_range`: The new valid range for deposits.
		#[pallet::weight(T::WeightInfo::set_deposit_range())]
		pub fn set_deposit_range(origin: OriginFor<T>, new_range: DepositRange<T::Balance>) -> DispatchResult {
			T::AdminOrigin::ensure_origin(origin)?;
			ensure!(!new_range.minimum.is_zero(), Error::<T>::InvalidDepositRange);
			ensure!(new_range.maximum > new_range.minimum, Error::<T>::InvalidDepositRange);
			IndexTokenDepositRange::<T>::put(&new_range);
			Self::deposit_event(Event::<T>::IndexTokenDepositRangeUpdated(new_range));
			Ok(())
		}

		/// Updates the range for redemption fee
		///
		/// Only callable by the admin origin
		///
		/// Parameters:
		/// - `new_range`: The new valid range for redemption fee.
		#[pallet::weight(T::WeightInfo::update_redemption_fees())]
		pub fn update_redemption_fees(
			origin: OriginFor<T>,
			new_range: RedemptionFeeRange<T::BlockNumber>,
		) -> DispatchResult {
			T::AdminOrigin::ensure_origin(origin)?;
			ensure!(new_range.range[0].0 < new_range.range[1].0, Error::<T>::InvalidRedemptionFeeRange);
			RedemptionFee::<T>::set(new_range.clone());
			Self::deposit_event(Event::<T>::NewRedemptionFeeRange(new_range));
			Ok(())
		}

		/// Updates the lockup period
		///
		/// Only callable by the admin origin
		///
		/// Parameters:
		/// - `lockup_period`: how long will the depositing assets will be locked
		#[pallet::weight(T::WeightInfo::set_lockup_period())]
		pub fn set_lockup_period(origin: OriginFor<T>, lockup_period: T::BlockNumber) -> DispatchResult {
			T::AdminOrigin::ensure_origin(origin)?;

			ensure!(
				T::LockupPeriodRange::min() <= lockup_period && lockup_period <= T::LockupPeriodRange::max(),
				Error::<T>::InvalidLockupPeriod
			);

			LockupPeriod::<T>::set(lockup_period);
			Self::deposit_event(Event::<T>::NewLockupPeriod(lockup_period));
			Ok(())
		}

		/// Force the metadata for an asset to some value.
		///
		/// Origin must be ForceOrigin.
		///
		/// Any deposit is left alone.
		///
		/// - `id`: The identifier of the asset to update.
		/// - `name`: The user friendly name of this asset. Limited in length by `StringLimit`.
		/// - `symbol`: The exchange symbol for this asset. Limited in length by `StringLimit`.
		/// - `decimals`: The number of decimals this asset uses to represent one unit.
		///
		/// Emits `MetadataSet`.
		///
		/// Weight: `O(N + S)` where N and S are the length of the name and
		/// symbol respectively.
		#[pallet::weight(T::WeightInfo::set_metadata())]
		pub fn set_metadata(
			origin: OriginFor<T>,
			id: T::AssetId,
			name: Vec<u8>,
			symbol: Vec<u8>,
			decimals: u8,
		) -> DispatchResult {
			T::AdminOrigin::ensure_origin(origin)?;

			ensure!(!name.is_empty(), Error::<T>::BadMetadata);
			ensure!(!symbol.is_empty(), Error::<T>::BadMetadata);
			ensure!(decimals <= T::MaxDecimals::get(), Error::<T>::InvalidDecimals);

			let bounded_name: BoundedVec<u8, T::StringLimit> =
				name.clone().try_into().map_err(|_| Error::<T>::BadMetadata)?;
			let bounded_symbol: BoundedVec<u8, T::StringLimit> =
				symbol.clone().try_into().map_err(|_| Error::<T>::BadMetadata)?;

			Metadata::<T>::insert(id, AssetMetadata { name: bounded_name, symbol: bounded_symbol, decimals });
			Self::deposit_event(Event::MetadataSet(id, name, symbol, decimals));
			Ok(())
		}

		/// Initiate a transfer from the user's sovereign account into the
		/// index.
		///
		/// This will withdraw the given amount from the user's sovereign
		/// account and mints PINT proportionally using the latest
		/// available price pairs
		#[pallet::weight(T::WeightInfo::deposit())]
		#[transactional]
		pub fn deposit(origin: OriginFor<T>, asset_id: T::AssetId, units: T::Balance) -> DispatchResult {
			let caller = T::AdminOrigin::ensure_origin(origin)?;
			if units.is_zero() {
				return Ok(());
			}

			// native asset can't be deposited here
			Self::ensure_not_native_asset(&asset_id)?;
			// only liquid assets can be deposited
			Self::ensure_liquid_asset(&asset_id)?;

			// can't calculate an exchange rate if the total supply of index tokens is 0
			if Self::index_token_issuance().is_zero() {
				return Err(Error::<T>::InsufficientIndexTokens.into());
			}

			// the amount of index token the given units of the liquid assets are worth
			let index_tokens = Self::index_token_equivalent(asset_id, units)?;

			// ensure the index token equivalent worth is within the set bounds
			Self::ensure_deposit_in_bounds(index_tokens)?;

			// transfer from the caller's sovereign account into the treasury's account
			T::Currency::transfer(asset_id, &caller, &Self::treasury_account(), units)?;

			// mint index token in caller's account
			Self::do_mint_index_token(&caller, index_tokens);

			// tell the remote asset manager that assets are available to bond
			T::RemoteAssetManager::deposit(asset_id, units);

			// insert new deposit
			Deposits::<T>::try_append(&caller, (index_tokens, frame_system::Pallet::<T>::block_number()))
				.map_err(|_| Error::<T>::TooManyDeposits)?;

			Self::deposit_event(Event::Deposited(asset_id, units, caller, index_tokens));
			Ok(())
		}

		/// Starts the withdraw process for the given amount of PINT to redeem
		/// for a distribution of underlying assets.
		///
		/// All withdrawals undergo an unlocking period after which the assets
		/// can be withdrawn. A withdrawal fee will be deducted from the
		/// PINT being redeemed by the LP depending on how long the
		/// assets remained in the index. The remaining PINT will be
		/// burned to match the new NAV after this withdrawal.
		///
		/// The distribution of the underlying assets will be equivalent to the
		/// ratio of the liquid assets in the index.
		#[pallet::weight(T::WeightInfo::withdraw())]
		#[transactional]
		pub fn withdraw(origin: OriginFor<T>, amount: T::Balance) -> DispatchResult {
			let caller = T::AdminOrigin::ensure_origin(origin.clone())?;
			ensure!(amount >= T::MinimumRedemption::get(), Error::<T>::MinimumRedemption);

			// update the locks of prior deposits
			Self::do_update_index_token_locks(&caller);

			let free_balance = T::IndexToken::free_balance(&caller);
			T::IndexToken::ensure_can_withdraw(
				&caller,
				amount,
				WithdrawReasons::all(),
				free_balance.saturating_sub(amount),
			)?;

			// amount = fees + redeem
			let fee = amount
				.fee(T::BaseWithdrawalFee::get())
				.ok_or(ArithmeticError::Overflow)?
				.saturating_add(Self::do_consolidate_deposits(&caller, amount)?);
			let redeem = amount.checked_sub(&fee).ok_or(Error::<T>::InsufficientDeposit)?.into();

			// calculate the payout for each asset based on the redeem amount
			let AssetRedemption { asset_amounts, redeemed_index_tokens } = Self::liquid_asset_redemptions(redeem)?;

			// update the index balance by burning all of the redeemed tokens and the fee
			// SAFETY: this is guaranteed to be lower than `amount`
			let effectively_withdrawn = fee + redeemed_index_tokens;

			// withdraw from caller balance
			T::IndexToken::withdraw(
				&caller,
				effectively_withdrawn,
				WithdrawReasons::all(),
				ExistenceRequirement::AllowDeath,
			)?;

			// issue new tokens to compensate the fee and put it into the treasury
			let fee = T::IndexToken::issue(fee);
			T::IndexToken::resolve_creating(&Self::treasury_account(), fee);

			let mut assets = Vec::with_capacity(asset_amounts.len());

			// start the redemption process for each withdrawal
			for (asset, units) in asset_amounts {
				// announce the unbonding routine
				T::RemoteAssetManager::announce_withdrawal(asset, units);
				// reserve the funds in the treasury's account until the redemption period is
				// over after which they can be transferred to the user account
				// NOTE: this should always succeed due to the way the asset distribution is
				// calculated
				T::Currency::reserve(asset, &Self::treasury_account(), units)?;
				assets.push(AssetWithdrawal { asset, units, reserved: units, withdrawn: false });
			}

			// after this block an asset withdrawal is allowed to advance to the transfer
			// state
			let end_block = frame_system::Pallet::<T>::block_number().saturating_add(T::WithdrawalPeriod::get());

			// lock the assets for the withdrawal period starting at current block
			PendingWithdrawals::<T>::append(&caller, PendingRedemption { end_block, assets });

			Self::deposit_event(Event::WithdrawalInitiated(caller, effectively_withdrawn));
			Ok(())
		}

		/// Attempts to complete all currently pending redemption processes
		/// started by the `withdraw` extrinsic.
		///
		/// This checks every pending withdrawal within `PendingWithdrawal` and
		/// tries to close it. Completing a withdrawal will succeed if
		/// following conditions are met:
		///   - the `LockupPeriod` has passed since the withdrawal was initiated
		///   - the treasury can cover the asset transfer to the caller's account, from which the
		///     caller then can initiate an `Xcm::Withdraw` to remove the assets from the PINT
		///     parachain entirely, if xcm transfers are supported.
		///
		/// *NOTE*: All individual withdrawals that resulted from "Withdraw"
		/// will be completed separately, however, the entire record of pending
		/// withdrawals will not be fully closed until the last withdrawal is
		/// completed. This means that a single `AssetWithdrawal` will be closed
		/// as soon as the aforementioned conditions are met, regardless of
		/// whether the other `AssetWithdrawal`s in the same `PendingWithdrawal` set
		/// can also be closed successfully.
		#[pallet::weight(T::WeightInfo::complete_withdraw())]
		#[transactional]
		pub fn complete_withdraw(origin: OriginFor<T>) -> DispatchResult {
			let caller = T::AdminOrigin::ensure_origin(origin.clone())?;
			let current_block = frame_system::Pallet::<T>::block_number();

			PendingWithdrawals::<T>::try_mutate_exists(&caller, |maybe_pending| -> DispatchResult {
				let pending = maybe_pending.take().ok_or(<Error<T>>::NoPendingWithdrawals)?;

				// try to redeem each redemption, but only close it if all assets could be
				// redeemed
				let still_pending: Vec<_> = pending
					.into_iter()
					.filter_map(|mut redemption| {
						// only try to close if the lockup period is over
						if redemption.end_block >= current_block &&
							Self::do_complete_redemption(&caller, &mut redemption.assets)
						{
							// all individual redemptions withdrawn, can remove them from storage
							Self::deposit_event(Event::WithdrawalCompleted(caller.clone(), redemption.assets));
							return None;
						}
						Some(redemption)
					})
					.collect();

				if !still_pending.is_empty() {
					// still have redemptions pending
					*maybe_pending = Some(still_pending);
				}

				Ok(())
			})
		}

		/// Updates the index token locks of the caller.
		///
		/// This removes expired locks and updates the caller's index token
		/// balance accordingly.
		#[pallet::weight(T::WeightInfo::unlock())]
		pub fn unlock(origin: OriginFor<T>) -> DispatchResult {
			let caller = T::AdminOrigin::ensure_origin(origin)?;
			Self::do_update_index_token_locks(&caller);
			Ok(())
		}
	}

	impl<T: Config> Pallet<T> {
		/// The account of the treausry that keeps track of all the assets
		/// contributed to the index
		pub fn treasury_account() -> AccountIdFor<T> {
			T::TreasuryPalletId::get().into_account()
		}

		/// The amount of index tokens held by the given user
		pub fn index_token_balance(account: &T::AccountId) -> T::Balance {
			T::IndexToken::total_balance(account)
		}

		/// The amount of index tokens
		pub fn index_token_issuance() -> T::Balance {
			T::IndexToken::total_issuance()
		}

		/// The free balance of the given account for the given asset.
		pub fn free_asset_balance(asset: T::AssetId, account: &T::AccountId) -> T::Balance {
			T::Currency::free_balance(asset, account)
		}

		/// The combined balance of the given account for the given asset.
		pub fn total_asset_balance(asset: T::AssetId, account: &T::AccountId) -> T::Balance {
			T::Currency::total_balance(asset, account)
		}

		/// The combined balance of the treasury account for the given asset.
		pub fn index_total_asset_balance(asset: T::AssetId) -> T::Balance {
			T::Currency::total_balance(asset, &Self::treasury_account())
		}

		/// The free balance of the treasury account for the given asset.
		pub fn index_free_asset_balance(asset: T::AssetId) -> T::Balance {
			T::Currency::free_balance(asset, &Self::treasury_account())
		}

		/// Iterates over all liquid assets
		pub fn liquid_assets() -> impl Iterator<Item = T::AssetId> {
			Assets::<T>::iter().filter(|(_, availability)| availability.is_liquid()).map(|(id, _)| id)
		}

		/// Iterates over all SAFT assets
		pub fn saft_assets() -> impl Iterator<Item = T::AssetId> {
			Assets::<T>::iter().filter(|(_, holding)| holding.is_saft()).map(|(k, _)| k)
		}

		fn calculate_nav_proportion(asset: T::AssetId, nav: Price) -> Result<Ratio, DispatchError> {
			// the proportion is `value(asset) / value(index)` and since `nav = value(index)/supply`, this is
			// `value(asset)/supply / nav`
			let asset_value = Self::net_asset_value(asset)?;
			let share = Ratio::checked_from_rational(asset_value.into(), Self::index_token_issuance().into())
				.ok_or(ArithmeticError::Overflow)?;
			share.checked_div(&nav).ok_or_else(|| ArithmeticError::Overflow.into())
		}

		/// Determine the index token equivalent value of the given saft_nav
		///
		/// Essentially how many index token the given `saft_nav` is worth we get this via `saft_nav
		/// / NAV` or `NAV^-1 * saft_nav`
		fn saft_equivalent(saft_nav: T::Balance) -> Result<T::Balance, DispatchError> {
			Self::nav()?
				.reciprocal()
				.and_then(|n| n.checked_mul_int(saft_nav.into()).and_then(|n| TryInto::<T::Balance>::try_into(n).ok()))
				.ok_or_else(|| ArithmeticError::Overflow.into())
		}

		/// Adds liquid asset units
		///
		/// - If asset exists, deposit more units into matched asset
		///
		/// This function is a no-op if:
		///  - The `units` to be converted is zero, this would be analogous to
		///    [`LocalTreasury::withdraw`]
		///  - The `amount` of index tokens to be received is less than the required ED and the
		///    account does not exist.
		fn do_add_asset(
			recipient: T::AccountId,
			asset_id: T::AssetId,
			units: T::Balance,
			amount: T::Balance,
		) -> DispatchResult {
			ensure!(Assets::<T>::contains_key(&asset_id), Error::<T>::AssetNotExists);

			if units.is_zero() {
				return Ok(());
			}

			// transfer the caller's funds into the treasury account in exchange for index tokens
			Self::add_liquid(&recipient, asset_id, units, amount)?;

			Self::deposit_event(Event::AssetAdded(asset_id, units, recipient, amount));
			Ok(())
		}

		/// Removes liquid assets
		fn do_remove_asset(
			who: T::AccountId,
			asset_id: T::AssetId,
			units: T::Balance,
			recipient: Option<T::AccountId>,
		) -> DispatchResult {
			if units.is_zero() {
				return Ok(());
			}
			Self::ensure_not_native_asset(&asset_id)?;

			// the amount of index token the given units of the liquid assets are worth
			let index_tokens = Self::index_token_equivalent(asset_id, units)?;

			// transfer the caller's fund into the treasury account
			Self::remove_liquid(&who, asset_id, units, index_tokens, recipient.clone())?;

			Self::deposit_event(Event::AssetRemoved(asset_id, units, who, recipient, index_tokens));
			Ok(())
		}

		/// The fee model depends on how long LP contributions remained in the index.
		/// Therefore, LP deposits in `deposit` are time-stamped (block number) so that fees can be
		/// determined as a function of time spent in the index.
		///
		/// This function consolidates the oldest deposits and removes the deposits implicated by
		/// the transferred withdrawal amount and returns the total redemption fee for the given
		/// amount.
		fn do_consolidate_deposits(caller: &T::AccountId, mut amount: T::Balance) -> Result<T::Balance, DispatchError> {
			<Deposits<T>>::try_mutate_exists(&caller, |maybe_deposits| -> Result<T::Balance, DispatchError> {
				let mut deposits = maybe_deposits.take().ok_or(<Error<T>>::NoDeposits)?;
				let mut total_fee: T::Balance = T::Balance::zero();
				let current_block = frame_system::Pallet::<T>::block_number();

				let redemption_fee_range = RedemptionFee::<T>::get();
				let mut calculate_redemption_fee_failed = false;
				let mut rem: Option<(T::Balance, T::BlockNumber)> = None;
				deposits.retain(|(index_tokens, block_number)| {
					// how long this deposit spent in the index.
					let time_spent = current_block.saturating_sub(*block_number);

					if amount.is_zero() {
						true
					} else if amount >= *index_tokens {
						amount = amount.saturating_sub(*index_tokens);
						if let Some(fee) = redemption_fee_range.redemption_fee(time_spent, *index_tokens) {
							total_fee = total_fee.saturating_add(fee);
						} else {
							calculate_redemption_fee_failed = true;
						}

						false
					} else {
						// the remaining amount is less than the oldest deposit, so we are simply updating the value of
						// the now oldest deposit
						rem = Some((index_tokens.saturating_sub(amount), *block_number));
						if let Some(fee) = redemption_fee_range.redemption_fee(time_spent, amount) {
							total_fee = total_fee.saturating_add(fee);
						} else {
							calculate_redemption_fee_failed = true;
						}

						amount = T::Balance::zero();
						true
					}
				});

				if calculate_redemption_fee_failed {
					return Err(Error::<T>::CalculateRedemptionFeeFailed.into());
				}

				if !deposits.is_empty() {
					if let Some(rem) = rem {
						// update the oldest value
						deposits[0] = rem;
					}
					*maybe_deposits = Some(deposits);
				}

				if !amount.is_zero() {
					return Err(<Error<T>>::InsufficientDeposit.into());
				}

				Ok(total_fee)
			})
		}

		/// Returns the relative price pair NAV/Asset to calculate the asset equivalent value:
		/// `num(asset) = num(index_tokens) * NAV/Asset`.
		///
		/// *NOTE*: assumes the `quote` is a liquid asset.
		fn liquid_nav_price_pair(nav: Price, quote: T::AssetId) -> Result<AssetPricePair<T::AssetId>, DispatchError> {
			let quote_price = T::PriceFeed::get_price(quote)?;
			let price = nav.checked_div(&quote_price).ok_or(ArithmeticError::Overflow)?;
			Ok(AssetPricePair::new(T::SelfAssetId::get(), quote, price))
		}

		/// Calculates the pure asset redemption for the given amount of the
		/// index token to be redeemed for all the liquid tokens in the index
		///
		/// *NOTE*:
		///   - This does not account for fees
		///   - This is a no-op for `redeem == 0`
		pub fn liquid_asset_redemptions(
			redeem: u128,
		) -> Result<AssetRedemption<T::AssetId, T::Balance>, DispatchError> {
			if redeem.is_zero() {
				return Ok(Default::default());
			}
			// track the index tokens that effectively are redeemed
			let mut redeemed_index_tokens = 0u128;

			// calculate the proportions of all liquid assets in the index' liquid value
			let AssetProportions { nav, proportions } = Self::liquid_asset_proportions()?;

			// the total NAV is sum(liquid_nav + saft_nav) and represents the real value of a 1unit of index
			// token
			let nav = Self::saft_nav()?.checked_add(&nav).ok_or(ArithmeticError::Overflow)?;

			// calculate the redeemed amounts
			let asset_amounts = proportions
				.into_iter()
				.map(|proportion| -> Result<_, DispatchError> {
					let index_tokens = proportion.of(redeem).ok_or(ArithmeticError::Overflow)?;
					redeemed_index_tokens =
						redeemed_index_tokens.checked_add(index_tokens).ok_or(ArithmeticError::Overflow)?;

					// the amount of index tokens to redeem in proportion of the liquid asset
					let index_tokens: T::Balance = index_tokens.try_into().map_err(|_| ArithmeticError::Overflow)?;

					// determine the asset amount based on the relative price pair NAV/Asset
					let nav_asset_price = Self::liquid_nav_price_pair(nav, proportion.asset)?;
					let asset_units: T::Balance = nav_asset_price
						.volume(index_tokens.into())
						.and_then(|n| TryInto::<T::Balance>::try_into(n).ok())
						.ok_or(ArithmeticError::Overflow)?;

					Ok((proportion.asset, asset_units))
				})
				.collect::<Result<_, _>>()?;

			Ok(AssetRedemption {
				asset_amounts,
				redeemed_index_tokens: redeemed_index_tokens.try_into().map_err(|_| ArithmeticError::Overflow)?,
			})
		}

		/// Ensures the given asset id is a liquid asset
		fn ensure_liquid_asset(asset_id: &T::AssetId) -> DispatchResult {
			Assets::<T>::get(asset_id)
				.filter(|availability| matches!(availability, AssetAvailability::Liquid(_)))
				.ok_or(Error::<T>::UnsupportedAsset)?;
			Ok(())
		}

		/// Ensures the given asset is not the native asset
		fn ensure_not_native_asset(asset_id: &T::AssetId) -> DispatchResult {
			ensure!(!Self::is_native_asset(*asset_id), Error::<T>::NativeAssetDisallowed);
			Ok(())
		}

		/// Whether the asset is in fact the native asset
		fn is_native_asset(asset_id: T::AssetId) -> bool {
			asset_id == T::SelfAssetId::get()
		}

		/// Mints the given amount of index token into the user's account and
		/// updates the lock accordingly
		fn do_mint_index_token(user: &T::AccountId, amount: T::Balance) {
			// increase the total issuance
			let issued = T::IndexToken::issue(amount);
			// add minted PINT to user's free balance
			T::IndexToken::resolve_creating(user, issued);

			Self::do_add_index_token_lock(user, amount);
		}

		/// Locks up the given amount of index token according to the
		/// `LockupPeriod` and updates the existing locks
		fn do_add_index_token_lock(user: &T::AccountId, amount: T::Balance) {
			let current_block = frame_system::Pallet::<T>::block_number();
			let mut locks = IndexTokenLocks::<T>::get(user);
			locks.push(IndexTokenLock { locked: amount, end_block: current_block + LockupPeriod::<T>::get() });
			Self::do_insert_index_token_locks(user, locks);
		}

		/// inserts the given locks and filters expired locks.
		fn do_insert_index_token_locks(user: &T::AccountId, locks: Vec<IndexTokenLock<T::BlockNumber, T::Balance>>) {
			let current_block = frame_system::Pallet::<T>::block_number();
			let mut locked = T::Balance::zero();

			let locks = locks
				.into_iter()
				.filter(|lock| {
					if current_block >= lock.end_block {
						// lock period is over
						false
					} else {
						// track locked amount
						locked = locked.saturating_add(lock.locked);
						true
					}
				})
				.collect::<Vec<_>>();

			if locks.is_empty() {
				// remove the lock entirely
				T::IndexToken::remove_lock(T::IndexTokenLockIdentifier::get(), user);
				IndexTokenLocks::<T>::remove(user);
				LockedIndexToken::<T>::remove(user);
			} else {
				// set the lock, if it already exists, this will update it
				T::IndexToken::set_lock(T::IndexTokenLockIdentifier::get(), user, locked, WithdrawReasons::all());

				IndexTokenLocks::<T>::insert(user, locks);
				LockedIndexToken::<T>::insert(user, locked);
			}
		}

		/// Updates the index token locks for the given user.
		fn do_update_index_token_locks(user: &T::AccountId) {
			let locks = IndexTokenLocks::<T>::get(user);
			if !locks.is_empty() {
				Self::do_insert_index_token_locks(user, locks)
			}
		}

		/// Tries to complete every single `AssetWithdrawal` by advancing their
		/// states towards the `Withdrawn` state. In which all assets were transferred to the
		/// caller's holding accounts.
		///
		/// Returns `true` if all entries are completed (the have been
		/// transferred to the caller's account)
		fn do_complete_redemption(
			caller: &T::AccountId,
			assets: &mut Vec<AssetWithdrawal<T::AssetId, T::Balance>>,
		) -> bool {
			// whether all assets reached state `Withdrawn`
			let mut all_withdrawn = true;

			for asset in assets {
				if !asset.withdrawn {
					// `unreserve` the previously reserved assets from the treasury.
					asset.reserved = T::Currency::unreserve(asset.asset, &Self::treasury_account(), asset.reserved);
					if T::Currency::transfer(asset.asset, &Self::treasury_account(), caller, asset.units).is_ok() {
						Self::deposit_event(Event::Withdrawn(caller.clone(), asset.asset, asset.units));
						asset.withdrawn = true;
						continue;
					}
				}
				all_withdrawn = false
			}
			all_withdrawn
		}

		/// Ensures the given lies within the configured deposit range
		pub fn ensure_deposit_in_bounds(amount: T::Balance) -> DispatchResult {
			let bounds = IndexTokenDepositRange::<T>::get();
			ensure!(amount >= bounds.minimum, Error::<T>::DepositAmountBelowMinimum);
			ensure!(amount <= bounds.maximum, Error::<T>::DepositExceedsMaximum);
			Ok(())
		}
	}

	impl<T: Config> AssetRecorder<T::AccountId, T::AssetId, T::Balance> for Pallet<T> {
		/// Creates an entry in the assets map and contributes the given amount
		/// of asset to the treasury.
		fn add_liquid(
			caller: &T::AccountId,
			asset_id: T::AssetId,
			units: T::Balance,
			nav: T::Balance,
		) -> DispatchResult {
			if units.is_zero() {
				return Ok(());
			}
			// native asset can't be added
			Self::ensure_not_native_asset(&asset_id)?;
			// transfer the asset from the caller to treasury account
			T::Currency::transfer(asset_id, caller, &Self::treasury_account(), units)?;
			// mint PINT into caller's balance increasing the total issuance
			T::IndexToken::deposit_creating(caller, nav);
			Ok(())
		}

		fn add_saft(
			caller: &T::AccountId,
			asset_id: T::AssetId,
			units: T::Balance,
			saft_nav: T::Balance,
		) -> DispatchResult {
			if units.is_zero() {
				return Ok(());
			}
			// native asset can't be added as saft
			Self::ensure_not_native_asset(&asset_id)?;

			// ensure that the given asset id is either SAFT or not yet registered
			Assets::<T>::try_mutate(asset_id, |maybe_available| -> DispatchResult {
				if let Some(exits) = maybe_available.replace(AssetAvailability::Saft) {
					ensure!(exits.is_saft(), Error::<T>::ExpectedSAFT);
				}
				Ok(())
			})?;

			// the current index token equivalent value of the given saft nav
			let index_token = Self::saft_equivalent(saft_nav)?;

			// mint the given units of the SAFT asset into the treasury's account
			T::Currency::deposit(asset_id, &Self::treasury_account(), units)?;

			// mint PINT into caller's balance increasing the total issuance
			T::IndexToken::deposit_creating(caller, index_token);
			Ok(())
		}

		fn insert_asset_availability(
			asset_id: T::AssetId,
			availability: AssetAvailability,
		) -> Option<AssetAvailability> {
			Assets::<T>::mutate(asset_id, |maybe_available| maybe_available.replace(availability))
		}

		fn remove_liquid(
			who: &T::AccountId,
			asset_id: T::AssetId,
			units: T::Balance,
			nav: T::Balance,
			recipient: Option<T::AccountId>,
		) -> DispatchResult {
			if units.is_zero() {
				return Ok(());
			}
			ensure!(Self::is_liquid_asset(&asset_id), Error::<T>::ExpectedLiquid);
			ensure!(T::IndexToken::can_slash(who, nav), Error::<T>::InsufficientDeposit);

			let recipient = recipient.unwrap_or_else(|| who.clone());

			// Execute the transfer which will take of updating the balance
			T::RemoteAssetManager::transfer_asset(recipient, asset_id, units)?;

			// burn index token accordingly, no index token changes in the meantime
			T::IndexToken::slash(who, nav);

			Ok(())
		}

		fn remove_saft(
			who: &T::AccountId,
			asset_id: T::AssetId,
			units: T::Balance,
			saft_nav: T::Balance,
		) -> DispatchResult {
			if units.is_zero() {
				return Ok(());
			}
			// native asset can't be processed here
			Self::ensure_not_native_asset(&asset_id)?;

			// the current index token equivalent value of the given saft nav
			let index_token = Self::saft_equivalent(saft_nav)?;

			ensure!(!Self::is_liquid_asset(&asset_id), Error::<T>::ExpectedSAFT);
			ensure!(T::IndexToken::can_slash(who, index_token), Error::<T>::InsufficientDeposit);

			// burn SAFT by withdrawing from the index
			T::Currency::withdraw(asset_id, &Self::treasury_account(), units)?;
			// burn index token accordingly, no index token changes in the meantime
			T::IndexToken::slash(who, index_token);

			Ok(())
		}
	}

	#[cfg(feature = "runtime-benchmarks")]
	impl<T: Config> AssetRecorderBenchmarks<T::AssetId, T::Balance> for Pallet<T> {
		/// create feed and add new liquid asset
		fn add_asset(
			asset_id: T::AssetId,
			units: T::Balance,
			location: MultiLocation,
			amount: T::Balance,
		) -> DispatchResult {
			let origin = T::AdminOrigin::successful_origin();
			let origin_account_id = T::AdminOrigin::ensure_origin(origin)?;

			// also mint the funds
			T::Currency::deposit(asset_id, &origin_account_id, amount)?;
			T::PriceFeedBenchmarks::create_feed(origin_account_id, asset_id).map_err(|e| e.error)?;

			// the tests of benchmarks register assets by default
			if Assets::<T>::get(asset_id).is_none() {
				Self::register_asset(
					T::AdminOrigin::successful_origin(),
					asset_id,
					AssetAvailability::Liquid(location),
				)?;
			}

			Self::add_asset(T::AdminOrigin::successful_origin(), asset_id, units, amount)
		}

		/// deposit index tokens to the testing account with saft_nav
		fn deposit_saft_equivalent(saft_nav: T::Balance) -> DispatchResult {
			let origin = T::AdminOrigin::successful_origin();
			let origin_account_id = T::AdminOrigin::ensure_origin(origin.clone()).unwrap();
			T::IndexToken::deposit_creating(&origin_account_id, Self::saft_equivalent(saft_nav)?);
			Ok(())
		}
	}

	impl<T: Config> MultiAssetRegistry<T::AssetId> for Pallet<T> {
		fn native_asset_location(asset: &T::AssetId) -> Option<MultiLocation> {
			Assets::<T>::get(asset).and_then(|availability| {
				if let AssetAvailability::Liquid(location) = availability {
					Some(location)
				} else {
					None
				}
			})
		}

		fn is_liquid_asset(asset: &T::AssetId) -> bool {
			Assets::<T>::get(asset).map(|availability| availability.is_liquid()).unwrap_or_default()
		}
	}

	impl<T: Config> SaftRegistry<T::AssetId, T::Balance> for Pallet<T> {
		fn net_saft_value(asset: T::AssetId) -> T::Balance {
			T::SaftRegistry::net_saft_value(asset)
		}
	}

	impl<T: Config> NavProvider<T::AssetId, T::Balance> for Pallet<T> {
		fn index_token_equivalent(asset: T::AssetId, units: T::Balance) -> Result<T::Balance, DispatchError> {
			// Price_asset/NAV*units
			if Self::is_native_asset(asset) {
				return Ok(units);
			}
			let price = Self::relative_asset_price(asset)?;
			price
				.reciprocal_volume(units.into())
				.and_then(|n| TryInto::<T::Balance>::try_into(n).ok())
				.ok_or_else(|| ArithmeticError::Overflow.into())
		}

		fn asset_equivalent(index_tokens: T::Balance, asset: T::AssetId) -> Result<T::Balance, DispatchError> {
			if Self::is_native_asset(asset) {
				return Ok(index_tokens);
			}
			// NAV/Price_asset*units
			let price = Self::relative_asset_price(asset)?;
			price
				.volume(index_tokens.into())
				.and_then(|n| TryInto::<T::Balance>::try_into(n).ok())
				.ok_or_else(|| ArithmeticError::Overflow.into())
		}

		fn relative_asset_price(asset: T::AssetId) -> Result<AssetPricePair<T::AssetId>, DispatchError> {
			let base_price = Self::nav()?;
			if Self::is_native_asset(asset) {
				return Ok(AssetPricePair::new(asset, asset, base_price));
			}

			let quote_price = if Self::is_liquid_asset(&asset) {
				T::PriceFeed::get_price(asset)?
			} else {
				let val = Self::net_saft_value(asset);
				Price::checked_from_rational(val.into(), Self::asset_balance(asset).into())
					.ok_or(ArithmeticError::Overflow)?
			};
			let price = base_price.checked_div(&quote_price).ok_or(ArithmeticError::Overflow)?;
			Ok(AssetPricePair::new(T::SelfAssetId::get(), asset, price))
		}

		fn calculate_net_asset_value(asset: T::AssetId, units: T::Balance) -> Result<T::Balance, DispatchError> {
			// the asset net worth depends on whether the asset is liquid or SAFT
			if Self::is_liquid_asset(&asset) {
				Self::calculate_net_liquid_value(asset, units)
			} else {
				Self::calculate_net_saft_value(asset, units)
			}
		}

		fn calculate_net_liquid_value(asset: T::AssetId, units: T::Balance) -> Result<T::Balance, DispatchError> {
			let price = T::PriceFeed::get_price(asset)?;
			price
				.checked_mul_int(units.into())
				.and_then(|n| TryInto::<T::Balance>::try_into(n).ok())
				.ok_or_else(|| ArithmeticError::Overflow.into())
		}

		fn calculate_net_saft_value(asset: T::AssetId, units: T::Balance) -> Result<T::Balance, DispatchError> {
			let val = Self::net_saft_value(asset);
			let price = Price::checked_from_rational(val.into(), Self::asset_balance(asset).into())
				.ok_or(ArithmeticError::Overflow)?;
			price
				.checked_mul_int(units.into())
				.and_then(|n| TryInto::<T::Balance>::try_into(n).ok())
				.ok_or_else(|| ArithmeticError::Overflow.into())
		}

		fn total_net_liquid_value() -> Result<U256, DispatchError> {
			Self::liquid_assets().into_iter().try_fold(U256::zero(), |worth, asset| -> Result<_, DispatchError> {
				worth
					.checked_add(U256::from(Self::net_liquid_value(asset)?.into()))
					.ok_or_else(|| ArithmeticError::Overflow.into())
			})
		}

		fn total_net_saft_value() -> Result<U256, DispatchError> {
			Self::saft_assets().into_iter().try_fold(U256::zero(), |worth, asset| -> Result<_, DispatchError> {
				worth
					.checked_add(U256::from(Self::net_saft_value(asset).into()))
					.ok_or_else(|| ArithmeticError::Overflow.into())
			})
		}

		fn total_net_asset_value() -> Result<U256, DispatchError> {
			Assets::<T>::iter().try_fold(U256::zero(), |value, (asset, availability)| -> Result<_, DispatchError> {
				if availability.is_liquid() {
					value.checked_add(U256::from(Self::net_liquid_value(asset)?.into()))
				} else {
					value.checked_add(U256::from(Self::net_saft_value(asset).into()))
				}
				.ok_or_else(|| ArithmeticError::Overflow.into())
			})
		}

		fn net_asset_value(asset: T::AssetId) -> Result<T::Balance, DispatchError> {
			if Self::is_liquid_asset(&asset) {
				Self::calculate_net_liquid_value(asset, Self::asset_balance(asset))
			} else {
				Ok(Self::net_saft_value(asset))
			}
		}

		fn nav() -> Result<Price, DispatchError> {
			let total_issuance = T::IndexToken::total_issuance();
			if total_issuance.is_zero() {
				return Ok(Price::zero());
			}

			Assets::<T>::iter().try_fold(Price::zero(), |nav, (asset, availability)| -> Result<_, DispatchError> {
				let value =
					if availability.is_liquid() { Self::net_liquid_value(asset)? } else { Self::net_saft_value(asset) };

				let proportion = Ratio::checked_from_rational(value.into(), total_issuance.into())
					.ok_or(ArithmeticError::Overflow)?;
				Ok(nav.checked_add(&proportion).ok_or(ArithmeticError::Overflow)?)
			})
		}

		fn liquid_nav() -> Result<Price, DispatchError> {
			let total_issuance = T::IndexToken::total_issuance();
			if total_issuance.is_zero() {
				return Ok(Price::zero());
			}
			Self::liquid_assets().try_fold(Price::zero(), |nav, asset| -> Result<_, DispatchError> {
				let value = Self::net_liquid_value(asset)?;
				let proportion = Ratio::checked_from_rational(value.into(), total_issuance.into())
					.ok_or(ArithmeticError::Overflow)?;
				Ok(nav.checked_add(&proportion).ok_or(ArithmeticError::Overflow)?)
			})
		}

		fn saft_nav() -> Result<Price, DispatchError> {
			let total_issuance = T::IndexToken::total_issuance();
			if total_issuance.is_zero() {
				return Ok(Price::zero());
			}
			Self::saft_assets().try_fold(Price::zero(), |nav, asset| -> Result<_, DispatchError> {
				let value = Self::net_saft_value(asset);
				let proportion = Ratio::checked_from_rational(value.into(), total_issuance.into())
					.ok_or(ArithmeticError::Overflow)?;
				Ok(nav.checked_add(&proportion).ok_or(ArithmeticError::Overflow)?)
			})
		}

		fn asset_proportion(asset: T::AssetId) -> Result<Ratio, DispatchError> {
			// the proportion is `value(asset) / value(index)` and since `nav = value(index)/supply`, this is
			// `value(asset)/supply / nav`
			let nav = Self::nav()?;
			Self::calculate_nav_proportion(asset, nav)
		}

		fn liquid_asset_proportion(asset: T::AssetId) -> Result<Ratio, DispatchError> {
			let nav = Self::liquid_nav()?;
			Self::calculate_nav_proportion(asset, nav)
		}

		fn saft_asset_proportion(asset: T::AssetId) -> Result<Ratio, DispatchError> {
			let nav = Self::saft_nav()?;
			Self::calculate_nav_proportion(asset, nav)
		}

		fn asset_proportions() -> Result<AssetProportions<T::AssetId>, DispatchError> {
			let nav = Self::nav()?;
			let proportions = Assets::<T>::iter()
				.map(|(id, _)| id)
				.map(|id| Self::calculate_nav_proportion(id, nav).map(|ratio| AssetProportion::new(id, ratio)))
				.collect::<Result<_, _>>()?;
			Ok(AssetProportions { nav, proportions })
		}

		fn liquid_asset_proportions() -> Result<AssetProportions<T::AssetId>, DispatchError> {
			let nav = Self::liquid_nav()?;
			let proportions = Self::liquid_assets()
				.map(|id| Self::calculate_nav_proportion(id, nav).map(|ratio| AssetProportion::new(id, ratio)))
				.collect::<Result<_, _>>()?;
			Ok(AssetProportions { nav, proportions })
		}

		fn saft_asset_proportions() -> Result<AssetProportions<T::AssetId>, DispatchError> {
			let nav = Self::saft_nav()?;
			let proportions = Self::saft_assets()
				.map(|id| Self::calculate_nav_proportion(id, nav).map(|ratio| AssetProportion::new(id, ratio)))
				.collect::<Result<_, _>>()?;
			Ok(AssetProportions { nav, proportions })
		}

		fn index_token_issuance() -> T::Balance {
			T::IndexToken::total_issuance()
		}

		fn asset_balance(asset: T::AssetId) -> T::Balance {
			// the free balance constitutes the funds held by the index
			T::Currency::free_balance(asset, &Self::treasury_account())
		}
	}

	/// Trait for the asset-index pallet extrinsic weights.
	pub trait WeightInfo {
		fn add_asset() -> Weight;
		fn complete_withdraw() -> Weight;
		fn register_asset() -> Weight;
		fn remove_asset() -> Weight;
		fn deposit() -> Weight;
		fn unlock() -> Weight;
		fn withdraw() -> Weight;
		fn set_metadata() -> Weight;
		fn set_deposit_range() -> Weight;
		fn set_lockup_period() -> Weight;
		fn update_redemption_fees() -> Weight;
	}

	/// For backwards compatibility and tests
	impl WeightInfo for () {
		fn add_asset() -> Weight {
			Default::default()
		}

		fn complete_withdraw() -> Weight {
			Default::default()
		}

		fn register_asset() -> Weight {
			Default::default()
		}

		fn remove_asset() -> Weight {
			Default::default()
		}

		fn deposit() -> Weight {
			Default::default()
		}

		fn set_metadata() -> Weight {
			Default::default()
		}

		fn unlock() -> Weight {
			Default::default()
		}

		fn withdraw() -> Weight {
			Default::default()
		}

		fn set_deposit_range() -> Weight {
			Default::default()
		}

		fn set_lockup_period() -> Weight {
			Default::default()
		}

		fn update_redemption_fees() -> Weight {
			Default::default()
		}
	}
}