From fa2b7e18e5d3b92dd36e31fa1e357bd5695ed275 Mon Sep 17 00:00:00 2001 From: janniks Date: Thu, 18 Jul 2024 17:34:37 +0200 Subject: [PATCH] feat: Add STX unit helper methods --- packages/transactions/src/units.ts | 27 +++++++++++++++++++++++ packages/transactions/tests/units.test.ts | 21 ++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 packages/transactions/src/units.ts create mode 100644 packages/transactions/tests/units.test.ts diff --git a/packages/transactions/src/units.ts b/packages/transactions/src/units.ts new file mode 100644 index 000000000..2c843c4bf --- /dev/null +++ b/packages/transactions/src/units.ts @@ -0,0 +1,27 @@ +export const MICROSTX_IN_STX = 1_000_000; + +/** + * Convert μSTX (micro-STX) to STX denomination. + * `1 STX = 1,000,000 μSTX` + * + * @example + * ```ts + * microStxToStx(1000000n); // 1n + * ``` + */ +export function microStxToStx(amountInMicroStx: number): number { + return amountInMicroStx / MICROSTX_IN_STX; +} + +/** + * Convert STX to μSTX (micro-STX) denomination. + * `1 STX = 1,000,000 μSTX` + * + * @example + * ```ts + * stxToMicroStx(1); // 1000000 + * ``` + */ +export function stxToMicroStx(amountInStx: number): number { + return amountInStx * MICROSTX_IN_STX; +} diff --git a/packages/transactions/tests/units.test.ts b/packages/transactions/tests/units.test.ts new file mode 100644 index 000000000..c2013acf8 --- /dev/null +++ b/packages/transactions/tests/units.test.ts @@ -0,0 +1,21 @@ +import { microStxToStx, stxToMicroStx } from '../src/units'; + +test(stxToMicroStx.name, () => { + expect(stxToMicroStx(1)).toBe(1000000); + expect(stxToMicroStx(1.23)).toBe(1230000); + expect(stxToMicroStx(0.000001)).toBe(1); + + expect(stxToMicroStx(-1)).toBe(-1000000); + expect(stxToMicroStx(-2.34)).toBe(-2340000); + expect(stxToMicroStx(-0.000001)).toBe(-1); +}); + +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(-2340000)).toBe(-2.34); + expect(microStxToStx(-1)).toBe(-0.000001); +});