From 6fb97a561423367178c7e404b0e728f50a933ad8 Mon Sep 17 00:00:00 2001 From: Pavel Prichodko <14926950+prichodko@users.noreply.github.com> Date: Thu, 2 Jun 2022 12:10:35 +0200 Subject: [PATCH] add private key to address function --- .../src/utils/private-key-to-address.test.ts | 10 ++++++++++ .../status-js/src/utils/private-key-to-address.ts | 13 +++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 packages/status-js/src/utils/private-key-to-address.test.ts create mode 100644 packages/status-js/src/utils/private-key-to-address.ts diff --git a/packages/status-js/src/utils/private-key-to-address.test.ts b/packages/status-js/src/utils/private-key-to-address.test.ts new file mode 100644 index 0000000..b5ffab4 --- /dev/null +++ b/packages/status-js/src/utils/private-key-to-address.test.ts @@ -0,0 +1,10 @@ +import { privateKeyToAddress } from './private-key-to-address' + +describe('privateKeyToAddress', () => { + it('should return public address', () => { + const privateKey = + '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709' + const address = privateKeyToAddress(privateKey) + expect(address).toEqual('0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01') + }) +}) diff --git a/packages/status-js/src/utils/private-key-to-address.ts b/packages/status-js/src/utils/private-key-to-address.ts new file mode 100644 index 0000000..e32f780 --- /dev/null +++ b/packages/status-js/src/utils/private-key-to-address.ts @@ -0,0 +1,13 @@ +import { keccak256 } from 'ethereum-cryptography/keccak' +import { getPublicKey } from 'ethereum-cryptography/secp256k1' +import { bytesToHex } from 'ethereum-cryptography/utils' + +export function privateKeyToAddress(privateKey: string): string { + const publicKey = getPublicKey(privateKey) + const publicKeyWithoutPrefix = publicKey.slice(1) // uncompressed public key has 04 prefix + const hash = keccak256(publicKeyWithoutPrefix) + const address = bytesToHex(hash.slice(12)) + + // TODO: add checksum + return address +}