From 21699c314ee4f00f3ba19de2909d722dafee65d8 Mon Sep 17 00:00:00 2001 From: Mimi Tran <80493680+mimi-imtbl@users.noreply.github.com> Date: Thu, 26 Sep 2024 15:42:54 +1000 Subject: [PATCH] [NO CHANGELOG][Add Funds Widget] Add convertTokenBalanceToUsd function (#2234) --- .../functions/convertTokenBalanceToUsd.ts | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 packages/checkout/widgets-lib/src/widgets/add-funds/functions/convertTokenBalanceToUsd.ts diff --git a/packages/checkout/widgets-lib/src/widgets/add-funds/functions/convertTokenBalanceToUsd.ts b/packages/checkout/widgets-lib/src/widgets/add-funds/functions/convertTokenBalanceToUsd.ts new file mode 100644 index 0000000000..50a529f667 --- /dev/null +++ b/packages/checkout/widgets-lib/src/widgets/add-funds/functions/convertTokenBalanceToUsd.ts @@ -0,0 +1,20 @@ +import { TokenBalance } from '@0xsquid/sdk/dist/types'; +import { RouteResponse } from '@0xsquid/squid-types'; +import { ethers } from 'ethers'; + +export function convertTokenBalanceToUsd( + balance: TokenBalance, + routeResponse: RouteResponse, +): number { + const { usdPrice } = routeResponse.route.estimate.fromToken; + + if (!usdPrice) { + throw new Error('USD conversion rate not available'); + } + + const tokenBalance = ethers.utils.formatUnits(balance.balance, balance.decimals); + + const usdBalance = parseFloat(tokenBalance) * usdPrice; + + return usdBalance; +}