Created
August 6, 2025 15:12
-
-
Save tranduybau/c0adcf5459a673468d0a6442d5f979bf to your computer and use it in GitHub Desktop.
generateAddressFromPrivateKey
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function generateAddressFromPrivateKey(privateKey: string, bech32Prefix: string): string { | |
| try { | |
| // Remove '0x' prefix if present | |
| const cleanPrivateKey = privateKey.startsWith('0x') ? privateKey.slice(2) : privateKey; | |
| // Convert private key to Uint8Array | |
| const privateKeyBytes = new Uint8Array(Buffer.from(cleanPrivateKey, 'hex')); | |
| // Generate public key from private key | |
| const publicKey = secp256k1.getPublicKey(privateKeyBytes); | |
| // Remove the first byte (compression flag) and get the actual public key | |
| const publicKeyBytes = publicKey.slice(1); | |
| // Generate address using SHA256 and RIPEMD160 | |
| const sha256Hash = sha256(publicKeyBytes); | |
| const ripemd160Hash = ripemd160(sha256Hash); | |
| // Encode to bech32 format | |
| const words = bech32.toWords(ripemd160Hash); | |
| const address = bech32.encode(bech32Prefix, words); | |
| if (!address) { | |
| throw new Error('Failed to encode bech32 address'); | |
| } | |
| return address; | |
| } catch (error: any) { | |
| console.error('Error generating STOC address:', error); | |
| throw new Error(`Failed to generate STOC address: ${error.message}`); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment