Skip to content

Commit

Permalink
Add Bech32.encodeFromBytes. Fix encode type
Browse files Browse the repository at this point in the history
  • Loading branch information
paulmillr committed Sep 18, 2024
1 parent e64cdda commit 6b20a45
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
19 changes: 17 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -480,12 +480,13 @@ export interface Bech32 {
encode<Prefix extends string>(
prefix: Prefix,
words: number[] | Uint8Array,
limit: number | false
limit?: number | false
): `${Lowercase<Prefix>}1${string}`;
decode<Prefix extends string>(
str: `${Prefix}1${string}`,
limit?: number | false
): Bech32Decoded<Prefix>;
encodeFromBytes(prefix: string, bytes: Uint8Array): string;
decodeToBytes(str: string): Bech32DecodedWithArray;
decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded<string>;
fromWords(to: number[]): Uint8Array;
Expand All @@ -509,6 +510,7 @@ function genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {
): `${Lowercase<Prefix>}1${string}` {
if (typeof prefix !== 'string')
throw new Error(`bech32.encode prefix should be string, not ${typeof prefix}`);
if (words instanceof Uint8Array) words = Array.from(words);
if (!Array.isArray(words) || (words.length && typeof words[0] !== 'number'))
throw new Error(`bech32.encode words should be array of numbers, not ${typeof words}`);
if (prefix.length === 0) throw new TypeError(`Invalid prefix length ${prefix.length}`);
Expand Down Expand Up @@ -553,7 +555,20 @@ function genBech32(encoding: 'bech32' | 'bech32m'): Bech32 {
return { prefix, words, bytes: fromWords(words) };
}

return { encode, decode, decodeToBytes, decodeUnsafe, fromWords, fromWordsUnsafe, toWords };
function encodeFromBytes(prefix: string, bytes: Uint8Array) {
return encode(prefix, toWords(bytes));
}

return {
encode,
decode,
encodeFromBytes,
decodeToBytes,
decodeUnsafe,
fromWords,
fromWordsUnsafe,
toWords,
};
}

export const bech32: Bech32 = /* @__PURE__ */ genBech32('bech32');
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions test/bech32.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -383,4 +383,9 @@ should('toWords/toWordsUnsafe accept Uint8Array', () => {
assert.deepStrictEqual(words, [0, 0, 8, 18, 4, 12, 31, 31]);
});

should('encode accepts Uint8Array', () => {
const bytes = new Uint8Array([0, 0, 8, 18, 4, 12, 31, 31]);
assert.deepStrictEqual(bech32.encode('test', bytes), 'test1qqgjyvlld2nz37');
});

if (require.main === module) should.run();

0 comments on commit 6b20a45

Please sign in to comment.