1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

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

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

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

            
17
use super::*;
18
use frame_support::{
19
	assert_noop,
20
	dispatch::{Pays, PostDispatchInfo},
21
	traits::ConstU32,
22
	weights::Weight,
23
	BoundedVec,
24
};
25
use sp_runtime::{DispatchError, DispatchErrorWithPostInfo};
26
use xcm_primitives::{
27
	EthereumXcmFee, EthereumXcmTransaction, EthereumXcmTransactionV1, ManualEthereumXcmFee,
28
};
29

            
30
// 	pragma solidity ^0.6.6;
31
// 	contract Test {
32
// 		function foo() external pure returns (bool) {
33
// 			return true;
34
// 		}
35
// 		function bar() external pure {
36
// 			require(false, "error_msg");
37
// 		}
38
// 	}
39
const CONTRACT: &str = "608060405234801561001057600080fd5b50610113806100206000396000f3fe6080604052\
40
						348015600f57600080fd5b506004361060325760003560e01c8063c2985578146037578063\
41
						febb0f7e146057575b600080fd5b603d605f565b6040518082151515158152602001915050\
42
						60405180910390f35b605d6068565b005b60006001905090565b600060db576040517f08c3\
43
						79a00000000000000000000000000000000000000000000000000000000081526004018080\
44
						602001828103825260098152602001807f6572726f725f6d73670000000000000000000000\
45
						00000000000000000000000081525060200191505060405180910390fd5b56fea264697066\
46
						7358221220fde68a3968e0e99b16fabf9b2997a78218b32214031f8e07e2c502daf603a69e\
47
						64736f6c63430006060033";
48

            
49
8
fn xcm_evm_transfer_legacy_transaction(destination: H160, value: U256) -> EthereumXcmTransaction {
50
8
	EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
51
8
		fee_payment: EthereumXcmFee::Auto,
52
8
		gas_limit: U256::from(0x100000),
53
8
		action: ethereum::TransactionAction::Call(destination),
54
8
		value,
55
8
		input:
56
8
			BoundedVec::<u8, ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>>::try_from(
57
8
				vec![],
58
8
			)
59
8
			.unwrap(),
60
8
		access_list: None,
61
8
	})
62
8
}
63

            
64
2
fn xcm_evm_call_eip_legacy_transaction(
65
2
	destination: H160,
66
2
	input: Vec<u8>,
67
2
) -> EthereumXcmTransaction {
68
2
	EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
69
2
		fee_payment: EthereumXcmFee::Manual(ManualEthereumXcmFee {
70
2
			gas_price: Some(U256::from(1)),
71
2
			max_fee_per_gas: None,
72
2
		}),
73
2
		gas_limit: U256::from(0x100000),
74
2
		action: ethereum::TransactionAction::Call(destination),
75
2
		value: U256::zero(),
76
2
		input:
77
2
			BoundedVec::<u8, ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>>::try_from(
78
2
				input,
79
2
			)
80
2
			.unwrap(),
81
2
		access_list: None,
82
2
	})
83
2
}
84

            
85
1
fn xcm_erc20_creation_legacy_transaction() -> EthereumXcmTransaction {
86
1
	EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
87
1
		fee_payment: EthereumXcmFee::Manual(ManualEthereumXcmFee {
88
1
			gas_price: Some(U256::from(1)),
89
1
			max_fee_per_gas: None,
90
1
		}),
91
1
		gas_limit: U256::from(0x100000),
92
1
		action: ethereum::TransactionAction::Create,
93
1
		value: U256::zero(),
94
1
		input:
95
1
			BoundedVec::<u8, ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>>::try_from(
96
1
				hex::decode(CONTRACT).unwrap(),
97
1
			)
98
1
			.unwrap(),
99
1
		access_list: None,
100
1
	})
101
1
}
102

            
103
#[test]
104
1
fn test_transact_xcm_evm_transfer() {
105
1
	let (pairs, mut ext) = new_test_ext(2);
106
1
	let alice = &pairs[0];
107
1
	let bob = &pairs[1];
108
1

            
109
1
	ext.execute_with(|| {
110
1
		let balances_before = System::account(&bob.account_id);
111
1
		EthereumXcm::transact(
112
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
113
1
			xcm_evm_transfer_legacy_transaction(bob.address, U256::from(100)),
114
1
		)
115
1
		.expect("Failed to execute transaction");
116
1

            
117
1
		assert_eq!(
118
1
			System::account(&bob.account_id).data.free,
119
1
			balances_before.data.free + 100
120
1
		);
121
1
	});
122
1
}
123

            
124
#[test]
125
1
fn test_transact_xcm_create() {
126
1
	let (pairs, mut ext) = new_test_ext(1);
127
1
	let alice = &pairs[0];
128
1

            
129
1
	ext.execute_with(|| {
130
1
		assert_noop!(
131
1
			EthereumXcm::transact(
132
1
				RawOrigin::XcmEthereumTransaction(alice.address).into(),
133
1
				xcm_erc20_creation_legacy_transaction()
134
1
			),
135
1
			DispatchErrorWithPostInfo {
136
1
				post_info: PostDispatchInfo {
137
1
					actual_weight: Some(Weight::zero()),
138
1
					pays_fee: Pays::Yes,
139
1
				},
140
1
				error: DispatchError::Other("Cannot convert xcm payload to known type"),
141
1
			}
142
1
		);
143
1
	});
144
1
}
145

            
146
#[test]
147
1
fn test_transact_xcm_evm_call_works() {
148
1
	let (pairs, mut ext) = new_test_ext(2);
149
1
	let alice = &pairs[0];
150
1
	let bob = &pairs[1];
151
1

            
152
1
	ext.execute_with(|| {
153
1
		let t = LegacyUnsignedTransaction {
154
1
			nonce: U256::zero(),
155
1
			gas_price: U256::from(1),
156
1
			gas_limit: U256::from(0x100000),
157
1
			action: ethereum::TransactionAction::Create,
158
1
			value: U256::zero(),
159
1
			input: hex::decode(CONTRACT).unwrap(),
160
1
		}
161
1
		.sign(&alice.private_key);
162
1
		assert_ok!(Ethereum::execute(alice.address, &t, None, None));
163

            
164
1
		let contract_address = hex::decode("32dcab0ef3fb2de2fce1d2e0799d36239671f04a").unwrap();
165
1
		let foo = hex::decode("c2985578").unwrap();
166
1
		let bar = hex::decode("febb0f7e").unwrap();
167
1

            
168
1
		let _ = EthereumXcm::transact(
169
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
170
1
			xcm_evm_call_eip_legacy_transaction(H160::from_slice(&contract_address), foo),
171
1
		)
172
1
		.expect("Failed to call `foo`");
173
1

            
174
1
		// Evm call failing still succesfully dispatched
175
1
		let _ = EthereumXcm::transact(
176
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
177
1
			xcm_evm_call_eip_legacy_transaction(H160::from_slice(&contract_address), bar),
178
1
		)
179
1
		.expect("Failed to call `bar`");
180
1

            
181
1
		assert!(pallet_ethereum::Pending::<Test>::count() == 2);
182

            
183
		// Transaction is in Pending storage, with nonce 0 and status 1 (evm succeed).
184
1
		let (transaction_0, _, receipt_0) = &pallet_ethereum::Pending::<Test>::get(0).unwrap();
185
1
		match (transaction_0, receipt_0) {
186
1
			(&crate::Transaction::Legacy(ref t), &crate::Receipt::Legacy(ref r)) => {
187
1
				assert!(t.nonce == U256::from(0u8));
188
1
				assert!(r.status_code == 1u8);
189
			}
190
			_ => unreachable!(),
191
		}
192

            
193
		// Transaction is in Pending storage, with nonce 1 and status 0 (evm failed).
194
1
		let (transaction_1, _, receipt_1) = &pallet_ethereum::Pending::<Test>::get(1).unwrap();
195
1
		match (transaction_1, receipt_1) {
196
1
			(&crate::Transaction::Legacy(ref t), &crate::Receipt::Legacy(ref r)) => {
197
1
				assert!(t.nonce == U256::from(1u8));
198
1
				assert!(r.status_code == 0u8);
199
			}
200
			_ => unreachable!(),
201
		}
202
1
	});
203
1
}
204

            
205
#[test]
206
1
fn test_transact_xcm_validation_works() {
207
1
	let (pairs, mut ext) = new_test_ext(2);
208
1
	let alice = &pairs[0];
209
1
	let bob = &pairs[1];
210
1

            
211
1
	ext.execute_with(|| {
212
1
		// Not enough gas limit to cover the transaction cost.
213
1
		assert_noop!(
214
1
			EthereumXcm::transact(
215
1
				RawOrigin::XcmEthereumTransaction(alice.address).into(),
216
1
				EthereumXcmTransaction::V1(EthereumXcmTransactionV1 {
217
1
					fee_payment: EthereumXcmFee::Manual(xcm_primitives::ManualEthereumXcmFee {
218
1
						gas_price: Some(U256::from(0)),
219
1
						max_fee_per_gas: None,
220
1
					}),
221
1
					gas_limit: U256::from(0x5207),
222
1
					action: ethereum::TransactionAction::Call(bob.address),
223
1
					value: U256::from(1),
224
1
					input: BoundedVec::<
225
1
						u8,
226
1
						ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>,
227
1
					>::try_from(vec![])
228
1
					.unwrap(),
229
1
					access_list: None,
230
1
				}),
231
1
			),
232
1
			DispatchErrorWithPostInfo {
233
1
				post_info: PostDispatchInfo {
234
1
					actual_weight: Some(Weight::zero()),
235
1
					pays_fee: Pays::Yes,
236
1
				},
237
1
				error: DispatchError::Other("Failed to validate ethereum transaction"),
238
1
			}
239
1
		);
240
1
	});
241
1
}
242

            
243
#[test]
244
1
fn test_ensure_transact_xcm_trough_no_proxy_error() {
245
1
	let (pairs, mut ext) = new_test_ext(2);
246
1
	let alice = &pairs[0];
247
1
	let bob = &pairs[1];
248
1

            
249
1
	ext.execute_with(|| {
250
1
		let r = EthereumXcm::transact_through_proxy(
251
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
252
1
			bob.address,
253
1
			xcm_evm_transfer_legacy_transaction(bob.address, U256::from(100)),
254
1
		);
255
1
		assert!(r.is_err());
256
1
		assert_eq!(
257
1
			r.unwrap_err().error,
258
1
			sp_runtime::DispatchError::Other("proxy error: expected `ProxyType::Any`"),
259
1
		);
260
1
	});
261
1
}
262

            
263
#[test]
264
1
fn test_ensure_transact_xcm_trough_proxy_error() {
265
1
	let (pairs, mut ext) = new_test_ext(2);
266
1
	let alice = &pairs[0];
267
1
	let bob = &pairs[1];
268
1

            
269
1
	ext.execute_with(|| {
270
1
		let _ = Proxy::add_proxy_delegate(
271
1
			&bob.account_id,
272
1
			alice.account_id.clone(),
273
1
			ProxyType::NotAllowed,
274
1
			0,
275
1
		);
276
1
		let r = EthereumXcm::transact_through_proxy(
277
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
278
1
			bob.address,
279
1
			xcm_evm_transfer_legacy_transaction(bob.address, U256::from(100)),
280
1
		);
281
1
		assert!(r.is_err());
282
1
		assert_eq!(
283
1
			r.unwrap_err().error,
284
1
			sp_runtime::DispatchError::Other("proxy error: expected `ProxyType::Any`"),
285
1
		);
286
1
	});
287
1
}
288

            
289
#[test]
290
1
fn test_ensure_transact_xcm_trough_proxy_ok() {
291
1
	let (pairs, mut ext) = new_test_ext(3);
292
1
	let alice = &pairs[0];
293
1
	let bob = &pairs[1];
294
1
	let charlie = &pairs[2];
295
1

            
296
1
	let allowed_proxies = vec![ProxyType::Any];
297

            
298
1
	for proxy in allowed_proxies.into_iter() {
299
1
		ext.execute_with(|| {
300
1
			let _ = Proxy::add_proxy_delegate(&bob.account_id, alice.account_id.clone(), proxy, 0);
301
1
			let alice_before = System::account(&alice.account_id);
302
1
			let bob_before = System::account(&bob.account_id);
303
1
			let charlie_before = System::account(&charlie.account_id);
304
1

            
305
1
			let r = EthereumXcm::transact_through_proxy(
306
1
				RawOrigin::XcmEthereumTransaction(alice.address).into(),
307
1
				bob.address,
308
1
				xcm_evm_transfer_legacy_transaction(charlie.address, U256::from(100)),
309
1
			);
310
1
			// Transact succeeded
311
1
			assert!(r.is_ok());
312

            
313
1
			let alice_after = System::account(&alice.account_id);
314
1
			let bob_after = System::account(&bob.account_id);
315
1
			let charlie_after = System::account(&charlie.account_id);
316
1

            
317
1
			// Alice remains unchanged
318
1
			assert_eq!(alice_before, alice_after);
319

            
320
			// Bob nonce was increased
321
1
			assert_eq!(bob_after.nonce, bob_before.nonce + 1);
322

            
323
			// Bob sent some funds without paying any fees
324
1
			assert_eq!(bob_after.data.free, bob_before.data.free - 100);
325

            
326
			// Charlie receive some funds
327
1
			assert_eq!(charlie_after.data.free, charlie_before.data.free + 100);
328

            
329
			// Clear proxy
330
			let _ =
331
1
				Proxy::remove_proxy_delegate(&bob.account_id, alice.account_id.clone(), proxy, 0);
332
1
		});
333
1
	}
334
1
}
335

            
336
#[test]
337
1
fn test_global_nonce_incr() {
338
1
	let (pairs, mut ext) = new_test_ext(3);
339
1
	let alice = &pairs[0];
340
1
	let bob = &pairs[1];
341
1
	let charlie = &pairs[2];
342
1

            
343
1
	ext.execute_with(|| {
344
1
		assert_eq!(EthereumXcm::nonce(), U256::zero());
345

            
346
1
		EthereumXcm::transact(
347
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
348
1
			xcm_evm_transfer_legacy_transaction(charlie.address, U256::one()),
349
1
		)
350
1
		.expect("Failed to execute transaction from Alice to Charlie");
351
1

            
352
1
		assert_eq!(EthereumXcm::nonce(), U256::one());
353

            
354
1
		EthereumXcm::transact(
355
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
356
1
			xcm_evm_transfer_legacy_transaction(charlie.address, U256::one()),
357
1
		)
358
1
		.expect("Failed to execute transaction from Bob to Charlie");
359
1

            
360
1
		assert_eq!(EthereumXcm::nonce(), U256::from(2));
361
1
	});
362
1
}
363

            
364
#[test]
365
1
fn test_global_nonce_not_incr() {
366
1
	let (pairs, mut ext) = new_test_ext(2);
367
1
	let alice = &pairs[0];
368
1
	let bob = &pairs[1];
369
1

            
370
1
	ext.execute_with(|| {
371
1
		assert_eq!(EthereumXcm::nonce(), U256::zero());
372

            
373
1
		let invalid_transaction_cost =
374
1
			EthereumXcmTransaction::V1(
375
1
				EthereumXcmTransactionV1 {
376
1
					fee_payment: EthereumXcmFee::Auto,
377
1
					gas_limit: U256::one(),
378
1
					action: ethereum::TransactionAction::Call(bob.address),
379
1
					value: U256::one(),
380
1
					input: BoundedVec::<
381
1
						u8,
382
1
						ConstU32<{ xcm_primitives::MAX_ETHEREUM_XCM_INPUT_SIZE }>,
383
1
					>::try_from(vec![])
384
1
					.unwrap(),
385
1
					access_list: None,
386
1
				},
387
1
			);
388
1

            
389
1
		EthereumXcm::transact(
390
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
391
1
			invalid_transaction_cost,
392
1
		)
393
1
		.expect_err("Failed to execute transaction from Alice to Bob");
394
1

            
395
1
		assert_eq!(EthereumXcm::nonce(), U256::zero());
396
1
	});
397
1
}
398

            
399
#[test]
400
1
fn test_transaction_hash_collision() {
401
1
	let (pairs, mut ext) = new_test_ext(3);
402
1
	let alice = &pairs[0];
403
1
	let bob = &pairs[1];
404
1
	let charlie = &pairs[2];
405
1

            
406
1
	ext.execute_with(|| {
407
1
		EthereumXcm::transact(
408
1
			RawOrigin::XcmEthereumTransaction(alice.address).into(),
409
1
			xcm_evm_transfer_legacy_transaction(charlie.address, U256::one()),
410
1
		)
411
1
		.expect("Failed to execute transaction from Alice to Charlie");
412
1

            
413
1
		EthereumXcm::transact(
414
1
			RawOrigin::XcmEthereumTransaction(bob.address).into(),
415
1
			xcm_evm_transfer_legacy_transaction(charlie.address, U256::one()),
416
1
		)
417
1
		.expect("Failed to execute transaction from Bob to Charlie");
418
1

            
419
1
		let mut hashes = pallet_ethereum::Pending::<Test>::iter_values()
420
2
			.map(|(tx, _, _)| tx.hash())
421
1
			.collect::<Vec<ethereum_types::H256>>();
422
1

            
423
1
		// Holds two transactions hashes
424
1
		assert_eq!(hashes.len(), 2);
425

            
426
1
		hashes.dedup();
427
1

            
428
1
		// Still holds two transactions hashes after removing potential consecutive repeated values.
429
1
		assert_eq!(hashes.len(), 2);
430
1
	});
431
1
}