Skip to content

Commit

Permalink
feat: Support IntegerType for unit conversions
Browse files Browse the repository at this point in the history
  • Loading branch information
aryzing committed Dec 4, 2024
1 parent fd0bf26 commit fe26977
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
10 changes: 6 additions & 4 deletions packages/transactions/src/units.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { IntegerType, intToBigInt } from '@stacks/common';

export const MICROSTX_IN_STX = 1_000_000;

/**
Expand All @@ -9,8 +11,8 @@ export const MICROSTX_IN_STX = 1_000_000;
* microStxToStx(1000000n); // 1n
* ```
*/
export function microStxToStx(amountInMicroStx: number): number {
return amountInMicroStx / MICROSTX_IN_STX;
export function microStxToStx(amountInMicroStx: IntegerType): number {
return Number(intToBigInt(amountInMicroStx)) / MICROSTX_IN_STX;
}

/**
Expand All @@ -22,6 +24,6 @@ export function microStxToStx(amountInMicroStx: number): number {
* stxToMicroStx(1); // 1000000
* ```
*/
export function stxToMicroStx(amountInStx: number): number {
return amountInStx * MICROSTX_IN_STX;
export function stxToMicroStx(amountInStx: IntegerType): number {
return Number(intToBigInt(amountInStx)) * MICROSTX_IN_STX;
}
28 changes: 28 additions & 0 deletions packages/transactions/tests/units.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,45 @@ test(stxToMicroStx.name, () => {
expect(stxToMicroStx(1.23)).toBe(1230000);
expect(stxToMicroStx(0.000001)).toBe(1);

expect(stxToMicroStx('1')).toBe(1000000);
expect(stxToMicroStx('1.23')).toBe(1230000);
expect(stxToMicroStx('0.000001')).toBe(1);

expect(stxToMicroStx(1n)).toBe(1000000);

expect(stxToMicroStx(-1)).toBe(-1000000);
expect(stxToMicroStx(-2.34)).toBe(-2340000);
expect(stxToMicroStx(-0.000001)).toBe(-1);

expect(stxToMicroStx('-1')).toBe(-1000000);
expect(stxToMicroStx('-2.34')).toBe(-2340000);
expect(stxToMicroStx('-0.000001')).toBe(-1);

expect(stxToMicroStx(-1n)).toBe(-1000000);
});

test(microStxToStx.name, () => {
expect(microStxToStx(1000000)).toBe(1);
expect(microStxToStx(1230000)).toBe(1.23);
expect(microStxToStx(1)).toBe(0.000001);

expect(microStxToStx('1000000')).toBe(1);
expect(microStxToStx('1230000')).toBe(1.23);
expect(microStxToStx('1')).toBe(0.000001);

expect(microStxToStx(1000000n)).toBe(1);
expect(microStxToStx(1230000n)).toBe(1.23);
expect(microStxToStx(1n)).toBe(0.000001);

expect(microStxToStx(-1000000)).toBe(-1);
expect(microStxToStx(-2340000)).toBe(-2.34);
expect(microStxToStx(-1)).toBe(-0.000001);

expect(microStxToStx('-1000000')).toBe(-1);
expect(microStxToStx('-2340000')).toBe(-2.34);
expect(microStxToStx('-1')).toBe(-0.000001);

expect(microStxToStx(-1000000n)).toBe(-1);
expect(microStxToStx(-2340000n)).toBe(-2.34);
expect(microStxToStx(-1n)).toBe(-0.000001);
});

0 comments on commit fe26977

Please sign in to comment.