Skip to content

Commit

Permalink
add custom formatEther method
Browse files Browse the repository at this point in the history
  • Loading branch information
codespool committed Oct 1, 2024
1 parent 6d66cce commit 6778453
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
30 changes: 30 additions & 0 deletions src/lib/formatters.ts
Original file line number Diff line number Diff line change
@@ -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);
}
5 changes: 0 additions & 5 deletions src/token-utils.ts

This file was deleted.

0 comments on commit 6778453

Please sign in to comment.