Skip to content

Commit

Permalink
#350: Support extremely large numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
cdc-Hitesh committed Nov 2, 2021
1 parent 6e30524 commit 1810ea7
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
13 changes: 12 additions & 1 deletion lib/src/cosmos/coins.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,23 @@ describe('coins', function () {
});
});

it('works for high value amount', function () {
expect(coin('100000000234500000000000000', 'utoken')).to.deep.eq({
amount: '100000000234500000000000000',
denom: 'utoken',
});
expect(coin('100000000234500000000000000123123123123', 'utoken')).to.deep.eq({
amount: '100000000234500000000000000123123123123',
denom: 'utoken',
});
});

it('throws for non-safe-integer values', function () {
expect(() => coin('1.23', 'utoken')).to.throw();
expect(() => coin('123.0', 'utoken')).to.throw();
expect(() => coin('NaN', 'utoken')).to.throw();
expect(() => coin(Number.POSITIVE_INFINITY.toString(), 'utoken')).to.throw();
expect(() => coin((Number.MAX_SAFE_INTEGER + 1).toString(), 'utoken')).to.throw();
expect(() => coin((Number.MAX_SAFE_INTEGER + 1).toString(), 'utoken')).to.not.throw();
});

it('throws for negative values', function () {
Expand Down
16 changes: 14 additions & 2 deletions lib/src/cosmos/coins.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { Uint53 } from '@cosmjs/math';
import { Big } from 'big.js';

// Decimal places
Big.DP = 100;

// Precision quantity after exponent format starts
Big.PE = 100;

export interface Coin {
readonly denom: string;
Expand All @@ -7,7 +13,13 @@ export interface Coin {

/** Creates a coin */
export function coin(amount: string, denom: string): Coin {
return { amount: Uint53.fromString(amount).toString(), denom };
const amountInBN = new Big(amount);

// Disallow decimal and negative integers
if (amountInBN.cmp(0) === -1 || amount.includes('.')) {
throw new Error('Invalid amount string.');
}
return { amount: amountInBN.toString(), denom };
}

/** Creates a list of coins with one element */
Expand Down

0 comments on commit 1810ea7

Please sign in to comment.