@@ -2,7 +2,25 @@ import { H160 } from '@polkadot/types/interfaces';
2
2
import { KeyringPair } from '@polkadot/keyring/types' ;
3
3
import { encodeAddress , ethereumEncode } from '@polkadot/util-crypto' ;
4
4
import { hexToU8a , u8aToHex } from '@polkadot/util' ;
5
- import { HexString } from './payloads' ;
5
+ import { EthereumKeyPair , HexString } from './payloads' ;
6
+ import { ethers } from 'ethers' ;
7
+
8
+ /**
9
+ * Creates a Random Ethereum key
10
+ */
11
+ export function createRandomKey ( ) : EthereumKeyPair {
12
+ const k = ethers . Wallet . createRandom ( ) ;
13
+ return {
14
+ publicKey : k . publicKey ,
15
+ privateKey : k . privateKey ,
16
+ address : {
17
+ ethereumAddress : k . address ,
18
+ unifiedAddress : getUnified32BytesAddress ( k . address ) ,
19
+ unifiedAddressSS58 : getSS58AccountFromEthereumAccount ( k . address ) ,
20
+ } ,
21
+ mnemonic : k . mnemonic ?. phrase ?? '' ,
22
+ } as EthereumKeyPair ;
23
+ }
6
24
7
25
/**
8
26
* Create a partial KeyringPair from an Ethereum address
@@ -36,12 +54,8 @@ export function getUnifiedAddress(pair: KeyringPair): string {
36
54
*/
37
55
export function getUnifiedPublicKey ( pair : KeyringPair ) : Uint8Array {
38
56
if ( 'ethereum' === pair . type ) {
39
- const ethAddressBytes = hexToU8a ( ethereumEncode ( pair . publicKey ) ) ;
40
- const suffix = new Uint8Array ( 12 ) . fill ( 0xee ) ;
41
- const result = new Uint8Array ( 32 ) ;
42
- result . set ( ethAddressBytes , 0 ) ;
43
- result . set ( suffix , 20 ) ;
44
- return result ;
57
+ const unifiedHex = getUnified32BytesAddress ( u8aToHex ( pair . publicKey ) ) ;
58
+ return hexToU8a ( unifiedHex ) ;
45
59
}
46
60
if ( pair . type === 'ecdsa' ) {
47
61
throw new Error ( 'Ecdsa key type is not supported and it should be replaced with ethereum ones!' ) ;
@@ -68,3 +82,12 @@ export function getSS58AccountFromEthereumAccount(accountId20Hex: string): strin
68
82
result . set ( suffix , 20 ) ;
69
83
return encodeAddress ( result ) ;
70
84
}
85
+
86
+ function getUnified32BytesAddress ( ethAddressOrPublicKey : string ) : HexString {
87
+ const ethAddressBytes = hexToU8a ( ethereumEncode ( ethAddressOrPublicKey ) ) ;
88
+ const suffix = new Uint8Array ( 12 ) . fill ( 0xee ) ;
89
+ const result = new Uint8Array ( 32 ) ;
90
+ result . set ( ethAddressBytes , 0 ) ;
91
+ result . set ( suffix , 20 ) ;
92
+ return u8aToHex ( result ) ;
93
+ }
0 commit comments