Add apiToBigInt

This commit is contained in:
Simon Warta 2022-06-22 15:42:25 +02:00
parent 6a173a9d1f
commit 03835af2d4
2 changed files with 56 additions and 0 deletions

View File

@ -0,0 +1,40 @@
import { apiToBigInt } from "./inthelpers";
describe("inthelpers", () => {
describe("apiToBigInt", () => {
it("works for positive an negative ints", () => {
expect(apiToBigInt("0")).toEqual(BigInt(0));
expect(apiToBigInt("1")).toEqual(BigInt(1));
expect(apiToBigInt("100")).toEqual(BigInt(100));
expect(apiToBigInt("-1")).toEqual(BigInt(-1));
expect(apiToBigInt("-100")).toEqual(BigInt(-100));
expect(apiToBigInt("9007199254740991")).toEqual(BigInt(9007199254740991));
expect(apiToBigInt("-9007199254740991")).toEqual(BigInt(-9007199254740991));
// uint64 max
expect(apiToBigInt("18446744073709551615")).toEqual(BigInt("18446744073709551615"));
// int64 min/max
expect(apiToBigInt("-9223372036854775808")).toEqual(BigInt("-9223372036854775808"));
expect(apiToBigInt("9223372036854775807")).toEqual(BigInt("9223372036854775807"));
});
it("throws for ill-formatted inputs", () => {
// empty
expect(() => apiToBigInt("")).toThrowError(/invalid string format/i);
expect(() => apiToBigInt("-")).toThrowError(/invalid string format/i);
// non decimal representation
expect(() => apiToBigInt("0x0")).toThrowError(/invalid string format/i);
expect(() => apiToBigInt("0x01")).toThrowError(/invalid string format/i);
expect(() => apiToBigInt("0x")).toThrowError(/invalid string format/i);
// decimal points
expect(() => apiToBigInt("1.0")).toThrowError(/invalid string format/i);
// Invalid dashes
expect(() => apiToBigInt("1-")).toThrowError(/invalid string format/i);
expect(() => apiToBigInt("--1")).toThrowError(/invalid string format/i);
expect(() => apiToBigInt("1-1")).toThrowError(/invalid string format/i);
expect(() => apiToBigInt("-1-1")).toThrowError(/invalid string format/i);
});
});
});

View File

@ -1,5 +1,7 @@
import { Int53 } from "@cosmjs/math";
import { assertString } from "./tendermint34/encodings";
/**
* Takes an integer value from the Tendermint RPC API and
* returns it as number.
@ -11,6 +13,20 @@ export function apiToSmallInt(input: string | number): number {
return asInt.toNumber();
}
/**
* Takes an integer value from the Tendermint RPC API and
* returns it as BigInt.
*
* This supports the full uint64 and int64 ranges.
*/
export function apiToBigInt(input: string): bigint {
assertString(input); // Runtime check on top of TypeScript just to be safe for semi-trusted API types
if (!input.match(/^-?[0-9]+$/)) {
throw new Error("Invalid string format");
}
return BigInt(input);
}
/**
* Takes an integer in the safe integer range and returns
* a string representation to be used in the Tendermint RPC API.