Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix planckToUnit #348

Merged
merged 2 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions packages/utils/lib/unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,18 @@ export const remToUnit = (rem: string) =>
* @description
* Converts an on chain balance value in bigint planck to a decimal value in token unit
*/
export const planckToUnit = (val: bigint, units: number): number => {
if (units < 0) {
export const planckToUnit = (val?: bigint, units?: number): number => {
if (!val) {
throw new Error(`Value can not be undefined`)
}

if (!units || units < 0) {
throw new Error(`Argument out of range: ${units}`)
}
const str = val ? val.toString() : ""
const numb = str.slice(0, str.length - units)
const dec = str.slice(str.length - units)

const str = val.toString().padStart(units + 1, "0")
const numb = str.slice(0, -units)
const dec = str.slice(-units)
const result = Number(numb + "." + dec)
return !isNaN(result) ? result : 0
}
Expand Down
22 changes: 19 additions & 3 deletions packages/utils/tests/unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,22 @@ describe("Tests suite - planckToUnit Function", () => {
expect(result).toEqual(expectedOutput)
})

test("should correctly convert a BigInt to units", () => {
const inputValue = 100n
const units = 3
const expectedOutput = Number("0.1")
const result = fn.planckToUnit(inputValue, units)
expect(result).toEqual(expectedOutput)
})

test("should correctly convert a BigInt to units", () => {
const inputValue = 100n
const units = 9
const expectedOutput = Number("0.0000001")
const result = fn.planckToUnit(inputValue, units)
expect(result).toEqual(expectedOutput)
})

test("should throw error when negative units", () => {
const inputValue = 10000000n
const units = -2
Expand All @@ -29,9 +45,9 @@ describe("Tests suite - planckToUnit Function", () => {
test("should throw error when undefined value", () => {
const inputValue = undefined
const units = 2
const expectedOutput = Number("0")
const result = fn.planckToUnit(inputValue, units)
expect(result).toEqual(expectedOutput)
expect(() => fn.planckToUnit(inputValue, units)).toThrowError(
"Value can not be undefined"
)
})
})

Expand Down