Skip to content

Commit

Permalink
fix comments and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Tbaut committed Sep 13, 2024
1 parent 8246da3 commit c348bf3
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
13 changes: 8 additions & 5 deletions packages/utils/lib/unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,19 @@ 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.toString().padStart(units + 1, '0')
// ^^^^^^^^^
const str = val.toString().padStart(units + 1, "0")
const numb = str.slice(0, -units)
const dec = str.slice(-units)
const result = Number(numb + '.' + dec)
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

0 comments on commit c348bf3

Please sign in to comment.