Skip to content

Commit

Permalink
chore: add unitToPlanck tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rossbulat committed Oct 31, 2024
1 parent 373f925 commit 9e9c17a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
13 changes: 10 additions & 3 deletions library/utils/src/unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,16 @@ export const unitToPlanck = (

// Process the fractional part if it exists
if (fractionalPart) {
// Scale the fractional part by padding to the full number of decimal places
const paddedFractional = fractionalPart.padEnd(units, "0");
const fractionalValue = BigInt(paddedFractional);
let fractionalValue: bigint;

if (fractionalPart.length > units) {
// If fractional part exceeds units, truncate it
fractionalValue = BigInt(fractionalPart.slice(0, units));
} else {
// Otherwise, pad the fractional part to match units
fractionalValue = BigInt(fractionalPart.padEnd(units, "0"));
}

bigIntValue += fractionalValue;
}

Expand Down
10 changes: 10 additions & 0 deletions library/utils/tests/unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ describe("unitToPlanck", () => {
expect(result).toEqual(10000000n);
});

test("Invalid when units are smaller than decimals - returns zero.", () => {
const result = fn.unitToPlanck("0.0001", 3);
expect(result).toEqual(0n);
});

test("Valid when unit value is decimals + 1.", () => {
const result = fn.unitToPlanck("0.0001", 4);
expect(result).toEqual(1n);
});

test("should return valid planck value for a string input", () => {
const result = fn.unitToPlanck("5", 6);
expect(result).toEqual(5000000n);
Expand Down

0 comments on commit 9e9c17a

Please sign in to comment.