From dec07c6c717767826828877de656e3ec5a7baeac Mon Sep 17 00:00:00 2001 From: fwx5618177 Date: Sat, 6 Apr 2024 16:30:49 +0800 Subject: [PATCH] feat: add new type to allow toBase58Check to get string in browser --- src/address.d.ts | 2 +- src/address.js | 3 ++- test/address.spec.ts | 6 ++++++ ts_src/address.ts | 5 +++-- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/address.d.ts b/src/address.d.ts index 6b5bc9c2a..092573392 100644 --- a/src/address.d.ts +++ b/src/address.d.ts @@ -36,7 +36,7 @@ export declare function fromBech32(address: string): Bech32Result; /** * encode address hash to base58 address with version */ -export declare function toBase58Check(hash: Buffer, version: number): string; +export declare function toBase58Check(hash: Buffer | string, version: number): string; /** * encode address hash to bech32 address with version and prefix */ diff --git a/src/address.js b/src/address.js index ad3ceeb1a..e69762311 100644 --- a/src/address.js +++ b/src/address.js @@ -83,9 +83,10 @@ exports.fromBech32 = fromBech32; * encode address hash to base58 address with version */ function toBase58Check(hash, version) { + hash = Buffer.isBuffer(hash) ? hash : Buffer.from(hash, 'hex'); (0, types_1.typeforce)( (0, types_1.tuple)(types_1.Hash160bit, types_1.UInt8), - arguments, + [hash, version], ); const payload = Buffer.allocUnsafe(21); payload.writeUInt8(version, 0); diff --git a/test/address.spec.ts b/test/address.spec.ts index 23c18b9f6..3ab06af31 100644 --- a/test/address.spec.ts +++ b/test/address.spec.ts @@ -101,6 +101,12 @@ describe('address', () => { assert.strictEqual(address, f.base58check); }); + + it('encodes ' + f.hash + ' (' + f.network + ')', () => { + const address = baddress.toBase58Check(f.hash, f.version); + + assert.strictEqual(address, f.base58check); + }); }); }); diff --git a/ts_src/address.ts b/ts_src/address.ts index cbd03da1f..3e8a1e7b7 100644 --- a/ts_src/address.ts +++ b/ts_src/address.ts @@ -116,8 +116,9 @@ export function fromBech32(address: string): Bech32Result { /** * encode address hash to base58 address with version */ -export function toBase58Check(hash: Buffer, version: number): string { - typeforce(tuple(Hash160bit, UInt8), arguments); +export function toBase58Check(hash: Buffer | string, version: number): string { + hash = Buffer.isBuffer(hash) ? hash : Buffer.from(hash, 'hex'); + typeforce(tuple(Hash160bit, UInt8), [hash, version]); const payload = Buffer.allocUnsafe(21); payload.writeUInt8(version, 0);