bigNumberify 0x fix #80

This commit is contained in:
Miguel Mota
2024-07-01 20:12:03 -07:00
parent 5775c61a9f
commit cc22a44b98
2 changed files with 19 additions and 4 deletions

View File

@@ -201,7 +201,7 @@ export class Base {
if (value.startsWith('0x') && Base.isHexString(value)) {
// Remove '0x' and ensure even-length hex string
const hexString = value.replace('0x', '')
const paddedHexString = hexString.length % 2 ? '0' + hexString : hexString
const paddedHexString = hexString.length % 2 ? '0' + hexString : (hexString || '0')
return BigInt('0x' + paddedHexString)
}
return BigInt(value)
@@ -210,14 +210,14 @@ export class Base {
if (Buffer.isBuffer(value)) {
// Convert buffer to hex string and ensure even-length hex string
const hexString = value.toString('hex')
const paddedHexString = hexString.length % 2 ? '0' + hexString : hexString
const paddedHexString = hexString.length % 2 ? '0' + hexString : (hexString || '0')
return BigInt('0x' + paddedHexString)
}
if (value instanceof Uint8Array) {
// Convert Uint8Array to hex string and ensure even-length hex string
const hexString = Buffer.from(value).toString('hex')
const paddedHexString = hexString.length % 2 ? '0' + hexString : hexString
const paddedHexString = hexString.length % 2 ? '0' + hexString : (hexString || '0')
return BigInt('0x' + paddedHexString)
}

View File

@@ -33,15 +33,30 @@ test('bufferifyFn', t => {
})
test('bigNumberify', t => {
t.plan(4)
t.plan(8)
const base = new Base()
t.deepEqual(base.bigNumberify(123), BigInt(123))
t.deepEqual(base.bigNumberify(''), BigInt(0))
t.deepEqual(base.bigNumberify(0), BigInt(0))
t.deepEqual(base.bigNumberify('0x'), BigInt(0))
t.deepEqual(base.bigNumberify('0x0'), BigInt(0))
t.deepEqual(base.bigNumberify('0x123'), BigInt('0x123'))
t.deepEqual(base.bigNumberify(BigInt(123)), BigInt(123))
t.deepEqual(base.bigNumberify(new Uint8Array([123])), BigInt(123))
})
test('bufferToHex', t => {
t.plan(5)
const base = new Base()
t.deepEqual(base.bufferToHex(Buffer.alloc(0)), '0x')
t.deepEqual(base.bufferToHex(Buffer.from('')), '0x')
t.deepEqual(base.bufferToHex(Buffer.from('x')), '0x78')
t.deepEqual(base.bufferToHex(''), '0x')
t.deepEqual(base.bufferToHex(0), '0x')
})
test('binarySearch', t => {
t.plan(3)