diff --git a/library/utils/src/unit.ts b/library/utils/src/unit.ts index 45c1c44..e7e1c42 100644 --- a/library/utils/src/unit.ts +++ b/library/utils/src/unit.ts @@ -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; } diff --git a/library/utils/tests/unit.test.ts b/library/utils/tests/unit.test.ts index 7a43abc..b250ff7 100644 --- a/library/utils/tests/unit.test.ts +++ b/library/utils/tests/unit.test.ts @@ -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);