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
// Copyright 2019-2022 PureStake Inc.
// This file is part of Moonbeam.

// Moonbeam 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.

// Moonbeam 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 Moonbeam.  If not, see <http://www.gnu.org/licenses/>.

use ethereum::{
	AccessList, AccessListItem, EIP1559Transaction, EIP2930Transaction, LegacyTransaction,
	TransactionAction, TransactionSignature, TransactionV2,
};
use ethereum_types::{H160, H256, U256};
use frame_support::{traits::ConstU32, BoundedVec};
use parity_scale_codec::{Decode, Encode};
use scale_info::TypeInfo;
use sp_std::vec::Vec;

// polkadot/blob/19f6665a6162e68cd2651f5fe3615d6676821f90/xcm/src/v3/mod.rs#L1193
// Defensively we increase this value to allow UMP fragments through xcm-transactor to prepare our
// runtime for a relay upgrade where the xcm instruction weights are not ZERO hardcoded. If that
// happens stuff will break in our side.
// Rationale behind the value: e.g. staking unbond will go above 64kb and thus
// required_weight_at_most must be below overall weight but still above whatever value we decide to
// set. For this reason we set here a value that makes sense for the overall weight.
pub const DEFAULT_PROOF_SIZE: u64 = 256 * 1024;

/// Max. allowed size of 65_536 bytes.
pub const MAX_ETHEREUM_XCM_INPUT_SIZE: u32 = 2u32.pow(16);

/// Ensure that a proxy between `delegator` and `delegatee` exists in order to deny or grant
/// permission to do xcm-transact to `transact_through_proxy`.
pub trait EnsureProxy<AccountId> {
	fn ensure_ok(delegator: AccountId, delegatee: AccountId) -> Result<(), &'static str>;
}

#[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, TypeInfo)]
/// Manually sets a gas fee.
pub struct ManualEthereumXcmFee {
	/// Legacy or Eip-2930, all fee will be used.
	pub gas_price: Option<U256>,
	/// Eip-1559, must be at least the on-chain base fee at the time of applying the xcm
	/// and will use up to the defined value.
	pub max_fee_per_gas: Option<U256>,
}

/// Xcm transact's Ethereum transaction configurable fee.
#[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, TypeInfo)]
pub enum EthereumXcmFee {
	/// Manually set gas fee.
	Manual(ManualEthereumXcmFee),
	/// Use the on-chain base fee at the time of processing the xcm.
	Auto,
}

/// Xcm transact's Ethereum transaction.
#[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, TypeInfo)]
pub enum EthereumXcmTransaction {
	V1(EthereumXcmTransactionV1),
	V2(EthereumXcmTransactionV2),
}

/// Value for `r` and `s` for the invalid signature included in Xcm transact's Ethereum transaction.
pub fn rs_id() -> H256 {
	H256::from_low_u64_be(1u64)
}

#[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, TypeInfo)]
pub struct EthereumXcmTransactionV1 {
	/// Gas limit to be consumed by EVM execution.
	pub gas_limit: U256,
	/// Fee configuration of choice.
	pub fee_payment: EthereumXcmFee,
	/// Either a Call (the callee, account or contract address) or Create (unsupported for v1).
	pub action: TransactionAction,
	/// Value to be transfered.
	pub value: U256,
	/// Input data for a contract call.
	pub input: BoundedVec<u8, ConstU32<MAX_ETHEREUM_XCM_INPUT_SIZE>>,
	/// Map of addresses to be pre-paid to warm storage.
	pub access_list: Option<Vec<(H160, Vec<H256>)>>,
}

#[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, TypeInfo)]
pub struct EthereumXcmTransactionV2 {
	/// Gas limit to be consumed by EVM execution.
	pub gas_limit: U256,
	/// Either a Call (the callee, account or contract address) or Create).
	pub action: TransactionAction,
	/// Value to be transfered.
	pub value: U256,
	/// Input data for a contract call. Max. size 65_536 bytes.
	pub input: BoundedVec<u8, ConstU32<MAX_ETHEREUM_XCM_INPUT_SIZE>>,
	/// Map of addresses to be pre-paid to warm storage.
	pub access_list: Option<Vec<(H160, Vec<H256>)>>,
}

pub trait XcmToEthereum {
	fn into_transaction_v2(
		&self,
		nonce: U256,
		chain_id: u64,
		allow_create: bool,
	) -> Option<TransactionV2>;
}

impl XcmToEthereum for EthereumXcmTransaction {
	fn into_transaction_v2(
		&self,
		nonce: U256,
		chain_id: u64,
		allow_create: bool,
	) -> Option<TransactionV2> {
		match self {
			EthereumXcmTransaction::V1(v1_tx) => {
				v1_tx.into_transaction_v2(nonce, chain_id, allow_create)
			}
			EthereumXcmTransaction::V2(v2_tx) => {
				v2_tx.into_transaction_v2(nonce, chain_id, allow_create)
			}
		}
	}
}

impl XcmToEthereum for EthereumXcmTransactionV1 {
	fn into_transaction_v2(&self, nonce: U256, chain_id: u64, _: bool) -> Option<TransactionV2> {
		// We dont support creates for now
		if self.action == TransactionAction::Create {
			return None;
		}
		let from_tuple_to_access_list = |t: &Vec<(H160, Vec<H256>)>| -> AccessList {
			t.iter()
				.map(|item| AccessListItem {
					address: item.0.clone(),
					storage_keys: item.1.clone(),
				})
				.collect::<Vec<AccessListItem>>()
		};

		let (gas_price, max_fee) = match &self.fee_payment {
			EthereumXcmFee::Manual(fee_config) => {
				(fee_config.gas_price, fee_config.max_fee_per_gas)
			}
			EthereumXcmFee::Auto => (None, Some(U256::zero())),
		};
		match (gas_price, max_fee) {
			(Some(gas_price), None) => {
				// Legacy or Eip-2930
				if let Some(ref access_list) = self.access_list {
					// Eip-2930
					Some(TransactionV2::EIP2930(EIP2930Transaction {
						chain_id,
						nonce,
						gas_price,
						gas_limit: self.gas_limit,
						action: self.action,
						value: self.value,
						input: self.input.to_vec(),
						access_list: from_tuple_to_access_list(access_list),
						odd_y_parity: true,
						r: rs_id(),
						s: rs_id(),
					}))
				} else {
					// Legacy
					Some(TransactionV2::Legacy(LegacyTransaction {
						nonce,
						gas_price,
						gas_limit: self.gas_limit,
						action: self.action,
						value: self.value,
						input: self.input.to_vec(),
						signature: TransactionSignature::new(42, rs_id(), rs_id())?,
					}))
				}
			}
			(None, Some(max_fee)) => {
				// Eip-1559
				Some(TransactionV2::EIP1559(EIP1559Transaction {
					chain_id,
					nonce,
					max_fee_per_gas: max_fee,
					max_priority_fee_per_gas: U256::zero(),
					gas_limit: self.gas_limit,
					action: self.action,
					value: self.value,
					input: self.input.to_vec(),
					access_list: if let Some(ref access_list) = self.access_list {
						from_tuple_to_access_list(access_list)
					} else {
						Vec::new()
					},
					odd_y_parity: true,
					r: rs_id(),
					s: rs_id(),
				}))
			}
			_ => return None,
		}
	}
}

impl XcmToEthereum for EthereumXcmTransactionV2 {
	fn into_transaction_v2(
		&self,
		nonce: U256,
		chain_id: u64,
		allow_create: bool,
	) -> Option<TransactionV2> {
		if !allow_create && self.action == TransactionAction::Create {
			// Create not allowed
			return None;
		}
		let from_tuple_to_access_list = |t: &Vec<(H160, Vec<H256>)>| -> AccessList {
			t.iter()
				.map(|item| AccessListItem {
					address: item.0.clone(),
					storage_keys: item.1.clone(),
				})
				.collect::<Vec<AccessListItem>>()
		};
		// Eip-1559
		Some(TransactionV2::EIP1559(EIP1559Transaction {
			chain_id,
			nonce,
			max_fee_per_gas: U256::zero(),
			max_priority_fee_per_gas: U256::zero(),
			gas_limit: self.gas_limit,
			action: self.action,
			value: self.value,
			input: self.input.to_vec(),
			access_list: if let Some(ref access_list) = self.access_list {
				from_tuple_to_access_list(access_list)
			} else {
				Vec::new()
			},
			odd_y_parity: true,
			r: rs_id(),
			s: rs_id(),
		}))
	}
}

/// The EthereumXcmTracingStatus storage key.
pub const ETHEREUM_XCM_TRACING_STORAGE_KEY: &[u8] = b":ethereum_xcm_tracing";

/// The current EthereumXcmTransaction trace status.
#[derive(Clone, Debug, Encode, Decode, PartialEq, Eq)]
pub enum EthereumXcmTracingStatus {
	/// A full block trace.
	Block,
	/// A single transaction.
	Transaction(H256),
	/// Exit signal.
	TransactionExited,
}

#[cfg(test)]
mod tests {
	use super::*;
	#[test]
	fn test_into_ethereum_tx_with_auto_fee_v1() {
		let xcm_transaction = EthereumXcmTransactionV1 {
			gas_limit: U256::one(),
			fee_payment: EthereumXcmFee::Auto,
			action: TransactionAction::Call(H160::default()),
			value: U256::zero(),
			input: BoundedVec::<u8, ConstU32<MAX_ETHEREUM_XCM_INPUT_SIZE>>::try_from(vec![1u8])
				.unwrap(),
			access_list: None,
		};
		let nonce = U256::zero();
		let expected_tx = Some(TransactionV2::EIP1559(EIP1559Transaction {
			chain_id: 111,
			nonce,
			max_fee_per_gas: U256::zero(),
			max_priority_fee_per_gas: U256::zero(),
			gas_limit: U256::one(),
			action: TransactionAction::Call(H160::default()),
			value: U256::zero(),
			input: vec![1u8],
			access_list: vec![],
			odd_y_parity: true,
			r: H256::from_low_u64_be(1u64),
			s: H256::from_low_u64_be(1u64),
		}));

		assert_eq!(
			xcm_transaction.into_transaction_v2(nonce, 111, false),
			expected_tx
		);
	}

	#[test]
	fn test_legacy_v1() {
		let xcm_transaction = EthereumXcmTransactionV1 {
			gas_limit: U256::one(),
			fee_payment: EthereumXcmFee::Manual(ManualEthereumXcmFee {
				gas_price: Some(U256::zero()),
				max_fee_per_gas: None,
			}),
			action: TransactionAction::Call(H160::default()),
			value: U256::zero(),
			input: BoundedVec::<u8, ConstU32<MAX_ETHEREUM_XCM_INPUT_SIZE>>::try_from(vec![1u8])
				.unwrap(),
			access_list: None,
		};
		let nonce = U256::zero();
		let expected_tx = Some(TransactionV2::Legacy(LegacyTransaction {
			nonce,
			gas_price: U256::zero(),
			gas_limit: U256::one(),
			action: TransactionAction::Call(H160::default()),
			value: U256::zero(),
			input: vec![1u8],
			signature: TransactionSignature::new(42, rs_id(), rs_id()).unwrap(),
		}));

		assert_eq!(
			xcm_transaction.into_transaction_v2(nonce, 111, false),
			expected_tx
		);
	}
	#[test]
	fn test_eip_2930_v1() {
		let access_list = Some(vec![(H160::default(), vec![H256::default()])]);
		let from_tuple_to_access_list = |t: &Vec<(H160, Vec<H256>)>| -> AccessList {
			t.iter()
				.map(|item| AccessListItem {
					address: item.0.clone(),
					storage_keys: item.1.clone(),
				})
				.collect::<Vec<AccessListItem>>()
		};

		let xcm_transaction = EthereumXcmTransactionV1 {
			gas_limit: U256::one(),
			fee_payment: EthereumXcmFee::Manual(ManualEthereumXcmFee {
				gas_price: Some(U256::zero()),
				max_fee_per_gas: None,
			}),
			action: TransactionAction::Call(H160::default()),
			value: U256::zero(),
			input: BoundedVec::<u8, ConstU32<MAX_ETHEREUM_XCM_INPUT_SIZE>>::try_from(vec![1u8])
				.unwrap(),
			access_list: access_list.clone(),
		};

		let nonce = U256::zero();
		let expected_tx = Some(TransactionV2::EIP2930(EIP2930Transaction {
			chain_id: 111,
			nonce,
			gas_price: U256::zero(),
			gas_limit: U256::one(),
			action: TransactionAction::Call(H160::default()),
			value: U256::zero(),
			input: vec![1u8],
			access_list: from_tuple_to_access_list(&access_list.unwrap()),
			odd_y_parity: true,
			r: H256::from_low_u64_be(1u64),
			s: H256::from_low_u64_be(1u64),
		}));

		assert_eq!(
			xcm_transaction.into_transaction_v2(nonce, 111, false),
			expected_tx
		);
	}

	#[test]
	fn test_eip1559_v2() {
		let xcm_transaction = EthereumXcmTransactionV2 {
			gas_limit: U256::one(),
			action: TransactionAction::Call(H160::default()),
			value: U256::zero(),
			input: BoundedVec::<u8, ConstU32<MAX_ETHEREUM_XCM_INPUT_SIZE>>::try_from(vec![1u8])
				.unwrap(),
			access_list: None,
		};
		let nonce = U256::zero();
		let expected_tx = Some(TransactionV2::EIP1559(EIP1559Transaction {
			chain_id: 111,
			nonce,
			max_fee_per_gas: U256::zero(),
			max_priority_fee_per_gas: U256::zero(),
			gas_limit: U256::one(),
			action: TransactionAction::Call(H160::default()),
			value: U256::zero(),
			input: vec![1u8],
			access_list: vec![],
			odd_y_parity: true,
			r: H256::from_low_u64_be(1u64),
			s: H256::from_low_u64_be(1u64),
		}));

		assert_eq!(
			xcm_transaction.into_transaction_v2(nonce, 111, false),
			expected_tx
		);
	}
}