referrerpolicy=no-referrer-when-downgrade

pallet_revive/evm/api/
account.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17//! Utilities for working with Ethereum accounts.
18use crate::{
19	evm::{TransactionSigned, TransactionUnsigned},
20	H160,
21};
22use sp_runtime::AccountId32;
23
24/// A simple account that can sign transactions
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Account(subxt_signer::eth::Keypair);
27
28impl Default for Account {
29	fn default() -> Self {
30		Self(subxt_signer::eth::dev::alith())
31	}
32}
33
34impl From<subxt_signer::eth::Keypair> for Account {
35	fn from(kp: subxt_signer::eth::Keypair) -> Self {
36		Self(kp)
37	}
38}
39
40impl Account {
41	/// Create a new account from a secret
42	pub fn from_secret_key(secret_key: [u8; 32]) -> Self {
43		subxt_signer::eth::Keypair::from_secret_key(secret_key).unwrap().into()
44	}
45
46	/// Get the [`H160`] address of the account.
47	pub fn address(&self) -> H160 {
48		H160::from_slice(&self.0.public_key().to_account_id().as_ref())
49	}
50
51	/// Get the substrate [`AccountId32`] of the account.
52	pub fn substrate_account(&self) -> AccountId32 {
53		let mut account_id = AccountId32::new([0xEE; 32]);
54		<AccountId32 as AsMut<[u8; 32]>>::as_mut(&mut account_id)[..20]
55			.copy_from_slice(self.address().as_ref());
56		account_id
57	}
58
59	/// Sign a transaction.
60	pub fn sign_transaction(&self, tx: TransactionUnsigned) -> TransactionSigned {
61		let payload = tx.unsigned_payload();
62		let signature = self.0.sign(&payload).0;
63		tx.with_signature(signature)
64	}
65}
66
67#[test]
68fn from_secret_key_works() {
69	let account = Account::from_secret_key(hex_literal::hex!(
70		"a872f6cbd25a0e04a08b1e21098017a9e6194d101d75e13111f71410c59cd57f"
71	));
72
73	assert_eq!(
74		account.address(),
75		H160::from(hex_literal::hex!("75e480db528101a381ce68544611c169ad7eb342"))
76	)
77}