@@ -14,7 +14,7 @@ import {
1414 PrivateKeyEncoding ,
1515} from '@metamask/keyring-api' ;
1616import type { AccountId } from '@metamask/keyring-utils' ;
17- import type { Hex , Json } from '@metamask/utils' ;
17+ import { add0x , type Hex , type Json } from '@metamask/utils' ;
1818import { Mutex } from 'async-mutex' ;
1919
2020// eslint-disable-next-line @typescript-eslint/naming-convention
@@ -37,7 +37,7 @@ const simpleKeyringV2Capabilities: KeyringCapabilities = {
3737 scopes : [ EthScope . Eoa ] ,
3838 privateKey : {
3939 importFormats : [
40- { encoding : PrivateKeyEncoding . Hexadecimal , type : 'eip155:eoa' } ,
40+ { encoding : PrivateKeyEncoding . Hexadecimal , type : EthAccountType . Eoa } ,
4141 ] ,
4242 exportFormats : [ { encoding : PrivateKeyEncoding . Hexadecimal } ] ,
4343 } ,
@@ -152,20 +152,30 @@ export class SimpleKeyringV2
152152 ) ;
153153 }
154154
155+ // Get current addresses before import
156+ const addressesBefore = await this . inner . getAccounts ( ) ;
157+ const addressSetBefore = new Set ( addressesBefore ) ;
158+
155159 // Get current accounts to preserve them
156160 const currentAccounts = await this . inner . serialize ( ) ;
157161
158162 // Import the new private key by deserializing with all accounts
159163 await this . inner . deserialize ( [ ...currentAccounts , privateKey ] ) ;
160164
161- // Get the address of the newly added account
162- const allAddresses = await this . inner . getAccounts ( ) ;
163- const newAddress = allAddresses [ allAddresses . length - 1 ] ;
165+ // Get addresses after import and find the newly added one
166+ const addressesAfter = await this . inner . getAccounts ( ) ;
167+
168+ // Find the new address by diffing the two sets
169+ const newAddresses = addressesAfter . filter (
170+ ( addr ) => ! addressSetBefore . has ( addr ) ,
171+ ) ;
164172
165- if ( ! newAddress ) {
173+ if ( newAddresses . length !== 1 || ! newAddresses [ 0 ] ) {
166174 throw new Error ( 'Failed to import private key' ) ;
167175 }
168176
177+ const newAddress = newAddresses [ 0 ] ;
178+
169179 // Create and return the new KeyringAccount
170180 const newAccount = this . #createKeyringAccount( newAddress ) ;
171181 return [ newAccount ] ;
@@ -214,10 +224,12 @@ export class SimpleKeyringV2
214224 const privateKeyHex = await this . inner . exportAccount (
215225 this . toHexAddress ( account . address ) ,
216226 ) ;
227+ // Sanitize private key format
228+ const privateKey = add0x ( privateKeyHex ) ;
217229
218230 const exported : ExportedAccount = {
219231 type : 'private-key' ,
220- privateKey : `0x ${ privateKeyHex } ` ,
232+ privateKey,
221233 encoding : PrivateKeyEncoding . Hexadecimal ,
222234 } ;
223235
0 commit comments