mock.rs 10.3 KB
Newer Older
Gavin Wood's avatar
Gavin Wood committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

Shawn Tabrizi's avatar
Shawn Tabrizi committed
17
18
pub use crate::{
	AllowKnownQueryResponses, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom,
Gavin Wood's avatar
Gavin Wood committed
19
	FixedRateOfFungible, FixedWeightBounds, LocationInverter, TakeWeightCredit,
Gavin Wood's avatar
Gavin Wood committed
20
21
};
pub use frame_support::{
Shawn Tabrizi's avatar
Shawn Tabrizi committed
22
23
24
	dispatch::{
		DispatchError, DispatchInfo, DispatchResultWithPostInfo, Dispatchable, Parameter, Weight,
	},
Gavin Wood's avatar
Gavin Wood committed
25
26
	ensure, parameter_types,
	sp_runtime::DispatchErrorWithPostInfo,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
27
28
	traits::{Contains, Get, IsInVec},
	weights::{GetDispatchInfo, PostDispatchInfo},
Gavin Wood's avatar
Gavin Wood committed
29
};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
30
31
32
33
34
35
pub use parity_scale_codec::{Decode, Encode};
pub use sp_std::{
	cell::RefCell,
	collections::{btree_map::BTreeMap, btree_set::BTreeSet},
	fmt::Debug,
	marker::PhantomData,
Gavin Wood's avatar
Gavin Wood committed
36
};
Gavin Wood's avatar
Gavin Wood committed
37
pub use xcm::latest::prelude::*;
38
use xcm_executor::traits::{ClaimAssets, DropAssets};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
39
40
41
pub use xcm_executor::{
	traits::{ConvertOrigin, FilterAssetLocation, InvertLocation, OnResponse, TransactAsset},
	Assets, Config,
Gavin Wood's avatar
Gavin Wood committed
42
43
};

Alexander Popiak's avatar
Alexander Popiak committed
44
45
46
47
48
49
pub enum TestOrigin {
	Root,
	Relay,
	Signed(u64),
	Parachain(u32),
}
Gavin Wood's avatar
Gavin Wood committed
50

Alexander Popiak's avatar
Alexander Popiak committed
51
52
53
54
/// A dummy call.
///
/// Each item contains the amount of weight that it *wants* to consume as the first item, and the actual amount (if
/// different from the former) in the second option.
Gavin Wood's avatar
Gavin Wood committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#[derive(Debug, Encode, Decode, Eq, PartialEq, Clone, Copy)]
pub enum TestCall {
	OnlyRoot(Weight, Option<Weight>),
	OnlyParachain(Weight, Option<Weight>, Option<u32>),
	OnlySigned(Weight, Option<Weight>, Option<u64>),
	Any(Weight, Option<Weight>),
}
impl Dispatchable for TestCall {
	type Origin = TestOrigin;
	type Config = ();
	type Info = ();
	type PostInfo = PostDispatchInfo;
	fn dispatch(self, origin: Self::Origin) -> DispatchResultWithPostInfo {
		let mut post_info = PostDispatchInfo::default();
		post_info.actual_weight = match self {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
70
71
72
73
			TestCall::OnlyRoot(_, maybe_actual) |
			TestCall::OnlySigned(_, maybe_actual, _) |
			TestCall::OnlyParachain(_, maybe_actual, _) |
			TestCall::Any(_, maybe_actual) => maybe_actual,
Gavin Wood's avatar
Gavin Wood committed
74
75
		};
		if match (&origin, &self) {
Alexander Popiak's avatar
Alexander Popiak committed
76
77
			(TestOrigin::Parachain(i), TestCall::OnlyParachain(_, _, Some(j))) => i == j,
			(TestOrigin::Signed(i), TestCall::OnlySigned(_, _, Some(j))) => i == j,
Shawn Tabrizi's avatar
Shawn Tabrizi committed
78
79
80
81
			(TestOrigin::Root, TestCall::OnlyRoot(..)) |
			(TestOrigin::Parachain(_), TestCall::OnlyParachain(_, _, None)) |
			(TestOrigin::Signed(_), TestCall::OnlySigned(_, _, None)) |
			(_, TestCall::Any(..)) => true,
Gavin Wood's avatar
Gavin Wood committed
82
83
84
85
86
87
88
89
90
91
92
93
			_ => false,
		} {
			Ok(post_info)
		} else {
			Err(DispatchErrorWithPostInfo { error: DispatchError::BadOrigin, post_info })
		}
	}
}

impl GetDispatchInfo for TestCall {
	fn get_dispatch_info(&self) -> DispatchInfo {
		let weight = *match self {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
94
95
96
97
			TestCall::OnlyRoot(estimate, ..) |
			TestCall::OnlyParachain(estimate, ..) |
			TestCall::OnlySigned(estimate, ..) |
			TestCall::Any(estimate, ..) => estimate,
Gavin Wood's avatar
Gavin Wood committed
98
		};
Shawn Tabrizi's avatar
Shawn Tabrizi committed
99
		DispatchInfo { weight, ..Default::default() }
Gavin Wood's avatar
Gavin Wood committed
100
101
102
103
104
105
106
107
108
109
110
	}
}

thread_local! {
	pub static SENT_XCM: RefCell<Vec<(MultiLocation, opaque::Xcm)>> = RefCell::new(Vec::new());
}
pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm)> {
	SENT_XCM.with(|q| (*q.borrow()).clone())
}
pub struct TestSendXcm;
impl SendXcm for TestSendXcm {
111
	fn send_xcm(dest: MultiLocation, msg: opaque::Xcm) -> SendResult {
Gavin Wood's avatar
Gavin Wood committed
112
113
114
115
116
117
118
119
120
121
122
		SENT_XCM.with(|q| q.borrow_mut().push((dest, msg)));
		Ok(())
	}
}

thread_local! {
	pub static ASSETS: RefCell<BTreeMap<u64, Assets>> = RefCell::new(BTreeMap::new());
}
pub fn assets(who: u64) -> Vec<MultiAsset> {
	ASSETS.with(|a| a.borrow().get(&who).map_or(vec![], |a| a.clone().into()))
}
123
124
pub fn add_asset<AssetArg: Into<MultiAsset>>(who: u64, what: AssetArg) {
	ASSETS.with(|a| a.borrow_mut().entry(who).or_insert(Assets::new()).subsume(what.into()));
Gavin Wood's avatar
Gavin Wood committed
125
126
127
128
129
130
131
132
133
134
135
136
}

pub struct TestAssetTransactor;
impl TransactAsset for TestAssetTransactor {
	fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> Result<(), XcmError> {
		let who = to_account(who.clone()).map_err(|_| XcmError::LocationCannotHold)?;
		add_asset(who, what.clone());
		Ok(())
	}

	fn withdraw_asset(what: &MultiAsset, who: &MultiLocation) -> Result<Assets, XcmError> {
		let who = to_account(who.clone()).map_err(|_| XcmError::LocationCannotHold)?;
Shawn Tabrizi's avatar
Shawn Tabrizi committed
137
138
139
140
		ASSETS.with(|a| {
			a.borrow_mut()
				.get_mut(&who)
				.ok_or(XcmError::NotWithdrawable)?
Gavin Wood's avatar
Gavin Wood committed
141
142
				.try_take(what.clone().into())
				.map_err(|_| XcmError::NotWithdrawable)
Shawn Tabrizi's avatar
Shawn Tabrizi committed
143
		})
Gavin Wood's avatar
Gavin Wood committed
144
145
146
147
148
149
	}
}

pub fn to_account(l: MultiLocation) -> Result<u64, MultiLocation> {
	Ok(match l {
		// Siblings at 2000+id
150
		MultiLocation { parents: 1, interior: X1(Parachain(id)) } => 2000 + id as u64,
Gavin Wood's avatar
Gavin Wood committed
151
		// Accounts are their number
152
		MultiLocation { parents: 0, interior: X1(AccountIndex64 { index, .. }) } => index,
Gavin Wood's avatar
Gavin Wood committed
153
		// Children at 1000+id
154
		MultiLocation { parents: 0, interior: X1(Parachain(id)) } => 1000 + id as u64,
Gavin Wood's avatar
Gavin Wood committed
155
		// Self at 3000
156
		MultiLocation { parents: 0, interior: Here } => 3000,
Alexander Popiak's avatar
Alexander Popiak committed
157
		// Parent at 3001
158
159
		MultiLocation { parents: 1, interior: Here } => 3001,
		_ => return Err(l),
Gavin Wood's avatar
Gavin Wood committed
160
161
162
163
164
	})
}

pub struct TestOriginConverter;
impl ConvertOrigin<TestOrigin> for TestOriginConverter {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
165
166
167
168
	fn convert_origin(
		origin: MultiLocation,
		kind: OriginKind,
	) -> Result<TestOrigin, MultiLocation> {
169
		use OriginKind::*;
Gavin Wood's avatar
Gavin Wood committed
170
171
172
		match (kind, origin) {
			(Superuser, _) => Ok(TestOrigin::Root),
			(SovereignAccount, l) => Ok(TestOrigin::Signed(to_account(l)?)),
173
174
175
176
177
			(Native, MultiLocation { parents: 0, interior: X1(Parachain(id)) }) =>
				Ok(TestOrigin::Parachain(id)),
			(Native, MultiLocation { parents: 1, interior: Here }) => Ok(TestOrigin::Relay),
			(Native, MultiLocation { parents: 0, interior: X1(AccountIndex64 { index, .. }) }) =>
				Ok(TestOrigin::Signed(index)),
Gavin Wood's avatar
Gavin Wood committed
178
179
180
181
182
183
			(_, origin) => Err(origin),
		}
	}
}

thread_local! {
Gavin Wood's avatar
Gavin Wood committed
184
185
	pub static IS_RESERVE: RefCell<BTreeMap<MultiLocation, Vec<MultiAssetFilter>>> = RefCell::new(BTreeMap::new());
	pub static IS_TELEPORTER: RefCell<BTreeMap<MultiLocation, Vec<MultiAssetFilter>>> = RefCell::new(BTreeMap::new());
Gavin Wood's avatar
Gavin Wood committed
186
}
Gavin Wood's avatar
Gavin Wood committed
187
pub fn add_reserve(from: MultiLocation, asset: MultiAssetFilter) {
Gavin Wood's avatar
Gavin Wood committed
188
189
190
	IS_RESERVE.with(|r| r.borrow_mut().entry(from).or_default().push(asset));
}
#[allow(dead_code)]
Gavin Wood's avatar
Gavin Wood committed
191
pub fn add_teleporter(from: MultiLocation, asset: MultiAssetFilter) {
Gavin Wood's avatar
Gavin Wood committed
192
193
194
195
196
	IS_TELEPORTER.with(|r| r.borrow_mut().entry(from).or_default().push(asset));
}
pub struct TestIsReserve;
impl FilterAssetLocation for TestIsReserve {
	fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
197
198
		IS_RESERVE
			.with(|r| r.borrow().get(origin).map_or(false, |v| v.iter().any(|a| a.contains(asset))))
Gavin Wood's avatar
Gavin Wood committed
199
200
201
202
203
	}
}
pub struct TestIsTeleporter;
impl FilterAssetLocation for TestIsTeleporter {
	fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
204
205
		IS_TELEPORTER
			.with(|r| r.borrow().get(origin).map_or(false, |v| v.iter().any(|a| a.contains(asset))))
Gavin Wood's avatar
Gavin Wood committed
206
207
208
	}
}

Gavin Wood's avatar
Gavin Wood committed
209
use xcm::latest::Response;
Gavin Wood's avatar
Gavin Wood committed
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
pub enum ResponseSlot {
	Expecting(MultiLocation),
	Received(Response),
}
thread_local! {
	pub static QUERIES: RefCell<BTreeMap<u64, ResponseSlot>> = RefCell::new(BTreeMap::new());
}
pub struct TestResponseHandler;
impl OnResponse for TestResponseHandler {
	fn expecting_response(origin: &MultiLocation, query_id: u64) -> bool {
		QUERIES.with(|q| match q.borrow().get(&query_id) {
			Some(ResponseSlot::Expecting(ref l)) => l == origin,
			_ => false,
		})
	}
Gavin Wood's avatar
Gavin Wood committed
225
	fn on_response(
226
		_origin: &MultiLocation,
Gavin Wood's avatar
Gavin Wood committed
227
228
		query_id: u64,
		response: xcm::latest::Response,
229
		_max_weight: Weight,
Gavin Wood's avatar
Gavin Wood committed
230
	) -> Weight {
Gavin Wood's avatar
Gavin Wood committed
231
		QUERIES.with(|q| {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
232
233
			q.borrow_mut().entry(query_id).and_modify(|v| {
				if matches!(*v, ResponseSlot::Expecting(..)) {
Gavin Wood's avatar
Gavin Wood committed
234
					*v = ResponseSlot::Received(response);
Shawn Tabrizi's avatar
Shawn Tabrizi committed
235
236
				}
			});
Gavin Wood's avatar
Gavin Wood committed
237
238
239
240
241
		});
		10
	}
}
pub fn expect_response(query_id: u64, from: MultiLocation) {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
242
	QUERIES.with(|q| q.borrow_mut().insert(query_id, ResponseSlot::Expecting(from)));
Gavin Wood's avatar
Gavin Wood committed
243
244
}
pub fn response(query_id: u64) -> Option<Response> {
Shawn Tabrizi's avatar
Shawn Tabrizi committed
245
246
	QUERIES.with(|q| {
		q.borrow().get(&query_id).and_then(|v| match v {
Gavin Wood's avatar
Gavin Wood committed
247
248
249
			ResponseSlot::Received(r) => Some(r.clone()),
			_ => None,
		})
Shawn Tabrizi's avatar
Shawn Tabrizi committed
250
	})
Gavin Wood's avatar
Gavin Wood committed
251
252
253
}

parameter_types! {
254
	pub TestAncestry: MultiLocation = X1(Parachain(42)).into();
Gavin Wood's avatar
Gavin Wood committed
255
256
257
258
259
260
261
	pub UnitWeightCost: Weight = 10;
}
parameter_types! {
	// Nothing is allowed to be paid/unpaid by default.
	pub static AllowUnpaidFrom: Vec<MultiLocation> = vec![];
	pub static AllowPaidFrom: Vec<MultiLocation> = vec![];
	// 1_000_000_000_000 => 1 unit of asset for 1 unit of Weight.
262
	pub static WeightPrice: (AssetId, u128) = (From::from(Here), 1_000_000_000_000);
263
	pub static MaxInstructions: u32 = 100;
Gavin Wood's avatar
Gavin Wood committed
264
265
266
267
268
269
270
271
272
}

pub type TestBarrier = (
	TakeWeightCredit,
	AllowKnownQueryResponses<TestResponseHandler>,
	AllowTopLevelPaidExecutionFrom<IsInVec<AllowPaidFrom>>,
	AllowUnpaidExecutionFrom<IsInVec<AllowUnpaidFrom>>,
);

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
parameter_types! {
	pub static TrappedAssets: Vec<(MultiLocation, MultiAssets)> = vec![];
}

pub struct TestAssetTrap;

impl DropAssets for TestAssetTrap {
	fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight {
		let mut t: Vec<(MultiLocation, MultiAssets)> = TrappedAssets::get();
		t.push((origin.clone(), assets.into()));
		TrappedAssets::set(t);
		5
	}
}

impl ClaimAssets for TestAssetTrap {
	fn claim_assets(origin: &MultiLocation, ticket: &MultiLocation, what: &MultiAssets) -> bool {
		let mut t: Vec<(MultiLocation, MultiAssets)> = TrappedAssets::get();
		if let (0, X1(GeneralIndex(i))) = (ticket.parents, &ticket.interior) {
			if let Some((l, a)) = t.get(*i as usize) {
				if l == origin && a == what {
					t.swap_remove(*i as usize);
					TrappedAssets::set(t);
					return true
				}
			}
		}
		false
	}
}

Gavin Wood's avatar
Gavin Wood committed
304
305
306
307
308
309
310
311
312
313
pub struct TestConfig;
impl Config for TestConfig {
	type Call = TestCall;
	type XcmSender = TestSendXcm;
	type AssetTransactor = TestAssetTransactor;
	type OriginConverter = TestOriginConverter;
	type IsReserve = TestIsReserve;
	type IsTeleporter = TestIsTeleporter;
	type LocationInverter = LocationInverter<TestAncestry>;
	type Barrier = TestBarrier;
314
	type Weigher = FixedWeightBounds<UnitWeightCost, TestCall, MaxInstructions>;
Gavin Wood's avatar
Gavin Wood committed
315
	type Trader = FixedRateOfFungible<WeightPrice, ()>;
Gavin Wood's avatar
Gavin Wood committed
316
	type ResponseHandler = TestResponseHandler;
317
318
	type AssetTrap = TestAssetTrap;
	type AssetClaims = TestAssetTrap;
Gavin Wood's avatar
Gavin Wood committed
319
}