Created
January 23, 2022 18:31
-
-
Save manelio/17f7561961c4be5fe72430c8ce758983 to your computer and use it in GitHub Desktop.
Convert address from EIP-55 to Bech32
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
| // CommonJS CLI version | |
| const { bech32 } = require('bech32'); | |
| const { toChecksumAddress } = require('web3-utils'); | |
| const { | |
| decode: bech32Decode, | |
| encode: bech32Encode, | |
| fromWords: bech32FromWords, | |
| toWords: bech32ToWords | |
| } = bech32 | |
| function makeBech32Encoder(prefix, limit) { | |
| return (data) => { | |
| if (data.substring(0, 2) !== '0x') { | |
| throw Error('Unrecognised address format'); | |
| } | |
| return bech32Encode(prefix, bech32ToWords(data), limit) | |
| } | |
| } | |
| function makeBech32Decoder(currentPrefix, limit) { | |
| return (data) => { | |
| const { prefix, words } = bech32Decode(data, limit); | |
| if (prefix !== currentPrefix) { | |
| throw Error('Unrecognised address format'); | |
| } | |
| return toChecksumAddress(Buffer.from(bech32FromWords(words)).toString('hex')); | |
| }; | |
| } | |
| const bech32Chain = (name, coinType, prefix, limit) => ({ | |
| coinType, | |
| decoder: makeBech32Decoder(prefix, limit), | |
| encoder: makeBech32Encoder(prefix, limit), | |
| name, | |
| }); | |
| const address = process.env.ADDRESS || ''; | |
| const { encoder, decoder } = bech32Chain('L1', 29, 'genesis') | |
| console.log(encoder(Buffer.from(address.substring(2), "hex"))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment