tests.rs 12.6 KB
Newer Older
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/>.

17
use crate::{mock::*, AssetTraps, QueryStatus};
18
19
use frame_support::{assert_noop, assert_ok, traits::Currency};
use polkadot_parachain::primitives::{AccountIdConversion, Id as ParaId};
20
use sp_runtime::traits::{BlakeTwo256, Hash};
Gavin Wood's avatar
Gavin Wood committed
21
use std::convert::TryInto;
22
use xcm::{latest::prelude::*, VersionedMultiAssets, VersionedXcm};
23
use xcm_executor::XcmExecutor;
24
25
26
27
28
29
30

const ALICE: AccountId = AccountId::new([0u8; 32]);
const BOB: AccountId = AccountId::new([1u8; 32]);
const PARA_ID: u32 = 2000;
const INITIAL_BALANCE: u128 = 100;
const SEND_AMOUNT: u128 = 10;

31
32
33
34
35
36
37
38
39
40
41
42
#[test]
fn report_outcome_notify_works() {
	let balances =
		vec![(ALICE, INITIAL_BALANCE), (ParaId::from(PARA_ID).into_account(), INITIAL_BALANCE)];
	let sender = AccountId32 { network: AnyNetwork::get(), id: ALICE.into() }.into();
	let mut message = Xcm(vec![TransferAsset {
		assets: (Here, SEND_AMOUNT).into(),
		beneficiary: sender.clone(),
	}]);
	let call = pallet_test_notifier::Call::notification_received(0, Default::default());
	let notify = Call::TestNotifier(call);
	new_test_ext_with_balances(balances).execute_with(|| {
43
44
		XcmPallet::report_outcome_notify(&mut message, Parachain(PARA_ID).into(), notify, 100)
			.unwrap();
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
		assert_eq!(
			message,
			Xcm(vec![
				SetAppendix(Xcm(vec![ReportError {
					query_id: 0,
					dest: Parent.into(),
					max_response_weight: 1_000_000
				},])),
				TransferAsset { assets: (Here, SEND_AMOUNT).into(), beneficiary: sender.clone() },
			])
		);
		let status = QueryStatus::Pending {
			responder: MultiLocation::from(Parachain(PARA_ID)).into(),
			maybe_notify: Some((4, 2)),
			timeout: 100,
		};
		assert_eq!(crate::Queries::<Test>::iter().collect::<Vec<_>>(), vec![(0, status)]);

		let r = XcmExecutor::<XcmConfig>::execute_xcm(
			Parachain(PARA_ID).into(),
			Xcm(vec![QueryResponse {
				query_id: 0,
				response: Response::ExecutionResult(Ok(())),
				max_weight: 1_000_000,
			}]),
			1_000_000_000,
		);
		assert_eq!(r, Outcome::Complete(1_000));
		assert_eq!(
			last_events(2),
			vec![
				Event::TestNotifier(pallet_test_notifier::Event::ResponseReceived(
					Parachain(PARA_ID).into(),
					0,
					Response::ExecutionResult(Ok(())),
				)),
				Event::XcmPallet(crate::Event::Notified(0, 4, 2)),
			]
		);
		assert_eq!(crate::Queries::<Test>::iter().collect::<Vec<_>>(), vec![]);
	});
}

#[test]
fn report_outcome_works() {
	let balances =
		vec![(ALICE, INITIAL_BALANCE), (ParaId::from(PARA_ID).into_account(), INITIAL_BALANCE)];
	let sender = AccountId32 { network: AnyNetwork::get(), id: ALICE.into() }.into();
	let mut message = Xcm(vec![TransferAsset {
		assets: (Here, SEND_AMOUNT).into(),
		beneficiary: sender.clone(),
	}]);
	new_test_ext_with_balances(balances).execute_with(|| {
98
		XcmPallet::report_outcome(&mut message, Parachain(PARA_ID).into(), 100).unwrap();
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
		assert_eq!(
			message,
			Xcm(vec![
				SetAppendix(Xcm(vec![ReportError {
					query_id: 0,
					dest: Parent.into(),
					max_response_weight: 0
				},])),
				TransferAsset { assets: (Here, SEND_AMOUNT).into(), beneficiary: sender.clone() },
			])
		);
		let status = QueryStatus::Pending {
			responder: MultiLocation::from(Parachain(PARA_ID)).into(),
			maybe_notify: None,
			timeout: 100,
		};
		assert_eq!(crate::Queries::<Test>::iter().collect::<Vec<_>>(), vec![(0, status)]);

		let r = XcmExecutor::<XcmConfig>::execute_xcm(
			Parachain(PARA_ID).into(),
			Xcm(vec![QueryResponse {
				query_id: 0,
				response: Response::ExecutionResult(Ok(())),
				max_weight: 0,
			}]),
			1_000_000_000,
		);
		assert_eq!(r, Outcome::Complete(1_000));
		assert_eq!(
			last_event(),
			Event::XcmPallet(crate::Event::ResponseReady(0, Response::ExecutionResult(Ok(())),))
		);

		let response = Some((Response::ExecutionResult(Ok(())), 1));
		assert_eq!(XcmPallet::take_response(0), response);
	});
}

137
138
139
140
141
142
143
144
145
/// Test sending an `XCM` message (`XCM::ReserveAssetDeposit`)
///
/// Asserts that the expected message is sent and the event is emitted
#[test]
fn send_works() {
	let balances =
		vec![(ALICE, INITIAL_BALANCE), (ParaId::from(PARA_ID).into_account(), INITIAL_BALANCE)];
	new_test_ext_with_balances(balances).execute_with(|| {
		let sender: MultiLocation =
Gavin Wood's avatar
Gavin Wood committed
146
			AccountId32 { network: AnyNetwork::get(), id: ALICE.into() }.into();
147
148
149
150
151
152
153
154
155
		let message = Xcm(vec![
			ReserveAssetDeposited((Parent, SEND_AMOUNT).into()),
			ClearOrigin,
			buy_execution((Parent, SEND_AMOUNT)),
			DepositAsset { assets: All.into(), max_assets: 1, beneficiary: sender.clone() },
		]);
		let versioned_dest = Box::new(RelayLocation::get().into());
		let versioned_message = Box::new(VersionedXcm::from(message.clone()));
		assert_ok!(XcmPallet::send(Origin::signed(ALICE), versioned_dest, versioned_message));
156
157
158
		assert_eq!(
			sent_xcm(),
			vec![(
159
				Here.into(),
160
161
162
163
164
				Xcm(Some(DescendOrigin(sender.clone().try_into().unwrap()))
					.into_iter()
					.chain(message.0.clone().into_iter())
					.collect())
			)],
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
		);
		assert_eq!(
			last_event(),
			Event::XcmPallet(crate::Event::Sent(sender, RelayLocation::get(), message))
		);
	});
}

/// Test that sending an `XCM` message fails when the `XcmRouter` blocks the
/// matching message format
///
/// Asserts that `send` fails with `Error::SendFailure`
#[test]
fn send_fails_when_xcm_router_blocks() {
	let balances =
		vec![(ALICE, INITIAL_BALANCE), (ParaId::from(PARA_ID).into_account(), INITIAL_BALANCE)];
	new_test_ext_with_balances(balances).execute_with(|| {
		let sender: MultiLocation =
			Junction::AccountId32 { network: AnyNetwork::get(), id: ALICE.into() }.into();
184
185
186
187
188
		let message = Xcm(vec![
			ReserveAssetDeposited((Parent, SEND_AMOUNT).into()),
			buy_execution((Parent, SEND_AMOUNT)),
			DepositAsset { assets: All.into(), max_assets: 1, beneficiary: sender.clone() },
		]);
189
190
191
		assert_noop!(
			XcmPallet::send(
				Origin::signed(ALICE),
192
193
				Box::new(MultiLocation::ancestor(8).into()),
				Box::new(VersionedXcm::from(message.clone())),
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
			),
			crate::Error::<Test>::SendFailure
		);
	});
}

/// Test `teleport_assets`
///
/// Asserts that the sender's balance is decreased as a result of execution of
/// local effects.
#[test]
fn teleport_assets_works() {
	let balances =
		vec![(ALICE, INITIAL_BALANCE), (ParaId::from(PARA_ID).into_account(), INITIAL_BALANCE)];
	new_test_ext_with_balances(balances).execute_with(|| {
		let weight = 2 * BaseXcmWeight::get();
		assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE);
		assert_ok!(XcmPallet::teleport_assets(
			Origin::signed(ALICE),
213
214
215
			Box::new(RelayLocation::get().into()),
			Box::new(AccountId32 { network: Any, id: BOB.into() }.into().into()),
			Box::new((Here, SEND_AMOUNT).into()),
Gavin Wood's avatar
Gavin Wood committed
216
			0,
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
		));
		assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE - SEND_AMOUNT);
		assert_eq!(
			last_event(),
			Event::XcmPallet(crate::Event::Attempted(Outcome::Complete(weight)))
		);
	});
}

/// Test `reserve_transfer_assets`
///
/// Asserts that the sender's balance is decreased and the beneficiary's balance
/// is increased. Verifies the correct message is sent and event is emitted.
#[test]
fn reserve_transfer_assets_works() {
	let balances =
		vec![(ALICE, INITIAL_BALANCE), (ParaId::from(PARA_ID).into_account(), INITIAL_BALANCE)];
	new_test_ext_with_balances(balances).execute_with(|| {
		let weight = BaseXcmWeight::get();
		let dest: MultiLocation =
			Junction::AccountId32 { network: NetworkId::Any, id: ALICE.into() }.into();
		assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE);
		assert_ok!(XcmPallet::reserve_transfer_assets(
			Origin::signed(ALICE),
241
242
243
			Box::new(Parachain(PARA_ID).into().into()),
			Box::new(dest.clone().into()),
			Box::new((Here, SEND_AMOUNT).into()),
Gavin Wood's avatar
Gavin Wood committed
244
			0,
245
246
247
248
249
250
251
252
253
254
		));
		// Alice spent amount
		assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE - SEND_AMOUNT);
		// Destination account (parachain account) has amount
		let para_acc: AccountId = ParaId::from(PARA_ID).into_account();
		assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE + SEND_AMOUNT);
		assert_eq!(
			sent_xcm(),
			vec![(
				Parachain(PARA_ID).into(),
255
256
257
258
259
260
				Xcm(vec![
					ReserveAssetDeposited((Parent, SEND_AMOUNT).into()),
					ClearOrigin,
					buy_execution((Parent, SEND_AMOUNT)),
					DepositAsset { assets: All.into(), max_assets: 1, beneficiary: dest },
				]),
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
			)]
		);
		assert_eq!(
			last_event(),
			Event::XcmPallet(crate::Event::Attempted(Outcome::Complete(weight)))
		);
	});
}

/// Test local execution of XCM
///
/// Asserts that the sender's balance is decreased and the beneficiary's balance
/// is increased. Verifies the expected event is emitted.
#[test]
fn execute_withdraw_to_deposit_works() {
	let balances =
		vec![(ALICE, INITIAL_BALANCE), (ParaId::from(PARA_ID).into_account(), INITIAL_BALANCE)];
	new_test_ext_with_balances(balances).execute_with(|| {
		let weight = 3 * BaseXcmWeight::get();
		let dest: MultiLocation =
			Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() }.into();
		assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE);
		assert_ok!(XcmPallet::execute(
			Origin::signed(ALICE),
285
286
287
288
289
			Box::new(VersionedXcm::from(Xcm(vec![
				WithdrawAsset((Here, SEND_AMOUNT).into()),
				buy_execution((Here, SEND_AMOUNT)),
				DepositAsset { assets: All.into(), max_assets: 1, beneficiary: dest },
			]))),
290
291
292
293
294
295
296
297
298
299
			weight
		));
		assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE - SEND_AMOUNT);
		assert_eq!(Balances::total_balance(&BOB), SEND_AMOUNT);
		assert_eq!(
			last_event(),
			Event::XcmPallet(crate::Event::Attempted(Outcome::Complete(weight)))
		);
	});
}
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

/// Test drop/claim assets.
#[test]
fn trapped_assets_can_be_claimed() {
	let balances = vec![(ALICE, INITIAL_BALANCE), (BOB, INITIAL_BALANCE)];
	new_test_ext_with_balances(balances).execute_with(|| {
		let weight = 6 * BaseXcmWeight::get();
		let dest: MultiLocation =
			Junction::AccountId32 { network: NetworkId::Any, id: BOB.into() }.into();

		assert_ok!(XcmPallet::execute(
			Origin::signed(ALICE),
			Box::new(VersionedXcm::from(Xcm(vec![
				WithdrawAsset((Here, SEND_AMOUNT).into()),
				buy_execution((Here, SEND_AMOUNT)),
				// Don't propagated the error into the result.
				SetErrorHandler(Xcm(vec![ClearError])),
				// This will make an error.
				Trap(0),
				// This would succeed, but we never get to it.
				DepositAsset { assets: All.into(), max_assets: 1, beneficiary: dest.clone() },
			]))),
			weight
		));
		let source: MultiLocation =
			Junction::AccountId32 { network: NetworkId::Any, id: ALICE.into() }.into();
		let trapped = AssetTraps::<Test>::iter().collect::<Vec<_>>();
		let vma = VersionedMultiAssets::from(MultiAssets::from((Here, SEND_AMOUNT)));
		let hash = BlakeTwo256::hash_of(&(source.clone(), vma.clone()));
		assert_eq!(
			last_events(2),
			vec![
				Event::XcmPallet(crate::Event::AssetsTrapped(hash.clone(), source, vma)),
				Event::XcmPallet(crate::Event::Attempted(Outcome::Complete(
					5 * BaseXcmWeight::get()
				)))
			]
		);
		assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE - SEND_AMOUNT);
		assert_eq!(Balances::total_balance(&BOB), INITIAL_BALANCE);

		let expected = vec![(hash, 1u32)];
		assert_eq!(trapped, expected);

		let weight = 3 * BaseXcmWeight::get();
		assert_ok!(XcmPallet::execute(
			Origin::signed(ALICE),
			Box::new(VersionedXcm::from(Xcm(vec![
				ClaimAsset { assets: (Here, SEND_AMOUNT).into(), ticket: Here.into() },
				buy_execution((Here, SEND_AMOUNT)),
				DepositAsset { assets: All.into(), max_assets: 1, beneficiary: dest.clone() },
			]))),
			weight
		));

		assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE - SEND_AMOUNT);
		assert_eq!(Balances::total_balance(&BOB), INITIAL_BALANCE + SEND_AMOUNT);
		assert_eq!(AssetTraps::<Test>::iter().collect::<Vec<_>>(), vec![]);

		let weight = 3 * BaseXcmWeight::get();
		assert_ok!(XcmPallet::execute(
			Origin::signed(ALICE),
			Box::new(VersionedXcm::from(Xcm(vec![
				ClaimAsset { assets: (Here, SEND_AMOUNT).into(), ticket: Here.into() },
				buy_execution((Here, SEND_AMOUNT)),
				DepositAsset { assets: All.into(), max_assets: 1, beneficiary: dest },
			]))),
			weight
		));
		assert_eq!(
			last_event(),
			Event::XcmPallet(crate::Event::Attempted(Outcome::Incomplete(
				BaseXcmWeight::get(),
				XcmError::UnknownClaim
			)))
		);
	});
}