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
#![cfg_attr(not(feature = "std"), no_std)]
18

            
19
use core::marker::PhantomData;
20
use evm::ExitReason;
21
use fp_evm::{Context, ExitRevert, PrecompileFailure, PrecompileHandle, Transfer};
22
use frame_support::{
23
	ensure,
24
	storage::types::{StorageMap, ValueQuery},
25
	traits::{ConstU32, Get, StorageInstance, Time},
26
	Blake2_128Concat,
27
};
28
use precompile_utils::{evm::costs::call_cost, prelude::*};
29
use sp_core::{H160, H256, U256};
30
use sp_io::hashing::keccak_256;
31
use sp_runtime::traits::UniqueSaturatedInto;
32
use sp_std::vec::Vec;
33

            
34
#[cfg(test)]
35
mod mock;
36
#[cfg(test)]
37
mod tests;
38

            
39
/// Storage prefix for nonces.
40
pub struct Nonces;
41

            
42
impl StorageInstance for Nonces {
43
	const STORAGE_PREFIX: &'static str = "Nonces";
44

            
45
13
	fn pallet_prefix() -> &'static str {
46
13
		"PrecompileCallPermit"
47
13
	}
48
}
49

            
50
/// Storage type used to store EIP2612 nonces.
51
pub type NoncesStorage = StorageMap<
52
	Nonces,
53
	// From
54
	Blake2_128Concat,
55
	H160,
56
	// Nonce
57
	U256,
58
	ValueQuery,
59
>;
60

            
61
/// EIP712 permit typehash.
62
pub const PERMIT_TYPEHASH: [u8; 32] = keccak256!(
63
	"CallPermit(address from,address to,uint256 value,bytes data,uint64 gaslimit\
64
,uint256 nonce,uint256 deadline)"
65
);
66

            
67
/// EIP712 permit domain used to compute an individualized domain separator.
68
const PERMIT_DOMAIN: [u8; 32] = keccak256!(
69
	"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
70
);
71

            
72
pub const CALL_DATA_LIMIT: u32 = 2u32.pow(16);
73

            
74
/// Precompile allowing to issue and dispatch call permits for gasless transactions.
75
/// A user can sign a permit for a call that can be dispatched and paid by another user or
76
/// smart contract.
77
pub struct CallPermitPrecompile<Runtime>(PhantomData<Runtime>);
78

            
79
97
#[precompile_utils::precompile]
80
impl<Runtime> CallPermitPrecompile<Runtime>
81
where
82
	Runtime: pallet_evm::Config,
83
{
84
10
	fn compute_domain_separator(address: H160) -> [u8; 32] {
85
10
		let name: H256 = keccak_256(b"Call Permit Precompile").into();
86
10
		let version: H256 = keccak256!("1").into();
87
10
		let chain_id: U256 = Runtime::ChainId::get().into();
88
10

            
89
10
		let domain_separator_inner = solidity::encode_arguments((
90
10
			H256::from(PERMIT_DOMAIN),
91
10
			name,
92
10
			version,
93
10
			chain_id,
94
10
			Address(address),
95
10
		));
96
10

            
97
10
		keccak_256(&domain_separator_inner).into()
98
10
	}
99

            
100
9
	pub fn generate_permit(
101
9
		address: H160,
102
9
		from: H160,
103
9
		to: H160,
104
9
		value: U256,
105
9
		data: Vec<u8>,
106
9
		gaslimit: u64,
107
9
		nonce: U256,
108
9
		deadline: U256,
109
9
	) -> [u8; 32] {
110
9
		let domain_separator = Self::compute_domain_separator(address);
111
9

            
112
9
		let permit_content = solidity::encode_arguments((
113
9
			H256::from(PERMIT_TYPEHASH),
114
9
			Address(from),
115
9
			Address(to),
116
9
			value,
117
9
			// bytes are encoded as the keccak_256 of the content
118
9
			H256::from(keccak_256(&data)),
119
9
			gaslimit,
120
9
			nonce,
121
9
			deadline,
122
9
		));
123
9
		let permit_content = keccak_256(&permit_content);
124
9
		let mut pre_digest = Vec::with_capacity(2 + 32 + 32);
125
9
		pre_digest.extend_from_slice(b"\x19\x01");
126
9
		pre_digest.extend_from_slice(&domain_separator);
127
9
		pre_digest.extend_from_slice(&permit_content);
128
9
		keccak_256(&pre_digest)
129
9
	}
130

            
131
18
	pub fn dispatch_inherent_cost() -> u64 {
132
18
		3_000 // cost of ECRecover precompile for reference
133
18
			+ RuntimeHelper::<Runtime>::db_write_gas_cost() // we write nonce
134
18
	}
135

            
136
	#[precompile::public(
137
		"dispatch(address,address,uint256,bytes,uint64,uint256,uint8,bytes32,bytes32)"
138
	)]
139
6
	fn dispatch(
140
6
		handle: &mut impl PrecompileHandle,
141
6
		from: Address,
142
6
		to: Address,
143
6
		value: U256,
144
6
		data: BoundedBytes<ConstU32<CALL_DATA_LIMIT>>,
145
6
		gas_limit: u64,
146
6
		deadline: U256,
147
6
		v: u8,
148
6
		r: H256,
149
6
		s: H256,
150
6
	) -> EvmResult<UnboundedBytes> {
151
6
		// Now: 8
152
6
		handle.record_db_read::<Runtime>(8)?;
153
		// NoncesStorage: Blake2_128(16) + contract(20) + Blake2_128(16) + owner(20) + nonce(32)
154
6
		handle.record_db_read::<Runtime>(104)?;
155

            
156
6
		handle.record_cost(Self::dispatch_inherent_cost())?;
157

            
158
6
		let from: H160 = from.into();
159
6
		let to: H160 = to.into();
160
6
		let data: Vec<u8> = data.into();
161
6

            
162
6
		// ENSURE GASLIMIT IS SUFFICIENT
163
6
		let call_cost = call_cost(value, <Runtime as pallet_evm::Config>::config());
164

            
165
6
		let total_cost = gas_limit
166
6
			.checked_add(call_cost)
167
6
			.ok_or_else(|| revert("Call require too much gas (uint64 overflow)"))?;
168

            
169
5
		if total_cost > handle.remaining_gas() {
170
1
			return Err(revert("Gaslimit is too low to dispatch provided call"));
171
4
		}
172
4

            
173
4
		// VERIFY PERMIT
174
4

            
175
4
		// Blockchain time is in ms while Ethereum use second timestamps.
176
4
		let timestamp: u128 =
177
4
			<Runtime as pallet_evm::Config>::Timestamp::now().unique_saturated_into();
178
4
		let timestamp: U256 = U256::from(timestamp / 1000);
179
4

            
180
4
		ensure!(deadline >= timestamp, revert("Permit expired"));
181

            
182
4
		let nonce = NoncesStorage::get(from);
183
4

            
184
4
		let permit = Self::generate_permit(
185
4
			handle.context().address,
186
4
			from,
187
4
			to,
188
4
			value,
189
4
			data.clone(),
190
4
			gas_limit,
191
4
			nonce,
192
4
			deadline,
193
4
		);
194
4

            
195
4
		let mut sig = [0u8; 65];
196
4
		sig[0..32].copy_from_slice(&r.as_bytes());
197
4
		sig[32..64].copy_from_slice(&s.as_bytes());
198
4
		sig[64] = v;
199

            
200
4
		let signer = sp_io::crypto::secp256k1_ecdsa_recover(&sig, &permit)
201
4
			.map_err(|_| revert("Invalid permit"))?;
202
4
		let signer = H160::from(H256::from_slice(keccak_256(&signer).as_slice()));
203
4

            
204
4
		ensure!(
205
4
			signer != H160::zero() && signer == from,
206
1
			revert("Invalid permit")
207
		);
208

            
209
3
		NoncesStorage::insert(from, nonce + U256::one());
210
3

            
211
3
		// DISPATCH CALL
212
3
		let sub_context = Context {
213
3
			caller: from,
214
3
			address: to.clone(),
215
3
			apparent_value: value,
216
3
		};
217

            
218
3
		let transfer = if value.is_zero() {
219
			None
220
		} else {
221
3
			Some(Transfer {
222
3
				source: from,
223
3
				target: to.clone(),
224
3
				value,
225
3
			})
226
		};
227

            
228
3
		let (reason, output) =
229
3
			handle.call(to, transfer, data, Some(gas_limit), false, &sub_context);
230
3
		match reason {
231
			ExitReason::Error(exit_status) => Err(PrecompileFailure::Error { exit_status }),
232
			ExitReason::Fatal(exit_status) => Err(PrecompileFailure::Fatal { exit_status }),
233
1
			ExitReason::Revert(_) => Err(PrecompileFailure::Revert {
234
1
				exit_status: ExitRevert::Reverted,
235
1
				output,
236
1
			}),
237
2
			ExitReason::Succeed(_) => Ok(output.into()),
238
		}
239
6
	}
240

            
241
	#[precompile::public("nonces(address)")]
242
	#[precompile::view]
243
6
	fn nonces(handle: &mut impl PrecompileHandle, owner: Address) -> EvmResult<U256> {
244
6
		// NoncesStorage: Blake2_128(16) + contract(20) + Blake2_128(16) + owner(20) + nonce(32)
245
6
		handle.record_db_read::<Runtime>(104)?;
246

            
247
6
		let owner: H160 = owner.into();
248
6

            
249
6
		let nonce = NoncesStorage::get(owner);
250
6

            
251
6
		Ok(nonce)
252
6
	}
253

            
254
	#[precompile::public("DOMAIN_SEPARATOR()")]
255
	#[precompile::view]
256
1
	fn domain_separator(handle: &mut impl PrecompileHandle) -> EvmResult<H256> {
257
1
		// ChainId
258
1
		handle.record_db_read::<Runtime>(8)?;
259

            
260
1
		let domain_separator: H256 =
261
1
			Self::compute_domain_separator(handle.context().address).into();
262
1

            
263
1
		Ok(domain_separator)
264
1
	}
265
}