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

//! Support for generically creating XCM calls that are used within `Xcm::Transact`
//!
//! Receiving chains will decode incoming XCM calls based on their native types, therefore the
//! encoding of `Xcm::Transact` is runtime agnostic.
//!
//! This crate provides a set of abstractions for commonly used pallets.
//! To create chain agnostic bindings for pallets, a few things are required.
//!
//! First, an exact replica of the pallet's call enum, but not bound to `T: Config`, but with
//! generic types. like for `pallet_staking`:
//!
//! ```ignore
//! pub enum StakingCall<Source, Balance, AccountId> {
//!   Bond(/* -snip */ ),
//!   UnBond(/* -snip */ ),
//!   BondExtra(/* -snip */ ),
//! }
//! ```
//!
//! each enum variant represents the corresponding extrinsic of the pallet.
//!
//! All the pallet's type that would be configured as part of `Config` trait and are part of the
//! public interface are now generics: `<Source, Balance, AccountId>`.
//!
//! In the event that bindings for different runtimes are required for the pallet, we may still need
//! to support different types, e.g. `RuntimeA::Balance = u128;` and `RuntimeB::Balance = u64;`.
//!
//! Instead of maintaining multiple configs of `StakingCall` with different types, we maintain a
//! config with a single type configuration, preferably those from our local chain's
//! `frame_system::Config`, and then provide a separate encoder, that handle encoding context aware,
//! for example a `CurrencyId` or `AssetId`.
//!
//! For that we configure the pallet's `PalletCallEncoder` trait according to the set of different
//! runtime configs.
//!
//! For the `pallet_staking` that is `StakingCallEncoder` that can be configured with encoders for
//! all the `StakingCall`'s generic types
//!
//! ```
//! use xcm_calls::{PalletCallEncoder, PassthroughCompactEncoder, PassthroughEncoder};
//! use xcm_calls::staking::StakingCallEncoder;
//! // native types
//! type AssetId = u64;
//! type Balance = u128;
//! type AccountId = u64;
//! type AccountLookupSource =  sp_runtime::MultiAddress<AccountId, ()>;
//!  /// The encoder to use when transacting `pallet_staking` calls
//!  pub struct PalletStakingEncoder;
//!  impl StakingCallEncoder<AccountLookupSource, Balance, AccountId> for PalletStakingEncoder {
//!     // encode the `Balance` as the same type as configured but compactly
//!  	type CompactBalanceEncoder = PassthroughCompactEncoder<Balance, AssetId>;
//!     // encode the `AccountLookupSource` as the same type as configured
//!  	type SourceEncoder = PassthroughEncoder<AccountLookupSource, AssetId>;
//!     // encode the `AccountId` as the same type as configured
//!  	type AccountIdEncoder = PassthroughEncoder<AccountId, AssetId>;
//!  }
//!
//! // Implement the `PalletCallEncoder` that determines whether a call can be encoded based
//! // on the context
//! impl PalletCallEncoder for PalletStakingEncoder {
//! 	type Context = AssetId;
//! 	fn can_encode(_ctx: &Self::Context) -> bool {
//! 		// allow all calls
//!         // handling this separately here allows us to eventually support additional chains
//!         // without runtime upgrades
//! 		true
//! 	}
//! }
//! ```

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

use codec::{Encode, Output};
use frame_support::sp_std::marker::PhantomData;

pub use encode_with::*;

pub mod assets;
mod encode_with;
pub mod proxy;
pub mod staking;
pub mod utility;

/// Represents an extrinsic of a pallet configured inside a runtime
#[derive(Encode)]
pub struct RuntimeCall<Call> {
	/// The index of the call's pallet within the runtime.
	///
	/// This must be equivalent with the `#[codec(index = <pallet_index>)]`
	/// annotation.
	pub pallet_index: u8,

	/// The actual dispatchable call of a pallet, like `system::Call::remark(..)`
	pub call: Call,
}

/// Abstraction over a dispatchable call in a pallet
pub trait PalletCall: Sized {
	/// Returns the index of the call within its pallet
	fn pallet_call_index(&self) -> u8;

	fn encoder<'a, 'b, Config: PalletCallEncoder>(
		&'a self,
		ctx: &'b Config::Context,
	) -> CallEncoder<'a, 'b, Self, Config> {
		CallEncoder::new(self, ctx)
	}
}

/// Common trait for encoders of pallet calls
pub trait PalletCallEncoder {
	/// The type used to determine whether this encoder can be applied.
	type Context;
	/// Whether the encoder can be applied
	fn can_encode(ctx: &Self::Context) -> bool;
}

/// Helps encoding the inner call based on the context used.
pub struct CallEncoder<'a, 'b, Call, Config: PalletCallEncoder> {
	/// The call to encode
	pub call: &'a Call,
	/// additional context required for encoding
	pub ctx: &'b Config::Context,
	marker: PhantomData<Config>,
}

impl<'a, 'b, Call, Config: PalletCallEncoder> CallEncoder<'a, 'b, Call, Config> {
	pub fn new(call: &'a Call, ctx: &'b Config::Context) -> Self {
		Self { call, ctx, marker: Default::default() }
	}

	/// Wraps the pallet call into a `RuntimeCall` with the given pallet index
	pub fn encode_runtime_call(self, pallet_index: u8) -> RuntimeCall<Self> {
		RuntimeCall { pallet_index, call: self }
	}
}

/// Wrapper around something to encode with additional context
pub struct ContextEncode<'a, I, C, E> {
	pub input: &'a I,
	pub ctx: &'a C,
	pub encoder: PhantomData<E>,
}

impl<'a, I, C, E> Encode for ContextEncode<'a, I, C, E>
where
	E: EncodeWith<I, C>,
{
	fn encode_to<T: Output + ?Sized>(&self, dest: &mut T) {
		E::encode_to_with(self.input, self.ctx, dest)
	}
}

#[cfg(test)]
mod tests {
	use std::{cell::RefCell, collections::HashSet};

	use codec::{Decode, Encode, MaxEncodedLen};
	use frame_election_provider_support::onchain;
	use frame_support::{
		parameter_types,
		sp_runtime::traits::BlakeTwo256,
		traits::{Currency, FindAuthor, Imbalance, InstanceFilter, OnUnbalanced, OneSessionHandler},
		weights::constants::RocksDbWeight,
	};
	use pallet_staking as staking;
	use pallet_staking::*;
	use sp_core::H256;
	use sp_runtime::{
		curve::PiecewiseLinear,
		testing::{Header, TestXt, UintAuthorityId},
		traits::IdentityLookup,
		Perbill,
	};
	use xcm::DoubleEncoded;

	use crate::{
		proxy::{ProxyCall, ProxyCallEncoder, ProxyParams, POLKADOT_PALLET_PROXY_INDEX},
		staking::{Bond, StakingCall, StakingCallEncoder, POLKADOT_PALLET_STAKING_INDEX},
		PassthroughCompactEncoder, PassthroughEncoder,
	};

	use super::*;
	use crate::{
		assets::{AssetParams, AssetsCall, AssetsCallEncoder, STATEMINT_PALLET_ASSETS_INDEX},
		utility::{UtilityCall, UtilityCallEncoder},
	};
	use frame_support::traits::Everything;

	/// The AccountId alias in this test module.
	pub(crate) type AccountId = u64;
	pub(crate) type AccountIndex = u64;
	pub(crate) type BlockNumber = u64;
	pub(crate) type Balance = u128;

	thread_local! {
		static SESSION: RefCell<(Vec<AccountId>, HashSet<AccountId>)> = RefCell::new(Default::default());
	}

	type NegativeImbalanceOf<T> =
		<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::NegativeImbalance;

	/// Another session handler struct to test on_disabled.
	pub struct OtherSessionHandler;
	impl OneSessionHandler<AccountId> for OtherSessionHandler {
		type Key = UintAuthorityId;

		fn on_genesis_session<'a, I: 'a>(_: I)
		where
			I: Iterator<Item = (&'a AccountId, Self::Key)>,
			AccountId: 'a,
		{
		}

		fn on_new_session<'a, I: 'a>(_: bool, validators: I, _: I)
		where
			I: Iterator<Item = (&'a AccountId, Self::Key)>,
			AccountId: 'a,
		{
			SESSION.with(|x| *x.borrow_mut() = (validators.map(|x| x.0.clone()).collect(), HashSet::new()));
		}

		fn on_disabled(validator_index: u32) {
			SESSION.with(|d| {
				let mut d = d.borrow_mut();
				let value = d.0[validator_index as usize];
				d.1.insert(value);
			})
		}
	}

	impl sp_runtime::BoundToRuntimeAppPublic for OtherSessionHandler {
		type Public = UintAuthorityId;
	}

	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
	type Block = frame_system::mocking::MockBlock<Test>;

	frame_support::construct_runtime!(
		pub enum Test where
			Block = Block,
			NodeBlock = Block,
			UncheckedExtrinsic = UncheckedExtrinsic,
		{
			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
			Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
			Balances: pallet_balances::{Pallet, Call, Storage, Event<T>},
			Utility: pallet_utility::{Pallet, Call, Event},

			// use polkadot index 7
			Staking: staking::{Pallet, Call, Storage, Event<T>} = 7,

			Session: pallet_session::{Pallet, Call, Storage, Event},

			// use polkadot index 29
			Proxy: pallet_proxy::{Pallet, Call, Storage, Event<T>} = 29,

			// use statemint index 50
			Assets: pallet_assets::{Pallet, Call, Storage, Event<T>} = 50,

			BagsList: pallet_bags_list::{Pallet, Call, Storage, Event<T>},
		}
	);

	const THRESHOLDS: [sp_npos_elections::VoteWeight; 9] = [10, 20, 30, 40, 50, 60, 1_000, 2_000, 10_000];

	parameter_types! {
		pub static BagThresholds: &'static [sp_npos_elections::VoteWeight] = &THRESHOLDS;
	}

	impl pallet_utility::Config for Test {
		type Event = Event;
		type Call = Call;
		type PalletsOrigin = OriginCaller;
		type WeightInfo = ();
	}

	impl pallet_bags_list::Config for Test {
		type Event = Event;
		type WeightInfo = ();
		type VoteWeightProvider = Staking;
		type BagThresholds = BagThresholds;
	}

	/// Author of block is always 11
	pub struct Author11;
	impl FindAuthor<AccountId> for Author11 {
		fn find_author<'a, I>(_digests: I) -> Option<AccountId>
		where
			I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,
		{
			Some(11)
		}
	}

	parameter_types! {
		pub const BlockHashCount: u64 = 250;
		pub BlockWeights: frame_system::limits::BlockWeights =
			frame_system::limits::BlockWeights::simple_max(
				frame_support::weights::constants::WEIGHT_PER_SECOND * 2
			);
		pub const MaxLocks: u32 = 1024;
		pub static SessionsPerEra: sp_staking::SessionIndex = 3;
		pub static ExistentialDeposit: Balance = 1;
		pub static SlashDeferDuration: EraIndex = 0;
		pub static Period: BlockNumber = 5;
		pub static Offset: BlockNumber = 0;
	}

	impl frame_system::Config for Test {
		type BaseCallFilter = Everything;
		type BlockWeights = ();
		type BlockLength = ();
		type DbWeight = RocksDbWeight;
		type Origin = Origin;
		type Index = AccountIndex;
		type BlockNumber = BlockNumber;
		type Call = Call;
		type Hash = H256;
		type Hashing = ::sp_runtime::traits::BlakeTwo256;
		type AccountId = AccountId;
		type Lookup = IdentityLookup<Self::AccountId>;
		type Header = Header;
		type Event = Event;
		type BlockHashCount = BlockHashCount;
		type Version = ();
		type PalletInfo = PalletInfo;
		type AccountData = pallet_balances::AccountData<Balance>;
		type OnNewAccount = ();
		type OnKilledAccount = ();
		type SystemWeightInfo = ();
		type SS58Prefix = ();
		type OnSetCode = ();
	}
	impl pallet_balances::Config for Test {
		type MaxLocks = MaxLocks;
		type Balance = Balance;
		type Event = Event;
		type DustRemoval = ();
		type ExistentialDeposit = ExistentialDeposit;
		type AccountStore = System;
		type MaxReserves = ();
		type ReserveIdentifier = [u8; 8];
		type WeightInfo = ();
	}
	parameter_types! {
		pub const UncleGenerations: u64 = 0;
		pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(25);
	}
	sp_runtime::impl_opaque_keys! {
		pub struct SessionKeys {
			pub other: OtherSessionHandler,
		}
	}
	impl pallet_session::Config for Test {
		type SessionManager = pallet_session::historical::NoteHistoricalRoot<Test, Staking>;
		type Keys = SessionKeys;
		type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
		type SessionHandler = (OtherSessionHandler,);
		type Event = Event;
		type ValidatorId = AccountId;
		type ValidatorIdOf = pallet_staking::StashOf<Test>;
		type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
		type WeightInfo = ();
	}

	impl pallet_session::historical::Config for Test {
		type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
		type FullIdentificationOf = pallet_staking::ExposureOf<Test>;
	}
	parameter_types! {
		pub const MinimumPeriod: u64 = 5;
	}
	impl pallet_timestamp::Config for Test {
		type Moment = u64;
		type OnTimestampSet = ();
		type MinimumPeriod = MinimumPeriod;
		type WeightInfo = ();
	}
	pallet_staking_reward_curve::build! {
		const I_NPOS: PiecewiseLinear<'static> = curve!(
			min_inflation: 0_025_000,
			max_inflation: 0_100_000,
			ideal_stake: 0_500_000,
			falloff: 0_050_000,
			max_piece_count: 40,
			test_precision: 0_005_000,
		);
	}
	parameter_types! {
		pub const BondingDuration: EraIndex = 3;
		pub const RewardCurve: &'static PiecewiseLinear<'static> = &I_NPOS;
		pub const MaxNominatorRewardedPerValidator: u32 = 64;
		pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(75);
	}

	thread_local! {
		pub static REWARD_REMAINDER_UNBALANCED: RefCell<u128> = RefCell::new(0);
	}

	pub struct RewardRemainderMock;

	impl OnUnbalanced<NegativeImbalanceOf<Test>> for RewardRemainderMock {
		fn on_nonzero_unbalanced(amount: NegativeImbalanceOf<Test>) {
			REWARD_REMAINDER_UNBALANCED.with(|v| {
				*v.borrow_mut() += amount.peek();
			});
			drop(amount);
		}
	}

	impl onchain::Config for Test {
		type Accuracy = Perbill;
		type DataProvider = Staking;
	}
	impl staking::Config for Test {
		const MAX_NOMINATIONS: u32 = 16;
		type Currency = Balances;
		type UnixTime = Timestamp;
		type CurrencyToVote = frame_support::traits::SaturatingCurrencyToVote;
		type RewardRemainder = RewardRemainderMock;
		type Event = Event;
		type Slash = ();
		type Reward = ();
		type SessionsPerEra = SessionsPerEra;
		type SlashDeferDuration = SlashDeferDuration;
		type SlashCancelOrigin = frame_system::EnsureRoot<Self::AccountId>;
		type BondingDuration = BondingDuration;
		type SessionInterface = Self;
		type EraPayout = ConvertCurve<RewardCurve>;
		type NextNewSession = Session;
		type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
		type ElectionProvider = onchain::OnChainSequentialPhragmen<Self>;
		type GenesisElectionProvider = Self::ElectionProvider;
		type WeightInfo = ();
		type OffendingValidatorsThreshold = OffendingValidatorsThreshold;
		type SortedListProvider = BagsList;
	}

	parameter_types! {
		pub const ProxyDepositBase: Balance = 100;
		pub const ProxyDepositFactor: Balance = 100;
		pub const MaxProxies: u16 = 32;
		pub const AnnouncementDepositBase: Balance = 100;
		pub const AnnouncementDepositFactor: Balance = 100;
		pub const MaxPending: u16 = 32;
	}

	/// The type used to represent the kinds of proxying allowed.
	#[derive(
		Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, scale_info::TypeInfo,
	)]
	pub enum ProxyType {
		Any = 0,
		NonTransfer = 1,
		Governance = 2,
		Staking = 3,
		// Skip 4 as it is now removed (was SudoBalances)
		IdentityJudgement = 5,
		CancelProxy = 6,
	}

	impl Default for ProxyType {
		fn default() -> Self {
			Self::Any
		}
	}
	impl InstanceFilter<Call> for ProxyType {
		fn filter(&self, _: &Call) -> bool {
			true
		}
	}

	impl pallet_proxy::Config for Test {
		type Event = Event;
		type Call = Call;
		type Currency = Balances;
		type ProxyType = ProxyType;
		type ProxyDepositBase = ProxyDepositBase;
		type ProxyDepositFactor = ProxyDepositFactor;
		type MaxProxies = MaxProxies;
		type WeightInfo = ();
		type MaxPending = MaxPending;
		type CallHasher = BlakeTwo256;
		type AnnouncementDepositBase = AnnouncementDepositBase;
		type AnnouncementDepositFactor = AnnouncementDepositFactor;
	}

	impl<LocalCall> frame_system::offchain::SendTransactionTypes<LocalCall> for Test
	where
		Call: From<LocalCall>,
	{
		type OverarchingCall = Call;
		type Extrinsic = TestXt<Call, ()>;
	}

	parameter_types! {
		pub const AssetDeposit: u64 = 1;
		pub const ApprovalDeposit: u64 = 1;
		pub const StringLimit: u32 = 50;
		pub const MetadataDepositBase: u64 = 1;
		pub const MetadataDepositPerByte: u64 = 1;
	}

	type AssetId = u64;

	impl pallet_assets::Config for Test {
		type Event = Event;
		type Balance = Balance;
		type AssetId = AssetId;
		type Currency = Balances;
		type ForceOrigin = frame_system::EnsureRoot<u64>;
		type AssetDeposit = AssetDeposit;
		type MetadataDepositBase = MetadataDepositBase;
		type MetadataDepositPerByte = MetadataDepositPerByte;
		type ApprovalDeposit = ApprovalDeposit;
		type StringLimit = StringLimit;
		type Freezer = ();
		type WeightInfo = ();
		type Extra = ();
	}

	struct PalletUtilityEncoder;
	impl UtilityCallEncoder for PalletUtilityEncoder {}

	impl PalletCallEncoder for PalletUtilityEncoder {
		type Context = AssetId;
		fn can_encode(_ctx: &u64) -> bool {
			true
		}
	}

	struct PalletStakingEncoder;
	impl StakingCallEncoder<AccountId, Balance, AccountId> for PalletStakingEncoder {
		type CompactBalanceEncoder = PassthroughCompactEncoder<Balance, AssetId>;
		type SourceEncoder = PassthroughEncoder<AccountId, AssetId>;
		type AccountIdEncoder = PassthroughEncoder<AccountId, AssetId>;
	}

	impl PalletCallEncoder for PalletStakingEncoder {
		type Context = AssetId;
		fn can_encode(_ctx: &u64) -> bool {
			true
		}
	}

	struct PalletProxyEncoder;
	impl ProxyCallEncoder<AccountId, ProxyType, BlockNumber> for PalletProxyEncoder {
		type AccountIdEncoder = PassthroughEncoder<AccountId, AssetId>;
		type ProxyTypeEncoder = PassthroughEncoder<ProxyType, AssetId>;
		type BlockNumberEncoder = PassthroughEncoder<BlockNumber, AssetId>;
	}

	impl PalletCallEncoder for PalletProxyEncoder {
		type Context = AssetId;
		fn can_encode(_ctx: &u64) -> bool {
			true
		}
	}

	struct PalletAssetsEncoder;
	impl AssetsCallEncoder<AssetId, AccountId, Balance> for PalletAssetsEncoder {
		type CompactAssetIdEncoder = PassthroughCompactEncoder<AssetId, AssetId>;
		type SourceEncoder = PassthroughEncoder<AccountId, AssetId>;
		type CompactBalanceEncoder = PassthroughCompactEncoder<Balance, AssetId>;
	}

	impl PalletCallEncoder for PalletAssetsEncoder {
		type Context = AssetId;
		fn can_encode(_ctx: &u64) -> bool {
			true
		}
	}

	type PalletAssetsCall = pallet_assets::Call<Test>;
	type PalletStakingCall = pallet_staking::Call<Test>;
	type PalletProxyCall = pallet_proxy::Call<Test>;

	type XcmAssetsCall = AssetsCall<AssetId, AccountId, Balance>;
	type XcmStakingCall = StakingCall<AccountId, Balance, AccountId>;
	type XcmProxyCall = ProxyCall<AccountId, ProxyType, BlockNumber>;

	macro_rules! encode_decode_call {
		($ty:ident, $call:ident,  $encoder:ident, $index: expr) => {
			let xcm_pallet_call_encoded = $encoder.encode();
			assert_eq!(xcm_pallet_call_encoded, $call.encode());

			let call_decoded = $ty::decode(&mut xcm_pallet_call_encoded.as_slice()).unwrap();
			assert_eq!($call, call_decoded);

			let runtime_call: Call = $call.into();
			let xcm_runtime_call_encoded = $encoder.encode_runtime_call($index).encode();

			let runtime_call_encoded = runtime_call.encode();
			assert_eq!(xcm_runtime_call_encoded, runtime_call_encoded);

			let runtime_call_decoded = Call::decode(&mut xcm_runtime_call_encoded.as_slice()).unwrap();
			assert_eq!(runtime_call, runtime_call_decoded);
		};
	}

	#[test]
	fn test_pallet_staking_call_codec() {
		let bond_extra = PalletStakingCall::bond_extra { max_additional: 100 };
		let call: Call = bond_extra.into();
		let mut encoded: DoubleEncoded<Call> = call.encode().into();
		assert!(encoded.ensure_decoded().is_ok());
		assert_eq!(encoded.take_decoded().unwrap(), call)
	}

	#[test]
	fn can_encode_decode_bond_extra() {
		let xcm_bond_extra = XcmStakingCall::BondExtra(100);
		let call = PalletStakingCall::bond_extra { max_additional: 100 };
		let xcm_encoder = xcm_bond_extra.encoder::<PalletStakingEncoder>(&0);

		encode_decode_call!(PalletStakingCall, call, xcm_encoder, POLKADOT_PALLET_STAKING_INDEX);
	}

	#[test]
	fn can_encode_decode_bond() {
		let controller = 9;
		let value = 100;

		let xcm_bond =
			XcmStakingCall::Bond(Bond { controller, value, payee: super::staking::RewardDestination::Stash });
		let call = PalletStakingCall::bond { controller, value, payee: pallet_staking::RewardDestination::Stash };

		let xcm_encoder = xcm_bond.encoder::<PalletStakingEncoder>(&0);

		encode_decode_call!(PalletStakingCall, call, xcm_encoder, POLKADOT_PALLET_STAKING_INDEX);
	}

	#[test]
	fn can_encode_decode_unbond() {
		let xcm_unbond = XcmStakingCall::Unbond(100);
		let call = PalletStakingCall::unbond { value: 100 };
		let xcm_encoder = xcm_unbond.encoder::<PalletStakingEncoder>(&0);

		encode_decode_call!(PalletStakingCall, call, xcm_encoder, POLKADOT_PALLET_STAKING_INDEX);
	}

	#[test]
	fn can_encode_decode_add_proxy() {
		let delegate = 1337;
		let xcm_add_proxy = XcmProxyCall::AddProxy(ProxyParams { delegate, proxy_type: ProxyType::Staking, delay: 0 });
		let call = PalletProxyCall::add_proxy { delegate, proxy_type: ProxyType::Staking, delay: 0 };
		let xcm_encoder = xcm_add_proxy.encoder::<PalletProxyEncoder>(&0);

		encode_decode_call!(PalletProxyCall, call, xcm_encoder, POLKADOT_PALLET_PROXY_INDEX);
	}

	#[test]
	fn can_encode_decode_remove_proxy() {
		let delegate = 1337;
		let xcm_remove_proxy =
			XcmProxyCall::RemoveProxy(ProxyParams { delegate, proxy_type: ProxyType::Any, delay: 0 });

		let call = PalletProxyCall::remove_proxy { delegate, proxy_type: ProxyType::Any, delay: 0 };
		let xcm_encoder = xcm_remove_proxy.encoder::<PalletProxyEncoder>(&0);

		encode_decode_call!(PalletProxyCall, call, xcm_encoder, POLKADOT_PALLET_PROXY_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_mint() {
		let id = 100;
		let beneficiary = 1337;
		let amount = 99;
		let xmc_call = XcmAssetsCall::Mint(AssetParams { id, beneficiary, amount });

		let call = PalletAssetsCall::mint { id, beneficiary, amount };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_burn() {
		let id = 2342;
		let beneficiary = 234632;
		let amount = 4572934273;
		let xmc_call = XcmAssetsCall::Burn(AssetParams { id, beneficiary, amount });

		let call = PalletAssetsCall::burn { id, who: beneficiary, amount };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_transfer() {
		let id = 2342;
		let beneficiary = 234632;
		let amount = 4572934273;
		let xmc_call = XcmAssetsCall::Transfer(AssetParams { id, beneficiary, amount });

		let call = PalletAssetsCall::transfer { id, target: beneficiary, amount };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_force_transfer() {
		let id = 2342;
		let source = 3249234342;
		let beneficiary = 234632;
		let amount = 4572934273;
		let xmc_call = XcmAssetsCall::ForceTransfer(id, source, beneficiary, amount);

		let call = PalletAssetsCall::force_transfer { id, source, dest: beneficiary, amount };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_freeze() {
		let id = 2342;
		let source = 3249234342;
		let xmc_call = XcmAssetsCall::Freeze(id, source);

		let call = PalletAssetsCall::freeze { id, who: source };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_thaw() {
		let id = 2342;
		let source = 3249234342;
		let xmc_call = XcmAssetsCall::Thaw(id, source);

		let call = PalletAssetsCall::thaw { id, who: source };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_freeze_asset() {
		let id = 2342;
		let xmc_call = XcmAssetsCall::FreezeAsset(id);

		let call = PalletAssetsCall::freeze_asset { id };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_thaw_asset() {
		let id = 2342;
		let xmc_call = XcmAssetsCall::ThawAsset(id);

		let call = PalletAssetsCall::thaw_asset { id };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_approve_transfer() {
		let id = 2342;
		let beneficiary = 234632;
		let amount = 4572934273;
		let xmc_call = XcmAssetsCall::ApproveTransfer(AssetParams { id, beneficiary, amount });

		let call = PalletAssetsCall::approve_transfer { id, delegate: beneficiary, amount };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode_assets_transfer_approved() {
		let id = 2342;
		let source = 3249234342;
		let beneficiary = 234632;
		let amount = 4572934273;
		let xmc_call = XcmAssetsCall::TransferApproved(id, source, beneficiary, amount);

		let call = PalletAssetsCall::transfer_approved { id, owner: source, destination: beneficiary, amount };

		let xcm_encoder = xmc_call.encoder::<PalletAssetsEncoder>(&0);

		encode_decode_call!(PalletAssetsCall, call, xcm_encoder, STATEMINT_PALLET_ASSETS_INDEX);
	}

	#[test]
	fn can_encode_decode() {
		let dest = 1;
		let value = 1_000;
		let transfers = vec![
			pallet_balances::Call::<Test>::transfer { dest, value }.encode(),
			pallet_balances::Call::<Test>::transfer { dest, value }.encode(),
		];
		let _xcm_call = UtilityCall::BatchAll(transfers);
	}
}