Thanks Buffalo Joe for the help!
There is a fromLegacyKeypair
helper function here, which is part of a lib called @solana/compat
.
Install with npm i @solana/compat@experimental
As Serban mentioned in the previous comment, it uses the importKey
method
/**
* Convert from a Legacy Web3 JS Keypair to a CryptoKeyPair
* @param keypair The Keypair to convert
* @returns A CryptoKeyPair
*/
export async function fromLegacyKeypair(keypair: Keypair, extractable?: boolean): Promise<CryptoKeyPair> {
const publicKey: CryptoKey = await crypto.subtle.importKey('raw', keypair.publicKey.toBytes(), 'Ed25519', true, [
'verify',
]);
const privateKeyBytesPkcs8 = addPkcs8Header(keypair.secretKey.slice(0, 32));
const privateKey: CryptoKey = await crypto.subtle.importKey(
'pkcs8',
privateKeyBytesPkcs8,
'Ed25519',
extractable ?? false,
['sign']
);
return {
privateKey,
publicKey,
} as CryptoKeyPair;
}
For example:
const secretKey = new Uint8Array([...]);
const legacyKeypair = Keypair.fromSecretKey(secretKey);
const cryptoKeypair = await fromLegacyKeypair(legacyKeypair);
It doesn't seem there is currently a helper function to convert bytes directly to a CryptoKeypair
, but the fromLegacyKeypair
helper function can be used as a reference.