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
//! # Xtokens Module
//!
//! ## Overview
//!
//! The xtokens module provides cross-chain token transfer functionality, by
//! cross-consensus messages(XCM).
//!
//! The xtokens module provides functions for
//! - Token transfer from parachains to relay chain.
//! - Token transfer between parachains, including relay chain tokens like DOT,
//!   KSM, and parachain tokens like ACA, aUSD.
//!
//! ## Interface
//!
//! ### Dispatchable functions
//!
//! - `transfer`: Transfer local assets with given `CurrencyId` and `Amount`.
//! - `transfer_multiasset`: Transfer `MultiAsset` assets.

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

use frame_support::{
	log,
	pallet_prelude::*,
	require_transactional,
	traits::{Contains, Get},
	Parameter,
};
use frame_system::{ensure_signed, pallet_prelude::*};
use sp_runtime::{
	traits::{AtLeast32BitUnsigned, Convert, MaybeSerializeDeserialize, Member, Zero},
	DispatchError,
};
use sp_std::{prelude::*, result::Result};

use xcm::{latest::Weight, prelude::*};
use xcm_executor::traits::{InvertLocation, WeightBounds};

pub use module::*;
use orml_traits::{
	location::{Parse, Reserve},
	GetByKey, XcmTransfer,
};

mod mock;
mod tests;

enum TransferKind {
	/// Transfer self reserve asset.
	SelfReserveAsset,
	/// To reserve location.
	ToReserve,
	/// To non-reserve location.
	ToNonReserve,
}
use TransferKind::*;

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

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

		/// The balance type.
		type Balance: Parameter
			+ Member
			+ AtLeast32BitUnsigned
			+ Default
			+ Copy
			+ MaybeSerializeDeserialize
			+ Into<u128>;

		/// Currency Id.
		type CurrencyId: Parameter + Member + Clone;

		/// Convert `T::CurrencyId` to `MultiLocation`.
		type CurrencyIdConvert: Convert<Self::CurrencyId, Option<MultiLocation>>;

		/// Convert `T::AccountId` to `MultiLocation`.
		type AccountIdToMultiLocation: Convert<Self::AccountId, MultiLocation>;

		/// Self chain location.
		#[pallet::constant]
		type SelfLocation: Get<MultiLocation>;

		/// Minimum xcm execution fee paid on destination chain.
		type MinXcmFee: GetByKey<MultiLocation, Option<u128>>;

		/// XCM executor.
		type XcmExecutor: ExecuteXcm<Self::Call>;

		/// MultiLocation filter
		type MultiLocationsFilter: Contains<MultiLocation>;

		/// Means of measuring the weight consumed by an XCM message locally.
		type Weigher: WeightBounds<Self::Call>;

		/// Base XCM weight.
		///
		/// The actually weight for an XCM message is `T::BaseXcmWeight +
		/// T::Weigher::weight(&msg)`.
		#[pallet::constant]
		type BaseXcmWeight: Get<Weight>;

		/// Means of inverting a location.
		type LocationInverter: InvertLocation;

		/// The maximum number of distinct assets allowed to be transferred in a
		/// single helper extrinsic.
		type MaxAssetsForTransfer: Get<usize>;

		/// The way to retreave the reserve of a MultiAsset. This can be
		/// configured to accept absolute or relative paths for self tokens
		type ReserveProvider: Reserve;
	}

	#[pallet::event]
	#[pallet::generate_deposit(fn deposit_event)]
	pub enum Event<T: Config> {
		/// Transferred `MultiAsset` with fee.
		TransferredMultiAssets {
			sender: T::AccountId,
			assets: MultiAssets,
			fee: MultiAsset,
			dest: MultiLocation,
		},
	}

	#[pallet::error]
	pub enum Error<T> {
		/// Asset has no reserve location.
		AssetHasNoReserve,
		/// Not cross-chain transfer.
		NotCrossChainTransfer,
		/// Invalid transfer destination.
		InvalidDest,
		/// Currency is not cross-chain transferable.
		NotCrossChainTransferableCurrency,
		/// The message's weight could not be determined.
		UnweighableMessage,
		// TODO: expand into XcmExecutionFailed(XcmError) after https://github.com/paritytech/substrate/pull/10242 done
		/// XCM execution failed.
		XcmExecutionFailed,
		/// Could not re-anchor the assets to declare the fees for the
		/// destination chain.
		CannotReanchor,
		/// Could not get ancestry of asset reserve location.
		InvalidAncestry,
		/// The MultiAsset is invalid.
		InvalidAsset,
		/// The destination `MultiLocation` provided cannot be inverted.
		DestinationNotInvertible,
		/// The version of the `Versioned` value used is not able to be
		/// interpreted.
		BadVersion,
		/// We tried sending distinct asset and fee but they have different
		/// reserve chains.
		DistinctReserveForAssetAndFee,
		/// The fee is zero.
		ZeroFee,
		/// The transfering asset amount is zero.
		ZeroAmount,
		/// The number of assets to be sent is over the maximum.
		TooManyAssetsBeingSent,
		/// The specified index does not exist in a MultiAssets struct.
		AssetIndexNonExistent,
		/// Fee is not enough.
		FeeNotEnough,
		/// Not supported MultiLocation
		NotSupportedMultiLocation,
		/// MinXcmFee not registered for certain reserve location
		MinXcmFeeNotDefined,
	}

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

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

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// Transfer native currencies.
		///
		/// `dest_weight` is the weight for XCM execution on the dest chain, and
		/// it would be charged from the transferred assets. If set below
		/// requirements, the execution may fail and assets wouldn't be
		/// received.
		///
		/// It's a no-op if any error on local XCM execution or message sending.
		/// Note sending assets out per se doesn't guarantee they would be
		/// received. Receiving depends on if the XCM message could be delivered
		/// by the network, and if the receiving chain would handle
		/// messages correctly.
		#[pallet::weight(Pallet::<T>::weight_of_transfer(currency_id.clone(), *amount, dest))]
		pub fn transfer(
			origin: OriginFor<T>,
			currency_id: T::CurrencyId,
			amount: T::Balance,
			dest: Box<VersionedMultiLocation>,
			dest_weight: Weight,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;
			let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::<T>::BadVersion)?;
			Self::do_transfer(who, currency_id, amount, dest, dest_weight)
		}

		/// Transfer `MultiAsset`.
		///
		/// `dest_weight` is the weight for XCM execution on the dest chain, and
		/// it would be charged from the transferred assets. If set below
		/// requirements, the execution may fail and assets wouldn't be
		/// received.
		///
		/// It's a no-op if any error on local XCM execution or message sending.
		/// Note sending assets out per se doesn't guarantee they would be
		/// received. Receiving depends on if the XCM message could be delivered
		/// by the network, and if the receiving chain would handle
		/// messages correctly.
		#[pallet::weight(Pallet::<T>::weight_of_transfer_multiasset(asset, dest))]
		pub fn transfer_multiasset(
			origin: OriginFor<T>,
			asset: Box<VersionedMultiAsset>,
			dest: Box<VersionedMultiLocation>,
			dest_weight: Weight,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;
			let asset: MultiAsset = (*asset).try_into().map_err(|()| Error::<T>::BadVersion)?;
			let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::<T>::BadVersion)?;
			Self::do_transfer_multiasset(who, asset, dest, dest_weight)
		}

		/// Transfer native currencies specifying the fee and amount as
		/// separate.
		///
		/// `dest_weight` is the weight for XCM execution on the dest chain, and
		/// it would be charged from the transferred assets. If set below
		/// requirements, the execution may fail and assets wouldn't be
		/// received.
		///
		/// `fee` is the amount to be spent to pay for execution in destination
		/// chain. Both fee and amount will be subtracted form the callers
		/// balance.
		///
		/// If `fee` is not high enough to cover for the execution costs in the
		/// destination chain, then the assets will be trapped in the
		/// destination chain
		///
		/// It's a no-op if any error on local XCM execution or message sending.
		/// Note sending assets out per se doesn't guarantee they would be
		/// received. Receiving depends on if the XCM message could be delivered
		/// by the network, and if the receiving chain would handle
		/// messages correctly.
		#[pallet::weight(Pallet::<T>::weight_of_transfer(currency_id.clone(), *amount, dest))]
		pub fn transfer_with_fee(
			origin: OriginFor<T>,
			currency_id: T::CurrencyId,
			amount: T::Balance,
			fee: T::Balance,
			dest: Box<VersionedMultiLocation>,
			dest_weight: Weight,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;
			let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::<T>::BadVersion)?;

			Self::do_transfer_with_fee(who, currency_id, amount, fee, dest, dest_weight)
		}

		/// Transfer `MultiAsset` specifying the fee and amount as separate.
		///
		/// `dest_weight` is the weight for XCM execution on the dest chain, and
		/// it would be charged from the transferred assets. If set below
		/// requirements, the execution may fail and assets wouldn't be
		/// received.
		///
		/// `fee` is the multiasset to be spent to pay for execution in
		/// destination chain. Both fee and amount will be subtracted form the
		/// callers balance For now we only accept fee and asset having the same
		/// `MultiLocation` id.
		///
		/// If `fee` is not high enough to cover for the execution costs in the
		/// destination chain, then the assets will be trapped in the
		/// destination chain
		///
		/// It's a no-op if any error on local XCM execution or message sending.
		/// Note sending assets out per se doesn't guarantee they would be
		/// received. Receiving depends on if the XCM message could be delivered
		/// by the network, and if the receiving chain would handle
		/// messages correctly.
		#[pallet::weight(Pallet::<T>::weight_of_transfer_multiasset(asset, dest))]
		pub fn transfer_multiasset_with_fee(
			origin: OriginFor<T>,
			asset: Box<VersionedMultiAsset>,
			fee: Box<VersionedMultiAsset>,
			dest: Box<VersionedMultiLocation>,
			dest_weight: Weight,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;
			let asset: MultiAsset = (*asset).try_into().map_err(|()| Error::<T>::BadVersion)?;
			let fee: MultiAsset = (*fee).try_into().map_err(|()| Error::<T>::BadVersion)?;
			let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::<T>::BadVersion)?;

			Self::do_transfer_multiasset_with_fee(who, asset, fee, dest, dest_weight)
		}

		/// Transfer several currencies specifying the item to be used as fee
		///
		/// `dest_weight` is the weight for XCM execution on the dest chain, and
		/// it would be charged from the transferred assets. If set below
		/// requirements, the execution may fail and assets wouldn't be
		/// received.
		///
		/// `fee_item` is index of the currencies tuple that we want to use for
		/// payment
		///
		/// It's a no-op if any error on local XCM execution or message sending.
		/// Note sending assets out per se doesn't guarantee they would be
		/// received. Receiving depends on if the XCM message could be delivered
		/// by the network, and if the receiving chain would handle
		/// messages correctly.
		#[pallet::weight(Pallet::<T>::weight_of_transfer_multicurrencies(currencies, fee_item, dest))]
		pub fn transfer_multicurrencies(
			origin: OriginFor<T>,
			currencies: Vec<(T::CurrencyId, T::Balance)>,
			fee_item: u32,
			dest: Box<VersionedMultiLocation>,
			dest_weight: Weight,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;
			let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::<T>::BadVersion)?;

			Self::do_transfer_multicurrencies(who, currencies, fee_item, dest, dest_weight)
		}

		/// Transfer several `MultiAsset` specifying the item to be used as fee
		///
		/// `dest_weight` is the weight for XCM execution on the dest chain, and
		/// it would be charged from the transferred assets. If set below
		/// requirements, the execution may fail and assets wouldn't be
		/// received.
		///
		/// `fee_item` is index of the MultiAssets that we want to use for
		/// payment
		///
		/// It's a no-op if any error on local XCM execution or message sending.
		/// Note sending assets out per se doesn't guarantee they would be
		/// received. Receiving depends on if the XCM message could be delivered
		/// by the network, and if the receiving chain would handle
		/// messages correctly.
		#[pallet::weight(Pallet::<T>::weight_of_transfer_multiassets(assets, fee_item, dest))]
		pub fn transfer_multiassets(
			origin: OriginFor<T>,
			assets: Box<VersionedMultiAssets>,
			fee_item: u32,
			dest: Box<VersionedMultiLocation>,
			dest_weight: Weight,
		) -> DispatchResult {
			let who = ensure_signed(origin)?;
			let assets: MultiAssets = (*assets).try_into().map_err(|()| Error::<T>::BadVersion)?;
			let dest: MultiLocation = (*dest).try_into().map_err(|()| Error::<T>::BadVersion)?;

			// We first grab the fee
			let fee: &MultiAsset = assets.get(fee_item as usize).ok_or(Error::<T>::AssetIndexNonExistent)?;

			Self::do_transfer_multiassets(who, assets.clone(), fee.clone(), dest, dest_weight)
		}
	}

	impl<T: Config> Pallet<T> {
		fn do_transfer(
			who: T::AccountId,
			currency_id: T::CurrencyId,
			amount: T::Balance,
			dest: MultiLocation,
			dest_weight: Weight,
		) -> DispatchResult {
			let location: MultiLocation =
				T::CurrencyIdConvert::convert(currency_id).ok_or(Error::<T>::NotCrossChainTransferableCurrency)?;

			ensure!(!amount.is_zero(), Error::<T>::ZeroAmount);
			ensure!(
				T::MultiLocationsFilter::contains(&dest),
				Error::<T>::NotSupportedMultiLocation
			);

			let asset: MultiAsset = (location, amount.into()).into();
			Self::do_transfer_multiassets(who, vec![asset.clone()].into(), asset, dest, dest_weight)
		}

		fn do_transfer_with_fee(
			who: T::AccountId,
			currency_id: T::CurrencyId,
			amount: T::Balance,
			fee: T::Balance,
			dest: MultiLocation,
			dest_weight: Weight,
		) -> DispatchResult {
			let location: MultiLocation =
				T::CurrencyIdConvert::convert(currency_id).ok_or(Error::<T>::NotCrossChainTransferableCurrency)?;

			ensure!(!amount.is_zero(), Error::<T>::ZeroAmount);
			ensure!(!fee.is_zero(), Error::<T>::ZeroFee);
			ensure!(
				T::MultiLocationsFilter::contains(&dest),
				Error::<T>::NotSupportedMultiLocation
			);

			let asset = (location.clone(), amount.into()).into();
			let fee_asset: MultiAsset = (location, fee.into()).into();

			// Push contains saturated addition, so we should be able to use it safely
			let mut assets = MultiAssets::new();
			assets.push(asset);
			assets.push(fee_asset.clone());

			Self::do_transfer_multiassets(who, assets, fee_asset, dest, dest_weight)
		}

		fn do_transfer_multiasset(
			who: T::AccountId,
			asset: MultiAsset,
			dest: MultiLocation,
			dest_weight: Weight,
		) -> DispatchResult {
			Self::do_transfer_multiassets(who, vec![asset.clone()].into(), asset, dest, dest_weight)
		}

		fn do_transfer_multiasset_with_fee(
			who: T::AccountId,
			asset: MultiAsset,
			fee: MultiAsset,
			dest: MultiLocation,
			dest_weight: Weight,
		) -> DispatchResult {
			// Push contains saturated addition, so we should be able to use it safely
			let mut assets = MultiAssets::new();
			assets.push(asset);
			assets.push(fee.clone());

			Self::do_transfer_multiassets(who, assets, fee, dest, dest_weight)?;

			Ok(())
		}

		fn do_transfer_multicurrencies(
			who: T::AccountId,
			currencies: Vec<(T::CurrencyId, T::Balance)>,
			fee_item: u32,
			dest: MultiLocation,
			dest_weight: Weight,
		) -> DispatchResult {
			ensure!(
				currencies.len() <= T::MaxAssetsForTransfer::get(),
				Error::<T>::TooManyAssetsBeingSent
			);
			ensure!(
				T::MultiLocationsFilter::contains(&dest),
				Error::<T>::NotSupportedMultiLocation
			);

			let mut assets = MultiAssets::new();

			// Lets grab the fee amount and location first
			let (fee_currency_id, fee_amount) = currencies
				.get(fee_item as usize)
				.ok_or(Error::<T>::AssetIndexNonExistent)?;

			for (currency_id, amount) in &currencies {
				let location: MultiLocation = T::CurrencyIdConvert::convert(currency_id.clone())
					.ok_or(Error::<T>::NotCrossChainTransferableCurrency)?;
				ensure!(!amount.is_zero(), Error::<T>::ZeroAmount);

				// Push contains saturated addition, so we should be able to use it safely
				assets.push((location, (*amount).into()).into())
			}

			// We construct the fee now, since getting it from assets wont work as assets
			// sorts it
			let fee_location: MultiLocation = T::CurrencyIdConvert::convert(fee_currency_id.clone())
				.ok_or(Error::<T>::NotCrossChainTransferableCurrency)?;

			let fee: MultiAsset = (fee_location, (*fee_amount).into()).into();

			Self::do_transfer_multiassets(who, assets, fee, dest, dest_weight)
		}

		fn do_transfer_multiassets(
			who: T::AccountId,
			assets: MultiAssets,
			fee: MultiAsset,
			dest: MultiLocation,
			dest_weight: Weight,
		) -> DispatchResult {
			ensure!(
				assets.len() <= T::MaxAssetsForTransfer::get(),
				Error::<T>::TooManyAssetsBeingSent
			);
			ensure!(
				T::MultiLocationsFilter::contains(&dest),
				Error::<T>::NotSupportedMultiLocation
			);
			let origin_location = T::AccountIdToMultiLocation::convert(who.clone());

			let mut non_fee_reserve: Option<MultiLocation> = None;
			let asset_len = assets.len();
			for i in 0..asset_len {
				let asset = assets.get(i).ok_or(Error::<T>::AssetIndexNonExistent)?;
				ensure!(
					matches!(asset.fun, Fungibility::Fungible(x) if !x.is_zero()),
					Error::<T>::InvalidAsset
				);
				// `assets` includes fee, the reserve location is decided by non fee asset
				if (fee != *asset && non_fee_reserve.is_none()) || asset_len == 1 {
					non_fee_reserve = T::ReserveProvider::reserve(asset);
				}
				// make sure all non fee assets share the same reserve
				if non_fee_reserve.is_some() {
					ensure!(
						non_fee_reserve == T::ReserveProvider::reserve(asset),
						Error::<T>::DistinctReserveForAssetAndFee
					);
				}
			}

			let fee_reserve = T::ReserveProvider::reserve(&fee);
			if fee_reserve != non_fee_reserve {
				// Current only support `ToReserve` with relay-chain asset as fee. other case
				// like `NonReserve` or `SelfReserve` with relay-chain fee is not support.
				ensure!(non_fee_reserve == dest.chain_part(), Error::<T>::InvalidAsset);

				let reserve_location = non_fee_reserve.clone().ok_or(Error::<T>::AssetHasNoReserve)?;
				let min_xcm_fee = T::MinXcmFee::get(&reserve_location).ok_or(Error::<T>::MinXcmFeeNotDefined)?;

				// min xcm fee should less than user fee
				let fee_to_dest: MultiAsset = (fee.id.clone(), min_xcm_fee).into();
				ensure!(fee_to_dest < fee, Error::<T>::FeeNotEnough);

				let mut assets_to_dest = MultiAssets::new();
				for i in 0..asset_len {
					let asset = assets.get(i).ok_or(Error::<T>::AssetIndexNonExistent)?;
					if fee != *asset {
						assets_to_dest.push(asset.clone());
					} else {
						assets_to_dest.push(fee_to_dest.clone());
					}
				}

				let mut assets_to_fee_reserve = MultiAssets::new();
				let asset_to_fee_reserve = subtract_fee(&fee, min_xcm_fee);
				assets_to_fee_reserve.push(asset_to_fee_reserve.clone());

				let mut override_recipient = T::SelfLocation::get();
				if override_recipient == MultiLocation::here() {
					let dest_chain_part = dest.chain_part().ok_or(Error::<T>::InvalidDest)?;
					let ancestry = T::LocationInverter::ancestry();
					let _ = override_recipient
						.reanchor(&dest_chain_part, &ancestry)
						.map_err(|_| Error::<T>::CannotReanchor);
				}

				// First xcm sent to fee reserve chain and routed to dest chain.
				// We can use `MinXcmFee` configuration to decide which target parachain use
				// teleport. But as current there's only one case which is Parachain send back
				// asset to Statemine/t, So we set `use_teleport` to always `true` in this case.
				Self::execute_and_send_reserve_kind_xcm(
					origin_location.clone(),
					assets_to_fee_reserve,
					asset_to_fee_reserve,
					fee_reserve,
					&dest,
					Some(override_recipient),
					dest_weight,
					true,
				)?;

				// Second xcm send to dest chain.
				Self::execute_and_send_reserve_kind_xcm(
					origin_location,
					assets_to_dest,
					fee_to_dest,
					non_fee_reserve,
					&dest,
					None,
					dest_weight,
					false,
				)?;
			} else {
				Self::execute_and_send_reserve_kind_xcm(
					origin_location,
					assets.clone(),
					fee.clone(),
					non_fee_reserve,
					&dest,
					None,
					dest_weight,
					false,
				)?;
			}

			Self::deposit_event(Event::<T>::TransferredMultiAssets {
				sender: who,
				assets,
				fee,
				dest,
			});

			Ok(())
		}

		/// Execute and send xcm with given assets and fee to dest chain or
		/// reserve chain.
		fn execute_and_send_reserve_kind_xcm(
			origin_location: MultiLocation,
			assets: MultiAssets,
			fee: MultiAsset,
			reserve: Option<MultiLocation>,
			dest: &MultiLocation,
			maybe_recipient_override: Option<MultiLocation>,
			dest_weight: Weight,
			use_teleport: bool,
		) -> DispatchResult {
			let (transfer_kind, dest, reserve, recipient) = Self::transfer_kind(reserve, dest)?;
			let recipient = match maybe_recipient_override {
				Some(recipient) => recipient,
				None => recipient,
			};

			let mut msg = match transfer_kind {
				SelfReserveAsset => Self::transfer_self_reserve_asset(assets, fee, dest, recipient, dest_weight)?,
				ToReserve => Self::transfer_to_reserve(assets, fee, dest, recipient, dest_weight)?,
				ToNonReserve => {
					Self::transfer_to_non_reserve(assets, fee, reserve, dest, recipient, dest_weight, use_teleport)?
				}
			};

			let weight = T::Weigher::weight(&mut msg).map_err(|()| Error::<T>::UnweighableMessage)?;
			T::XcmExecutor::execute_xcm_in_credit(origin_location, msg, weight, weight)
				.ensure_complete()
				.map_err(|error| {
					log::error!("Failed execute transfer message with {:?}", error);
					Error::<T>::XcmExecutionFailed
				})?;

			Ok(())
		}

		fn transfer_self_reserve_asset(
			assets: MultiAssets,
			fee: MultiAsset,
			dest: MultiLocation,
			recipient: MultiLocation,
			dest_weight: Weight,
		) -> Result<Xcm<T::Call>, DispatchError> {
			Ok(Xcm(vec![TransferReserveAsset {
				assets: assets.clone(),
				dest: dest.clone(),
				xcm: Xcm(vec![
					Self::buy_execution(fee, &dest, dest_weight)?,
					Self::deposit_asset(recipient, assets.len() as u32),
				]),
			}]))
		}

		fn transfer_to_reserve(
			assets: MultiAssets,
			fee: MultiAsset,
			reserve: MultiLocation,
			recipient: MultiLocation,
			dest_weight: Weight,
		) -> Result<Xcm<T::Call>, DispatchError> {
			Ok(Xcm(vec![
				WithdrawAsset(assets.clone()),
				InitiateReserveWithdraw {
					assets: All.into(),
					reserve: reserve.clone(),
					xcm: Xcm(vec![
						Self::buy_execution(fee, &reserve, dest_weight)?,
						Self::deposit_asset(recipient, assets.len() as u32),
					]),
				},
			]))
		}

		fn transfer_to_non_reserve(
			assets: MultiAssets,
			fee: MultiAsset,
			reserve: MultiLocation,
			dest: MultiLocation,
			recipient: MultiLocation,
			dest_weight: Weight,
			use_teleport: bool,
		) -> Result<Xcm<T::Call>, DispatchError> {
			let mut reanchored_dest = dest.clone();
			if reserve == MultiLocation::parent() {
				match dest {
					MultiLocation {
						parents,
						interior: X1(Parachain(id)),
					} if parents == 1 => {
						reanchored_dest = Parachain(id).into();
					}
					_ => {}
				}
			}

			if !use_teleport {
				Ok(Xcm(vec![
					WithdrawAsset(assets.clone()),
					InitiateReserveWithdraw {
						assets: All.into(),
						reserve: reserve.clone(),
						xcm: Xcm(vec![
							Self::buy_execution(half(&fee), &reserve, dest_weight)?,
							DepositReserveAsset {
								assets: All.into(),
								max_assets: assets.len() as u32,
								dest: reanchored_dest,
								xcm: Xcm(vec![
									Self::buy_execution(half(&fee), &dest, dest_weight)?,
									Self::deposit_asset(recipient, assets.len() as u32),
								]),
							},
						]),
					},
				]))
			} else {
				Ok(Xcm(vec![
					WithdrawAsset(assets.clone()),
					InitiateReserveWithdraw {
						assets: All.into(),
						reserve: reserve.clone(),
						xcm: Xcm(vec![
							Self::buy_execution(half(&fee), &reserve, dest_weight)?,
							InitiateTeleport {
								assets: All.into(),
								dest: reanchored_dest,
								xcm: Xcm(vec![
									Self::buy_execution(half(&fee), &dest, dest_weight)?,
									Self::deposit_asset(recipient, assets.len() as u32),
								]),
							},
						]),
					},
				]))
			}
		}

		fn deposit_asset(recipient: MultiLocation, max_assets: u32) -> Instruction<()> {
			DepositAsset {
				assets: All.into(),
				max_assets,
				beneficiary: recipient,
			}
		}

		fn buy_execution(
			asset: MultiAsset,
			at: &MultiLocation,
			weight: Weight,
		) -> Result<Instruction<()>, DispatchError> {
			let ancestry = T::LocationInverter::ancestry();
			let fees = asset
				.reanchored(at, &ancestry)
				.map_err(|_| Error::<T>::CannotReanchor)?;
			Ok(BuyExecution {
				fees,
				weight_limit: WeightLimit::Limited(weight),
			})
		}

		/// Ensure has the `dest` has chain part and recipient part.
		fn ensure_valid_dest(dest: &MultiLocation) -> Result<(MultiLocation, MultiLocation), DispatchError> {
			if let (Some(dest), Some(recipient)) = (dest.chain_part(), dest.non_chain_part()) {
				Ok((dest, recipient))
			} else {
				Err(Error::<T>::InvalidDest.into())
			}
		}

		/// Get the transfer kind.
		///
		/// Returns `Err` if `dest` combination doesn't make sense, or `reserve`
		/// is none, else returns a tuple of:
		/// - `transfer_kind`.
		/// - asset's `reserve` parachain or relay chain location,
		/// - `dest` parachain or relay chain location.
		/// - `recipient` location.
		fn transfer_kind(
			reserve: Option<MultiLocation>,
			dest: &MultiLocation,
		) -> Result<(TransferKind, MultiLocation, MultiLocation, MultiLocation), DispatchError> {
			let (dest, recipient) = Self::ensure_valid_dest(dest)?;

			let self_location = T::SelfLocation::get();
			ensure!(dest != self_location, Error::<T>::NotCrossChainTransfer);
			let reserve = reserve.ok_or(Error::<T>::AssetHasNoReserve)?;
			let transfer_kind = if reserve == self_location {
				SelfReserveAsset
			} else if reserve == dest {
				ToReserve
			} else {
				ToNonReserve
			};
			Ok((transfer_kind, dest, reserve, recipient))
		}
	}

	// weights
	impl<T: Config> Pallet<T> {
		/// Returns weight of `transfer_multiasset` call.
		fn weight_of_transfer_multiasset(asset: &VersionedMultiAsset, dest: &VersionedMultiLocation) -> Weight {
			let asset: Result<MultiAsset, _> = asset.clone().try_into();
			let dest = dest.clone().try_into();
			if let (Ok(asset), Ok(dest)) = (asset, dest) {
				if let Ok((transfer_kind, dest, _, reserve)) =
					Self::transfer_kind(T::ReserveProvider::reserve(&asset), &dest)
				{
					let mut msg = match transfer_kind {
						SelfReserveAsset => Xcm(vec![TransferReserveAsset {
							assets: vec![].into(),
							dest,
							xcm: Xcm(vec![]),
						}]),
						ToReserve | ToNonReserve => Xcm(vec![
							WithdrawAsset(MultiAssets::from(asset)),
							InitiateReserveWithdraw {
								assets: All.into(),
								// `dest` is always (equal to) `reserve` in both cases
								reserve,
								xcm: Xcm(vec![]),
							},
						]),
					};
					return T::Weigher::weight(&mut msg)
						.map_or(Weight::max_value(), |w| T::BaseXcmWeight::get().saturating_add(w));
				}
			}
			0
		}

		/// Returns weight of `transfer` call.
		fn weight_of_transfer(currency_id: T::CurrencyId, amount: T::Balance, dest: &VersionedMultiLocation) -> Weight {
			if let Some(location) = T::CurrencyIdConvert::convert(currency_id) {
				let asset = (location, amount.into()).into();
				Self::weight_of_transfer_multiasset(&asset, dest)
			} else {
				0
			}
		}

		/// Returns weight of `transfer` call.
		fn weight_of_transfer_multicurrencies(
			currencies: &[(T::CurrencyId, T::Balance)],
			fee_item: &u32,
			dest: &VersionedMultiLocation,
		) -> Weight {
			let mut assets: Vec<MultiAsset> = Vec::new();
			for (currency_id, amount) in currencies {
				if let Some(location) = T::CurrencyIdConvert::convert(currency_id.clone()) {
					let asset: MultiAsset = (location.clone(), (*amount).into()).into();
					assets.push(asset);
				} else {
					return 0;
				}
			}

			Self::weight_of_transfer_multiassets(&VersionedMultiAssets::from(MultiAssets::from(assets)), fee_item, dest)
		}

		/// Returns weight of `transfer_multiassets` call.
		fn weight_of_transfer_multiassets(
			assets: &VersionedMultiAssets,
			fee_item: &u32,
			dest: &VersionedMultiLocation,
		) -> Weight {
			let assets: Result<MultiAssets, ()> = assets.clone().try_into();
			let dest = dest.clone().try_into();
			if let (Ok(assets), Ok(dest)) = (assets, dest) {
				let reserve_location = Self::get_reserve_location(&assets, fee_item);
				if let Ok((transfer_kind, dest, _, reserve)) = Self::transfer_kind(reserve_location, &dest) {
					let mut msg = match transfer_kind {
						SelfReserveAsset => Xcm(vec![TransferReserveAsset {
							assets,
							dest,
							xcm: Xcm(vec![]),
						}]),
						ToReserve | ToNonReserve => Xcm(vec![
							WithdrawAsset(assets),
							InitiateReserveWithdraw {
								assets: All.into(),
								// `dest` is always (equal to) `reserve` in both cases
								reserve,
								xcm: Xcm(vec![]),
							},
						]),
					};
					return T::Weigher::weight(&mut msg)
						.map_or(Weight::max_value(), |w| T::BaseXcmWeight::get().saturating_add(w));
				}
			}
			0
		}

		/// Get reserve location by `assets` and `fee_item`. the `assets`
		/// includes fee asset and non fee asset. make sure assets have ge one
		/// asset. all non fee asset should share same reserve location.
		fn get_reserve_location(assets: &MultiAssets, fee_item: &u32) -> Option<MultiLocation> {
			let reserve_idx = if assets.len() == 1 {
				0
			} else if *fee_item == 0 {
				1
			} else {
				0
			};
			let asset = assets.get(reserve_idx);
			asset.and_then(T::ReserveProvider::reserve)
		}
	}

	impl<T: Config> XcmTransfer<T::AccountId, T::Balance, T::CurrencyId> for Pallet<T> {
		#[require_transactional]
		fn transfer(
			who: T::AccountId,
			currency_id: T::CurrencyId,
			amount: T::Balance,
			dest: MultiLocation,
			dest_weight: Weight,
		) -> DispatchResult {
			Self::do_transfer(who, currency_id, amount, dest, dest_weight)
		}

		#[require_transactional]
		fn transfer_multi_asset(
			who: T::AccountId,
			asset: MultiAsset,
			dest: MultiLocation,
			dest_weight: Weight,
		) -> DispatchResult {
			Self::do_transfer_multiasset(who, asset, dest, dest_weight)
		}
	}
}

/// Returns amount if `asset` is fungible, or zero.
fn fungible_amount(asset: &MultiAsset) -> u128 {
	if let Fungible(amount) = &asset.fun {
		*amount
	} else {
		Zero::zero()
	}
}

fn half(asset: &MultiAsset) -> MultiAsset {
	let half_amount = fungible_amount(asset)
		.checked_div(2)
		.expect("div 2 can't overflow; qed");
	MultiAsset {
		fun: Fungible(half_amount),
		id: asset.id.clone(),
	}
}

fn subtract_fee(asset: &MultiAsset, amount: u128) -> MultiAsset {
	let final_amount = fungible_amount(asset).checked_sub(amount).expect("fee too low; qed");
	MultiAsset {
		fun: Fungible(final_amount),
		id: asset.id.clone(),
	}
}