Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/core/Base58.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,9 @@ export function toHex(value: string): Hex.Hex {
integer = integer + internal.alphabetToInteger[char]!
}

if (!pad) return `0x${integer.toString(16)}` as Hex.Hex
return `0x${'0'.repeat(pad * 2)}${integer.toString(16)}` as Hex.Hex
const body = integer === 0n ? '' : integer.toString(16)
if (!pad) return `0x${body}` as Hex.Hex
return `0x${'0'.repeat(pad * 2)}${body}` as Hex.Hex
}

export declare namespace toHex {
Expand Down
29 changes: 29 additions & 0 deletions src/core/_test/Base58.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ describe('fromHex', () => {
test('default', () => {
expect(Base58.fromHex('0x00000000287fb4cd')).toBe('1111233QC4')
})

test('leading zeros (all-zero value)', () => {
expect(Base58.fromHex('0x00')).toBe('1')
expect(Base58.fromHex('0x0000')).toBe('11')
expect(Base58.fromHex('0x000000')).toBe('111')
})

test('empty', () => {
expect(Base58.fromHex('0x')).toBe('')
})
})

describe('fromString', () => {
Expand Down Expand Up @@ -47,6 +57,15 @@ describe('toBytes', () => {
]
`)
})

test('leading zeros', () => {
expect(Base58.toBytes('1')).toStrictEqual(new Uint8Array([0]))
expect(Base58.toBytes('1112NEpo7TZRRrLZSi2U')).toStrictEqual(
new Uint8Array([
0, 0, 0, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33,
]),
)
})
})

describe('toHex', () => {
Expand All @@ -57,6 +76,16 @@ describe('toHex', () => {
'[Error: invalid base58 character: I]',
)
})

test('leading ones (all-zero value)', () => {
expect(Base58.toHex('1')).toBe('0x00')
expect(Base58.toHex('11')).toBe('0x0000')
expect(Base58.toHex('111')).toBe('0x000000')
})

test('empty', () => {
expect(Base58.toHex('')).toBe('0x')
})
})

describe('toString', () => {
Expand Down
3 changes: 2 additions & 1 deletion src/core/internal/base58.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export function from(value: Hex.Hex | Bytes.Bytes) {
let integer = (() => {
let hex = value
if (value instanceof Uint8Array) hex = Hex.fromBytes(bytes)
if (hex === '0x') return 0n
return BigInt(hex as string)
})()

Expand All @@ -87,7 +88,7 @@ export function from(value: Hex.Hex | Bytes.Bytes) {
result = integerToAlphabet[remainder] + result
}

while (bytes.length > 1 && bytes[0] === 0) {
while (bytes.length > 0 && bytes[0] === 0) {
result = '1' + result
bytes = bytes.slice(1)
}
Expand Down