pallet_evm_precompile_unified_accounts/
lib.rs

1// This file is part of Astar.
2
3// Copyright (C) Stake Technologies Pte.Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later
5
6// Astar is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// Astar is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with Astar. If not, see <http://www.gnu.org/licenses/>.
18
19#![cfg_attr(not(feature = "std"), no_std)]
20
21use astar_primitives::evm::{UnifiedAddress, UnifiedAddressMapper};
22use core::marker::PhantomData;
23use fp_evm::PrecompileHandle;
24use frame_support::traits::IsType;
25use precompile_utils::prelude::*;
26use sp_core::{crypto::AccountId32, H256};
27
28#[cfg(test)]
29mod mock;
30#[cfg(test)]
31mod tests;
32
33/// A precompile that expose AU related functions.
34pub struct UnifiedAccountsPrecompile<T, UA>(PhantomData<(T, UA)>);
35
36#[precompile_utils::precompile]
37impl<R, UA> UnifiedAccountsPrecompile<R, UA>
38where
39    R: pallet_evm::Config + pallet_unified_accounts::Config,
40    <R as frame_system::Config>::AccountId: IsType<AccountId32>,
41    UA: UnifiedAddressMapper<R::AccountId>,
42{
43    #[precompile::public("get_evm_address_or_default(bytes32)")]
44    #[precompile::view]
45    fn get_evm_address_or_default(
46        _: &mut impl PrecompileHandle,
47        account_id: H256,
48    ) -> EvmResult<(Address, bool)> {
49        let account_id = AccountId32::new(account_id.into()).into();
50
51        let output: (Address, bool) = match UA::to_h160_or_default(&account_id) {
52            UnifiedAddress::Mapped(address) => (address.into(), true),
53            UnifiedAddress::Default(address) => (address.into(), false),
54        };
55        Ok(output)
56    }
57
58    #[precompile::public("get_native_address_or_default(address)")]
59    #[precompile::view]
60    fn get_native_address_or_default(
61        _: &mut impl PrecompileHandle,
62        evm_address: Address,
63    ) -> EvmResult<(H256, bool)> {
64        let output: (H256, bool) = match UA::to_account_id_or_default(&evm_address.into()) {
65            UnifiedAddress::Mapped(account_id) => (H256::from(account_id.into().as_ref()), true),
66            UnifiedAddress::Default(account_id) => (H256::from(account_id.into().as_ref()), false),
67        };
68        Ok(output)
69    }
70}