Skip to content

Commit b0512bc

Browse files
committed
Fix failing test case
1 parent 9d314e1 commit b0512bc

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

packages/sdk/src/plt/TokenAmount.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,18 @@ export function instanceOf(value: unknown): value is TokenAmount {
146146
return value instanceof TokenAmount;
147147
}
148148

149+
/**
150+
* Get decimal places from a Big {@linkcode Big}.
151+
*
152+
* @param big The number to get the decimal places.
153+
* @returns {number} The number of decimal places in above number.
154+
*/
155+
function getDecimalPlaces(big: Big): number {
156+
// `b.c` is an array of single digits (coefficient), `b.e` is the exponent (0-based index of highest digit)
157+
const decimals = big.c.length - (big.e + 1);
158+
return decimals > 0 ? decimals : 0;
159+
}
160+
149161
/**
150162
* Creates a TokenAmount from a number, string, {@linkcode Big}, or bigint.
151163
*
@@ -163,7 +175,7 @@ export function fromDecimal(amount: BigSource | bigint, decimals: number): Token
163175
}
164176

165177
const bigAmount = Big(parsed);
166-
const parsedDecimals = bigAmount.toFixed(0).split('.')[1]?.length ?? 0;
178+
const parsedDecimals = getDecimalPlaces(bigAmount);
167179
if (parsedDecimals > decimals) {
168180
throw new Error('The amount has more decimal places than the specified decimals.');
169181
}

packages/sdk/test/ci/plt/TokenAmount.test.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,7 @@ describe('PLT TokenAmount', () => {
1212
expect(TokenAmount.fromDecimal('15.002456687544126548', 18)).toEqual(
1313
TokenAmount.create(15002456687544126548n, 18)
1414
);
15-
expect(TokenAmount.fromDecimal(MAX_U64, 0)).toEqual(
16-
TokenAmount.create(MAX_U64, 0)
17-
);
15+
expect(TokenAmount.fromDecimal(MAX_U64, 0)).toEqual(TokenAmount.create(MAX_U64, 0));
1816
});
1917

2018
test('Parses large decimal values correctly', () => {
@@ -38,11 +36,12 @@ describe('PLT TokenAmount', () => {
3836
expect(() => TokenAmount.fromDecimal(99999999999999999999999999n, 1)).toThrow(
3937
TokenAmount.Err.exceedsMaxValue()
4038
);
41-
4239
});
4340

4441
test('Token amounts with more decimals than specified throws', () => {
45-
expect(() => TokenAmount.fromDecimal('1.000003', 0)).toThrow('The amount has more decimal places than the specified decimals.');
42+
expect(() => TokenAmount.fromDecimal('1.000003', 0)).toThrow(
43+
'The amount has more decimal places than the specified decimals.'
44+
);
4645
});
4746

4847
test('Returns expected amount', () => {

0 commit comments

Comments
 (0)