1#![cfg_attr(not(feature = "std"), no_std)]
20
21extern crate alloc;
22
23use alloc::vec::Vec;
24use core::marker::PhantomData;
25use ethereum_standards::{
26 IERC20,
27 IERC20::{IERC20Calls, IERC20Events},
28};
29use frame_support::traits::fungibles::metadata::Inspect as MetadataInspect;
30use pallet_assets::{weights::WeightInfo as _, AssetsCallback, Call, Config, TransferFlags};
31use pallet_revive::precompiles::{
32 alloy::{
33 self,
34 primitives::IntoLogData,
35 sol_types::{Revert, SolCall},
36 },
37 AddressMapper, AddressMatcher, Error, Ext, Precompile, RuntimeCosts, H160, H256,
38};
39use sp_runtime::traits::{UniqueSaturatedInto, Zero};
40
41pub mod foreign_assets;
42pub mod migration;
43pub mod permit;
44pub mod weights;
45pub use weights::WeightInfo;
46
47#[cfg(feature = "runtime-benchmarks")]
48pub(crate) mod benchmarking;
49
50#[cfg(test)]
51mod foreign_assets_tests;
52#[cfg(test)]
53mod migration_tests;
54#[cfg(test)]
55mod mock;
56#[cfg(test)]
57mod permit_precompile_tests;
58#[cfg(test)]
59mod permit_tests;
60#[cfg(test)]
61mod test_helpers;
62#[cfg(test)]
63mod tests;
64
65pub use foreign_assets::{pallet, pallet::Config as ForeignAssetsConfig, ForeignAssetId};
66pub use migration::MigrateForeignAssetPrecompileMappings;
67pub use permit::pallet::Config as PermitConfig;
68
69pub trait AssetIdExtractor {
71 type AssetId;
72 fn asset_id_from_address(address: &[u8; 20]) -> Result<Self::AssetId, Error>;
74 fn asset_index(id: &Self::AssetId) -> Option<u32>;
76}
77
78pub trait AssetPrecompileConfig {
80 const MATCHER: AddressMatcher;
82
83 type AssetIdExtractor: AssetIdExtractor;
85}
86
87pub struct InlineAssetIdExtractor;
89
90impl AssetIdExtractor for InlineAssetIdExtractor {
91 type AssetId = u32;
92 fn asset_id_from_address(addr: &[u8; 20]) -> Result<Self::AssetId, Error> {
93 let bytes: [u8; 4] = addr[0..4].try_into().expect("slice is 4 bytes; qed");
94 let index = u32::from_be_bytes(bytes);
95 Ok(index)
96 }
97 fn asset_index(id: &Self::AssetId) -> Option<u32> {
98 Some(*id)
99 }
100}
101
102pub struct InlineIdConfig<const PREFIX: u16>;
104
105impl<const P: u16> AssetPrecompileConfig for InlineIdConfig<P> {
106 const MATCHER: AddressMatcher = AddressMatcher::Prefix(core::num::NonZero::new(P).unwrap());
107 type AssetIdExtractor = InlineAssetIdExtractor;
108}
109
110pub struct ForeignAssetIdExtractor<Runtime, Instance = ()> {
113 _phantom: PhantomData<(Runtime, Instance)>,
114}
115
116impl<Runtime, Instance: 'static> AssetIdExtractor for ForeignAssetIdExtractor<Runtime, Instance>
117where
118 Runtime: pallet_assets::Config<Instance>
119 + pallet::Config<ForeignAssetId = <Runtime as pallet_assets::Config<Instance>>::AssetId>
120 + pallet_revive::Config,
121{
122 type AssetId = <Runtime as pallet_assets::Config<Instance>>::AssetId;
123 fn asset_id_from_address(addr: &[u8; 20]) -> Result<Self::AssetId, Error> {
124 let bytes: [u8; 4] = addr[0..4].try_into().expect("slice is 4 bytes; qed");
125 let index = u32::from_be_bytes(bytes);
126 pallet::Pallet::<Runtime>::asset_id_of(index)
127 .ok_or(Error::Revert(Revert { reason: "Invalid foreign asset id".into() }))
128 }
129 fn asset_index(id: &Self::AssetId) -> Option<u32> {
130 pallet::Pallet::<Runtime>::asset_index_of(id)
131 }
132}
133
134pub struct ForeignIdConfig<const PREFIX: u16, Runtime, Instance = ()> {
136 _phantom: PhantomData<(Runtime, Instance)>,
137}
138
139impl<const P: u16, Runtime, Instance: 'static> AssetPrecompileConfig
140 for ForeignIdConfig<P, Runtime, Instance>
141where
142 Runtime: pallet_assets::Config<Instance>
143 + pallet::Config<ForeignAssetId = <Runtime as pallet_assets::Config<Instance>>::AssetId>
144 + pallet_revive::Config,
145{
146 const MATCHER: AddressMatcher = AddressMatcher::Prefix(core::num::NonZero::new(P).unwrap());
147 type AssetIdExtractor = ForeignAssetIdExtractor<Runtime, Instance>;
148}
149
150pub struct ERC20<Runtime, PrecompileConfig, Instance = ()> {
161 _phantom: PhantomData<(Runtime, PrecompileConfig, Instance)>,
162}
163
164impl<Runtime, PrecompileConfig, Instance: 'static> Precompile
165 for ERC20<Runtime, PrecompileConfig, Instance>
166where
167 PrecompileConfig: AssetPrecompileConfig,
168 Runtime: crate::Config<Instance> + pallet_revive::Config + permit::Config,
169 <<PrecompileConfig as AssetPrecompileConfig>::AssetIdExtractor as AssetIdExtractor>::AssetId:
170 Into<<Runtime as Config<Instance>>::AssetId>,
171 Call<Runtime, Instance>: Into<<Runtime as pallet_revive::Config>::RuntimeCall>,
172 alloy::primitives::U256: TryInto<<Runtime as Config<Instance>>::Balance>,
173 alloy::primitives::U256: TryFrom<<Runtime as Config<Instance>>::Balance>,
174{
175 type T = Runtime;
176 type Interface = IERC20::IERC20Calls;
177 const MATCHER: AddressMatcher = PrecompileConfig::MATCHER;
178 const HAS_CONTRACT_INFO: bool = false;
179
180 fn call(
181 address: &[u8; 20],
182 input: &Self::Interface,
183 env: &mut impl Ext<T = Self::T>,
184 ) -> Result<Vec<u8>, Error> {
185 frame_support::ensure!(
186 !env.is_delegate_call(),
187 pallet_revive::Error::<Self::T>::PrecompileDelegateDenied,
188 );
189
190 let asset_id = PrecompileConfig::AssetIdExtractor::asset_id_from_address(address)?.into();
191 let contract_addr = H160::from(*address);
192
193 match input {
194 IERC20Calls::transfer(_) |
196 IERC20Calls::approve(_) |
197 IERC20Calls::transferFrom(_) |
198 IERC20Calls::permit(_)
199 if env.is_read_only() =>
200 {
201 Err(Error::Error(pallet_revive::Error::<Self::T>::StateChangeDenied.into()))
202 },
203
204 IERC20Calls::transfer(call) => Self::transfer(asset_id, contract_addr, call, env),
206 IERC20Calls::totalSupply(_) => Self::total_supply(asset_id, env),
207 IERC20Calls::balanceOf(call) => Self::balance_of(asset_id, call, env),
208 IERC20Calls::allowance(call) => Self::allowance(asset_id, call, env),
209 IERC20Calls::approve(call) => Self::approve(asset_id, call, env),
210 IERC20Calls::transferFrom(call) => {
211 Self::transfer_from(asset_id, contract_addr, call, env)
212 },
213
214 IERC20Calls::permit(call) => Self::permit(asset_id, contract_addr, call, env),
216 IERC20Calls::nonces(call) => Self::nonces(contract_addr, call, env),
217 IERC20Calls::DOMAIN_SEPARATOR(_) => {
218 Self::domain_separator(asset_id, contract_addr, env)
219 },
220
221 IERC20Calls::name(_) => Self::name(asset_id, env),
223 IERC20Calls::symbol(_) => Self::symbol(asset_id, env),
224 IERC20Calls::decimals(_) => Self::decimals(asset_id, env),
225 }
226 }
227}
228
229pub struct Erc20TransferLogsCallback<Runtime, PrecompileConfig, Instance = ()> {
245 _phantom: PhantomData<(Runtime, PrecompileConfig, Instance)>,
246}
247
248impl<Runtime, PrecompileConfig, Instance>
249 AssetsCallback<
250 <Runtime as Config<Instance>>::AssetId,
251 <Runtime as frame_system::Config>::AccountId,
252 <Runtime as Config<Instance>>::Balance,
253 > for Erc20TransferLogsCallback<Runtime, PrecompileConfig, Instance>
254where
255 PrecompileConfig: AssetPrecompileConfig,
256 Runtime: Config<Instance> + pallet_revive::Config,
257 <Runtime as Config<Instance>>::AssetId:
258 Clone + Into<<PrecompileConfig::AssetIdExtractor as AssetIdExtractor>::AssetId>,
259 alloy::primitives::U256: TryFrom<<Runtime as Config<Instance>>::Balance>,
260 Instance: 'static,
261{
262 fn issued(
263 id: &<Runtime as Config<Instance>>::AssetId,
264 owner: &<Runtime as frame_system::Config>::AccountId,
265 amount: <Runtime as Config<Instance>>::Balance,
266 ) {
267 Self::emit(id, alloy::primitives::Address::ZERO, Self::evm_address(owner), amount);
268 }
269
270 fn transferred(
271 id: &<Runtime as Config<Instance>>::AssetId,
272 from: &<Runtime as frame_system::Config>::AccountId,
273 to: &<Runtime as frame_system::Config>::AccountId,
274 amount: <Runtime as Config<Instance>>::Balance,
275 ) {
276 Self::emit(id, Self::evm_address(from), Self::evm_address(to), amount);
277 }
278
279 fn burned(
280 id: &<Runtime as Config<Instance>>::AssetId,
281 owner: &<Runtime as frame_system::Config>::AccountId,
282 amount: <Runtime as Config<Instance>>::Balance,
283 ) {
284 Self::emit(id, Self::evm_address(owner), alloy::primitives::Address::ZERO, amount);
285 }
286
287 fn deposited(
288 id: &<Runtime as Config<Instance>>::AssetId,
289 who: &<Runtime as frame_system::Config>::AccountId,
290 amount: <Runtime as Config<Instance>>::Balance,
291 ) {
292 Self::emit(id, alloy::primitives::Address::ZERO, Self::evm_address(who), amount);
293 }
294
295 fn withdrawn(
296 id: &<Runtime as Config<Instance>>::AssetId,
297 who: &<Runtime as frame_system::Config>::AccountId,
298 amount: <Runtime as Config<Instance>>::Balance,
299 ) {
300 Self::emit(id, Self::evm_address(who), alloy::primitives::Address::ZERO, amount);
301 }
302}
303
304impl<Runtime, PrecompileConfig, Instance>
305 Erc20TransferLogsCallback<Runtime, PrecompileConfig, Instance>
306where
307 PrecompileConfig: AssetPrecompileConfig,
308 Runtime: Config<Instance> + pallet_revive::Config,
309 <Runtime as Config<Instance>>::AssetId:
310 Clone + Into<<PrecompileConfig::AssetIdExtractor as AssetIdExtractor>::AssetId>,
311 alloy::primitives::U256: TryFrom<<Runtime as Config<Instance>>::Balance>,
312 Instance: 'static,
313{
314 fn token_address(id: &<Runtime as Config<Instance>>::AssetId) -> Option<H160> {
317 let index = PrecompileConfig::AssetIdExtractor::asset_index(&id.clone().into())?;
318 let mut address = PrecompileConfig::MATCHER.base_address();
319 address[..4].copy_from_slice(&index.to_be_bytes());
320 Some(H160(address))
321 }
322
323 fn evm_address(
324 account: &<Runtime as frame_system::Config>::AccountId,
325 ) -> alloy::primitives::Address {
326 <Runtime as pallet_revive::Config>::AddressMapper::to_address(account).0.into()
327 }
328
329 fn emit(
330 id: &<Runtime as Config<Instance>>::AssetId,
331 from: alloy::primitives::Address,
332 to: alloy::primitives::Address,
333 amount: <Runtime as Config<Instance>>::Balance,
334 ) {
335 let Ok(value) = alloy::primitives::U256::try_from(amount) else {
336 frame_support::defensive!(
337 "asset balance exceeds U256; Transfer log dropped (unreachable for balance types up to 256 bit)",
338 (id, from, to, amount)
339 );
340 return;
341 };
342 let Some(token) = Self::token_address(id) else {
343 log::error!(
344 target: frame_support::LOG_TARGET,
345 "asset has no precompile address mapping; Transfer log dropped (a foreign asset predating the index-map migration): {:?}",
346 (id, from, to, amount)
347 );
348 return;
349 };
350 emit_transfer_log::<Runtime>(token, from, to, value);
351 }
352}
353
354fn emit_transfer_log<Runtime: pallet_revive::Config>(
359 token: H160,
360 from: alloy::primitives::Address,
361 to: alloy::primitives::Address,
362 value: alloy::primitives::U256,
363) {
364 let (topics, data) = IERC20Events::Transfer(IERC20::Transfer { from, to, value })
365 .into_log_data()
366 .split();
367 let topics = topics.into_iter().map(|t| H256(t.0)).collect::<Vec<_>>();
368 let topics = pallet_revive::ContractLogTopics::try_from(topics)
369 .expect("Transfer has 3 topics, within NUM_EVENT_TOPICS of 4; qed");
370 let data = pallet_revive::ContractLogData::try_from(data.to_vec())
371 .expect("Transfer data is a single 32 byte word, within EVENT_BYTES of 64 KiB; qed");
372 pallet_revive::Pallet::<Runtime>::emit_contract_log_outside_frame(token, topics, data);
373}
374
375const TRANSFER_LOG_TOPICS: u32 = 3;
378const TRANSFER_LOG_DATA_LEN: u32 = 32;
379
380const ERR_INVALID_CALLER: &str = "Invalid caller";
381const ERR_BALANCE_CONVERSION_FAILED: &str = "Balance conversion failed";
382
383impl<Runtime, PrecompileConfig, Instance: 'static> ERC20<Runtime, PrecompileConfig, Instance>
384where
385 PrecompileConfig: AssetPrecompileConfig,
386 Runtime: crate::Config<Instance> + pallet_revive::Config + permit::Config,
387 <<PrecompileConfig as AssetPrecompileConfig>::AssetIdExtractor as AssetIdExtractor>::AssetId:
388 Into<<Runtime as Config<Instance>>::AssetId>,
389 Call<Runtime, Instance>: Into<<Runtime as pallet_revive::Config>::RuntimeCall>,
390 alloy::primitives::U256: TryInto<<Runtime as Config<Instance>>::Balance>,
391 alloy::primitives::U256: TryFrom<<Runtime as Config<Instance>>::Balance>,
392{
393 fn caller(env: &mut impl Ext<T = Runtime>) -> Result<H160, Error> {
395 env.caller()
396 .account_id()
397 .map(<Runtime as pallet_revive::Config>::AddressMapper::to_address)
398 .map_err(|_| Error::Revert(Revert { reason: ERR_INVALID_CALLER.into() }))
399 }
400
401 fn to_balance(
403 value: alloy::primitives::U256,
404 ) -> Result<<Runtime as Config<Instance>>::Balance, Error> {
405 value
406 .try_into()
407 .map_err(|_| Error::Revert(Revert { reason: ERR_BALANCE_CONVERSION_FAILED.into() }))
408 }
409
410 fn to_u256(
413 value: <Runtime as Config<Instance>>::Balance,
414 ) -> Result<alloy::primitives::U256, Error> {
415 alloy::primitives::U256::try_from(value)
416 .map_err(|_| Error::Revert(Revert { reason: ERR_BALANCE_CONVERSION_FAILED.into() }))
417 }
418
419 fn deposit_event(env: &mut impl Ext<T = Runtime>, event: IERC20Events) -> Result<(), Error> {
421 let (topics, data) = event.into_log_data().split();
422 let topics = topics.into_iter().map(|v| H256(v.0)).collect::<Vec<_>>();
423 let topics = pallet_revive::ContractLogTopics::try_from(topics)
424 .expect("IERC20 events have 3 topics, within NUM_EVENT_TOPICS of 4; qed");
425 env.frame_meter_mut().charge_weight_token(RuntimeCosts::DepositEvent {
426 num_topic: topics.len() as u32,
427 len: data.len() as u32,
428 })?;
429 env.deposit_event(topics, data.to_vec())?;
430 Ok(())
431 }
432
433 fn transfer(
438 asset_id: <Runtime as Config<Instance>>::AssetId,
439 contract_addr: H160,
440 call: &IERC20::transferCall,
441 env: &mut impl Ext<T = Runtime>,
442 ) -> Result<Vec<u8>, Error> {
443 env.charge(<Runtime as Config<Instance>>::WeightInfo::transfer())?;
448 env.frame_meter_mut().charge_weight_token(RuntimeCosts::DepositEvent {
449 num_topic: TRANSFER_LOG_TOPICS,
450 len: TRANSFER_LOG_DATA_LEN,
451 })?;
452
453 let from = Self::caller(env)?;
454 let from_account = <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&from);
455 let dest = <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(
456 &call.to.into_array().into(),
457 );
458 let amount = Self::to_balance(call.value)?;
459
460 let f = TransferFlags { keep_alive: false, best_effort: false, burn_dust: false };
461 pallet_assets::Pallet::<Runtime, Instance>::do_transfer(
462 asset_id,
463 &from_account,
464 &dest,
465 amount,
466 None,
467 f,
468 )?;
469
470 if call.value.is_zero() {
475 emit_transfer_log::<Runtime>(contract_addr, from.0.into(), call.to, call.value);
476 }
477
478 Ok(IERC20::transferCall::abi_encode_returns(&true))
479 }
480
481 fn total_supply(
483 asset_id: <Runtime as Config<Instance>>::AssetId,
484 env: &mut impl Ext<T = Runtime>,
485 ) -> Result<Vec<u8>, Error> {
486 use frame_support::traits::fungibles::Inspect;
487 env.charge(<Runtime as Config<Instance>>::WeightInfo::total_issuance())?;
488
489 let value =
490 Self::to_u256(pallet_assets::Pallet::<Runtime, Instance>::total_issuance(asset_id))?;
491 Ok(IERC20::totalSupplyCall::abi_encode_returns(&value))
492 }
493
494 fn balance_of(
500 asset_id: <Runtime as Config<Instance>>::AssetId,
501 call: &IERC20::balanceOfCall,
502 env: &mut impl Ext<T = Runtime>,
503 ) -> Result<Vec<u8>, Error> {
504 use frame_support::traits::fungibles::Inspect;
505
506 env.charge(<Runtime as Config<Instance>>::WeightInfo::balance())?;
507 let account = call.account.into_array().into();
508 let account = <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&account);
509 let value = Self::to_u256(pallet_assets::Pallet::<Runtime, Instance>::total_balance(
510 asset_id, &account,
511 ))?;
512 Ok(IERC20::balanceOfCall::abi_encode_returns(&value))
513 }
514
515 fn allowance(
517 asset_id: <Runtime as Config<Instance>>::AssetId,
518 call: &IERC20::allowanceCall,
519 env: &mut impl Ext<T = Runtime>,
520 ) -> Result<Vec<u8>, Error> {
521 env.charge(<Runtime as Config<Instance>>::WeightInfo::allowance())?;
522 use frame_support::traits::fungibles::approvals::Inspect;
523 let owner = call.owner.into_array().into();
524 let owner = <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&owner);
525
526 let spender = call.spender.into_array().into();
527 let spender = <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&spender);
528 let value = Self::to_u256(pallet_assets::Pallet::<Runtime, Instance>::allowance(
529 asset_id, &owner, &spender,
530 ))?;
531
532 Ok(IERC20::allowanceCall::abi_encode_returns(&value))
533 }
534
535 fn approve(
545 asset_id: <Runtime as Config<Instance>>::AssetId,
546 call: &IERC20::approveCall,
547 env: &mut impl Ext<T = Runtime>,
548 ) -> Result<Vec<u8>, Error> {
549 use frame_support::traits::fungibles::approvals::Inspect as ApprovalsInspect;
550
551 let worst_case = <Runtime as Config<Instance>>::WeightInfo::allowance()
553 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::cancel_approval())
554 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::approve_transfer());
555 let charged = env.charge(worst_case)?;
556
557 let owner = Self::caller(env)?;
558 let owner_account =
559 <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&owner);
560 let spender: H160 = call.spender.into_array().into();
561 let spender_account = env.to_account_id(&spender);
562 let new_amount: <Runtime as Config<Instance>>::Balance = call.value.unique_saturated_into();
565
566 let current = pallet_assets::Pallet::<Runtime, Instance>::allowance(
567 asset_id.clone(),
568 &owner_account,
569 &spender_account,
570 );
571
572 let actual_weight;
573 if new_amount.is_zero() {
574 if !current.is_zero() {
575 pallet_assets::Pallet::<Runtime, Instance>::do_cancel_approval(
578 &asset_id,
579 &owner_account,
580 &spender_account,
581 )?;
582 actual_weight = <Runtime as Config<Instance>>::WeightInfo::allowance()
583 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::cancel_approval());
584 } else {
585 actual_weight = <Runtime as Config<Instance>>::WeightInfo::allowance();
587 }
588 } else {
589 if !current.is_zero() {
595 pallet_assets::Pallet::<Runtime, Instance>::do_cancel_approval(
596 &asset_id,
597 &owner_account,
598 &spender_account,
599 )?;
600 actual_weight = worst_case;
601 } else {
602 actual_weight = <Runtime as Config<Instance>>::WeightInfo::allowance()
603 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::approve_transfer());
604 }
605 pallet_assets::Pallet::<Runtime, Instance>::do_approve_transfer(
606 asset_id,
607 &owner_account,
608 &spender_account,
609 new_amount,
610 )?;
611 }
612 env.adjust_gas(charged, actual_weight);
613
614 Self::deposit_event(
615 env,
616 IERC20Events::Approval(IERC20::Approval {
617 owner: owner.0.into(),
618 spender: call.spender,
619 value: call.value,
620 }),
621 )?;
622
623 Ok(IERC20::approveCall::abi_encode_returns(&true))
624 }
625
626 fn transfer_from(
631 asset_id: <Runtime as Config<Instance>>::AssetId,
632 contract_addr: H160,
633 call: &IERC20::transferFromCall,
634 env: &mut impl Ext<T = Runtime>,
635 ) -> Result<Vec<u8>, Error> {
636 env.charge(<Runtime as Config<Instance>>::WeightInfo::transfer_approved())?;
639 env.frame_meter_mut().charge_weight_token(RuntimeCosts::DepositEvent {
640 num_topic: TRANSFER_LOG_TOPICS,
641 len: TRANSFER_LOG_DATA_LEN,
642 })?;
643 let spender = Self::caller(env)?;
644 let spender = <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&spender);
645
646 let from = call.from.into_array().into();
647 let from = <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&from);
648
649 let to = call.to.into_array().into();
650 let to = <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&to);
651
652 let approval_amount = Self::to_balance(call.value)?;
653 pallet_assets::Pallet::<Runtime, Instance>::do_transfer_approved(
654 asset_id,
655 &from,
656 &spender,
657 &to,
658 approval_amount,
659 )?;
660
661 if call.value.is_zero() {
665 emit_transfer_log::<Runtime>(contract_addr, call.from, call.to, call.value);
666 }
667
668 Ok(IERC20::transferFromCall::abi_encode_returns(&true))
669 }
670
671 pub(crate) fn permit(
679 asset_id: <Runtime as Config<Instance>>::AssetId,
680 verifying_contract: H160,
681 call: &IERC20::permitCall,
682 env: &mut impl Ext<T = Runtime>,
683 ) -> Result<Vec<u8>, Error> {
684 let use_permit_weight = <Runtime as permit::Config>::WeightInfo::use_permit();
688 let worst_case = use_permit_weight
689 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::allowance())
690 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::cancel_approval())
691 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::approve_transfer());
692 let charged = env.charge(worst_case)?;
693
694 let owner_h160: H160 = call.owner.into_array().into();
695 let spender_h160: H160 = call.spender.into_array().into();
696
697 let value_bytes: [u8; 32] = call.value.to_be_bytes();
699 let deadline_bytes: [u8; 32] = call.deadline.to_be_bytes();
700 let r_bytes: [u8; 32] = call.r.0;
701 let s_bytes: [u8; 32] = call.s.0;
702
703 let transaction_outcome = frame_support::storage::with_transaction(|| {
704 let result = (|| {
705 permit::Pallet::<Runtime>::use_permit(
707 &verifying_contract,
708 &pallet_assets::Pallet::<Runtime, Instance>::name(asset_id.clone()),
709 &owner_h160,
710 &spender_h160,
711 &value_bytes,
712 &deadline_bytes,
713 call.v,
714 &r_bytes,
715 &s_bytes,
716 )
717 .map_err(|e| {
718 let msg = match e {
719 permit::pallet::Error::PermitExpired => "Permit expired",
720 permit::pallet::Error::InvalidSignature => "Invalid signature",
721 permit::pallet::Error::SignerMismatch => "Signer does not match owner",
722 permit::pallet::Error::SignatureSValueTooHigh => {
723 "Signature s value too high (malleability)"
724 },
725 permit::pallet::Error::InvalidVValue => "Invalid signature v value",
726 permit::pallet::Error::NonceOverflow => "Nonce overflow",
727 permit::pallet::Error::InvalidOwner => "Invalid owner address",
728 permit::pallet::Error::InvalidSpender => "Invalid spender address",
729 };
730 Error::Revert(Revert { reason: msg.into() })
731 })?;
732
733 use frame_support::traits::fungibles::approvals::Inspect as ApprovalsInspect;
736 let owner_account =
737 <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&owner_h160);
738 let spender_account =
739 <Runtime as pallet_revive::Config>::AddressMapper::to_account_id(&spender_h160);
740
741 let new_amount: <Runtime as Config<Instance>>::Balance =
743 call.value.unique_saturated_into();
744 let current = pallet_assets::Pallet::<Runtime, Instance>::allowance(
745 asset_id.clone(),
746 &owner_account,
747 &spender_account,
748 );
749
750 let actual_weight;
751 if new_amount.is_zero() {
752 if !current.is_zero() {
753 pallet_assets::Pallet::<Runtime, Instance>::do_cancel_approval(
756 &asset_id,
757 &owner_account,
758 &spender_account,
759 )?;
760 actual_weight = use_permit_weight
761 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::allowance())
762 .saturating_add(
763 <Runtime as Config<Instance>>::WeightInfo::cancel_approval(),
764 );
765 } else {
766 actual_weight = use_permit_weight
768 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::allowance());
769 }
770 } else {
771 if !current.is_zero() {
772 pallet_assets::Pallet::<Runtime, Instance>::do_cancel_approval(
774 &asset_id,
775 &owner_account,
776 &spender_account,
777 )?;
778 actual_weight = worst_case;
779 } else {
780 actual_weight = use_permit_weight
782 .saturating_add(<Runtime as Config<Instance>>::WeightInfo::allowance())
783 .saturating_add(
784 <Runtime as Config<Instance>>::WeightInfo::approve_transfer(),
785 );
786 }
787 pallet_assets::Pallet::<Runtime, Instance>::do_approve_transfer(
788 asset_id,
789 &owner_account,
790 &spender_account,
791 new_amount,
792 )?;
793 }
794
795 Self::deposit_event(
797 env,
798 IERC20Events::Approval(IERC20::Approval {
799 owner: call.owner,
800 spender: call.spender,
801 value: call.value,
802 }),
803 )?;
804 Ok::<_, Error>(actual_weight)
805 })();
806 match result {
807 Ok(actual_weight) => {
808 frame_support::storage::TransactionOutcome::Commit(Ok(actual_weight))
809 },
810 Err(e) => {
811 log::trace!(target: frame_support::LOG_TARGET, "Call to permit failed: {e:?}");
812 frame_support::storage::TransactionOutcome::Rollback(Err(e))
813 },
814 }
815 });
816
817 match transaction_outcome {
819 Ok(actual_weight) => {
820 env.adjust_gas(charged, actual_weight);
821 Ok(Vec::new())
822 },
823 Err(e) => Err(e),
824 }
825 }
826
827 fn nonces(
829 verifying_contract: H160,
830 call: &IERC20::noncesCall,
831 env: &mut impl Ext<T = Runtime>,
832 ) -> Result<Vec<u8>, Error> {
833 env.charge(<Runtime as permit::Config>::WeightInfo::nonces())?;
834
835 let owner_h160: H160 = call.owner.into_array().into();
836 let nonce = permit::Pallet::<Runtime>::nonce(&verifying_contract, &owner_h160);
837
838 let nonce_bytes = nonce.to_big_endian();
840 let nonce_alloy = alloy::primitives::U256::from_be_bytes(nonce_bytes);
841
842 Ok(IERC20::noncesCall::abi_encode_returns(&nonce_alloy))
843 }
844
845 fn domain_separator(
847 asset_id: <Runtime as Config<Instance>>::AssetId,
848 verifying_contract: H160,
849 env: &mut impl Ext<T = Runtime>,
850 ) -> Result<Vec<u8>, Error> {
851 env.charge(<Runtime as permit::Config>::WeightInfo::domain_separator())?;
852
853 let token_name = pallet_assets::Pallet::<Runtime, Instance>::name(asset_id);
855
856 let separator =
857 permit::Pallet::<Runtime>::compute_domain_separator(&verifying_contract, &token_name);
858 let separator_alloy: alloy::primitives::FixedBytes<32> = separator.0.into();
859
860 Ok(IERC20::DOMAIN_SEPARATORCall::abi_encode_returns(&separator_alloy))
861 }
862
863 fn name(
865 asset_id: <Runtime as Config<Instance>>::AssetId,
866 env: &mut impl Ext<T = Runtime>,
867 ) -> Result<Vec<u8>, Error> {
868 env.charge(<Runtime as Config<Instance>>::WeightInfo::get_metadata())?;
869
870 let metadata = pallet_assets::Pallet::<Runtime, Instance>::get_metadata(asset_id)
871 .ok_or(Error::Revert(Revert { reason: "Metadata not found".into() }))?;
872
873 let name = alloc::string::String::from_utf8(metadata.name.to_vec())
874 .map_err(|_| Error::Revert(Revert { reason: "Invalid UTF-8 in name".into() }))?;
875
876 Ok(IERC20::nameCall::abi_encode_returns(&name))
877 }
878
879 fn symbol(
881 asset_id: <Runtime as Config<Instance>>::AssetId,
882 env: &mut impl Ext<T = Runtime>,
883 ) -> Result<Vec<u8>, Error> {
884 env.charge(<Runtime as Config<Instance>>::WeightInfo::get_metadata())?;
885
886 let metadata = pallet_assets::Pallet::<Runtime, Instance>::get_metadata(asset_id)
887 .ok_or(Error::Revert(Revert { reason: "Metadata not found".into() }))?;
888
889 let symbol = alloc::string::String::from_utf8(metadata.symbol.to_vec())
890 .map_err(|_| Error::Revert(Revert { reason: "Invalid UTF-8 in symbol".into() }))?;
891
892 Ok(IERC20::symbolCall::abi_encode_returns(&symbol))
893 }
894
895 fn decimals(
897 asset_id: <Runtime as Config<Instance>>::AssetId,
898 env: &mut impl Ext<T = Runtime>,
899 ) -> Result<Vec<u8>, Error> {
900 env.charge(<Runtime as Config<Instance>>::WeightInfo::get_metadata())?;
901
902 let metadata = pallet_assets::Pallet::<Runtime, Instance>::get_metadata(asset_id)
903 .ok_or(Error::Revert(Revert { reason: "Metadata not found".into() }))?;
904
905 Ok(IERC20::decimalsCall::abi_encode_returns(&metadata.decimals))
906 }
907}