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
25pub struct Account(subxt_signer::eth::Keypair);
26
27impl Default for Account {
28	fn default() -> Self {
29		Self(subxt_signer::eth::dev::alith())
30	}
31}
32
33impl From<subxt_signer::eth::Keypair> for Account {
34	fn from(kp: subxt_signer::eth::Keypair) -> Self {
35		Self(kp)
36	}
37}
38
39impl Account {
40	/// Create a new account from a secret
41	pub fn from_secret_key(secret_key: [u8; 32]) -> Self {
42		subxt_signer::eth::Keypair::from_secret_key(secret_key).unwrap().into()
43	}
44
45	/// Get the [`H160`] address of the account.
46	pub fn address(&self) -> H160 {
47		H160::from_slice(&self.0.public_key().to_account_id().as_ref())
48	}
49
50	/// Get the substrate [`AccountId32`] of the account.
51	pub fn substrate_account(&self) -> AccountId32 {
52		let mut account_id = AccountId32::new([0xEE; 32]);
53		<AccountId32 as AsMut<[u8; 32]>>::as_mut(&mut account_id)[..20]
54			.copy_from_slice(self.address().as_ref());
55		account_id
56	}
57
58	/// Sign a transaction.
59	pub fn sign_transaction(&self, tx: TransactionUnsigned) -> TransactionSigned {
60		let payload = tx.unsigned_payload();
61		let signature = self.0.sign(&payload).0;
62		tx.with_signature(signature)
63	}
64}
65
66#[test]
67fn from_secret_key_works() {
68	let account = Account::from_secret_key(hex_literal::hex!(
69		"a872f6cbd25a0e04a08b1e21098017a9e6194d101d75e13111f71410c59cd57f"
70	));
71
72	assert_eq!(
73		account.address(),
74		H160::from(hex_literal::hex!("75e480db528101a381ce68544611c169ad7eb342"))
75	)
76}