From 6778453452ce90542748413847bbab1341e3f7e5 Mon Sep 17 00:00:00 2001 From: codespool <4625220+codespool@users.noreply.github.com> Date: Tue, 1 Oct 2024 10:21:03 +0300 Subject: [PATCH] add custom formatEther method --- src/lib/formatters.ts | 30 ++++++++++++++++++++++++++++++ src/token-utils.ts | 5 ----- 2 files changed, 30 insertions(+), 5 deletions(-) create mode 100644 src/lib/formatters.ts delete mode 100644 src/token-utils.ts diff --git a/src/lib/formatters.ts b/src/lib/formatters.ts new file mode 100644 index 000000000..5fa5aa7db --- /dev/null +++ b/src/lib/formatters.ts @@ -0,0 +1,30 @@ + +import { BN } from "@polkadot/util"; +import { formatEther } from "viem"; + +export function formatEtherAsString(wei: bigint | string | BN): string { + let weiBigInt: bigint; + + if (typeof wei === "bigint") { + weiBigInt = wei; + } else if (typeof wei === "string") { + weiBigInt = BigInt(wei); + } else if (wei instanceof BN) { + weiBigInt = BigInt(wei.toString()); + } else { + throw new Error("Invalid input type"); + } + + return formatEther(weiBigInt); +} + +export function formatEtherAsNumber(wei: bigint | string | BN): number { + const etherBigInt = BigInt(formatEtherAsString(wei)); + const MAX_SAFE_INTEGER_BIGINT = BigInt(Number.MAX_SAFE_INTEGER); + + if (etherBigInt > MAX_SAFE_INTEGER_BIGINT || etherBigInt < -MAX_SAFE_INTEGER_BIGINT) { + throw new Error("Value is outside of safe integer bounds for JavaScript numbers"); + } + + return Number(etherBigInt); +} diff --git a/src/token-utils.ts b/src/token-utils.ts deleted file mode 100644 index 3d689f44d..000000000 --- a/src/token-utils.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { ethers } from 'ethers'; - -export const weiToToken = (wei: bigint): number => { - return Number(ethers.utils.formatEther(String(wei))); -};