tokens.ts 807 B

123456789101112131415161718192021222324252627
  1. export const DECIMALS = 6;
  2. export const tokensToString = (value: bigint): string => {
  3. const asStr = value.toString();
  4. const whole =
  5. asStr.length > DECIMALS ? asStr.slice(0, asStr.length - DECIMALS) : "0";
  6. const decimal =
  7. asStr.length > DECIMALS ? asStr.slice(asStr.length - DECIMALS) : asStr;
  8. const decimalPadded = decimal.padStart(DECIMALS, "0");
  9. const decimalTruncated = decimalPadded.replace(/0+$/, "");
  10. return [
  11. whole,
  12. ...(decimalTruncated === "" ? [] : [".", decimalTruncated]),
  13. ].join("");
  14. };
  15. export const stringToTokens = (value: string): bigint | undefined => {
  16. const [whole, decimal] = value.split(".");
  17. try {
  18. return BigInt(
  19. `${whole ?? "0"}${(decimal ?? "").slice(0, DECIMALS).padEnd(DECIMALS, "0")}`,
  20. );
  21. } catch {
  22. return undefined;
  23. }
  24. };