Skip to content

Commit

Permalink
use amount.Amount type to store balances
Browse files Browse the repository at this point in the history
  • Loading branch information
artursapek committed Nov 5, 2024
1 parent d89d701 commit e13a839
Show file tree
Hide file tree
Showing 31 changed files with 205 additions and 505 deletions.
4 changes: 2 additions & 2 deletions wormhole-connect/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import sui from '@wormhole-foundation/sdk/sui';
import cosmwasm from '@wormhole-foundation/sdk/cosmwasm';
import algorand from '@wormhole-foundation/sdk/algorand';
import RouteOperator from 'routes/operator';
import { getTokenDecimals, getWrappedTokenId } from 'utils';
import { getTokenDecimals, getWrappedToken } from 'utils';
import { CHAIN_ORDER } from './constants';
import { getTokenBridgeWrappedTokenAddressSync } from 'utils/sdkv2';
import { createUiConfig } from './ui';
Expand Down Expand Up @@ -229,7 +229,7 @@ export async function newWormholeContextV2(): Promise<WormholeV2<Network>> {
const fa = getTokenBridgeWrappedTokenAddressSync(token, chain);
if (fa) {
tokenV2.address = fa.toString();
tokenV2.decimals = getTokenDecimals(chain, getWrappedTokenId(token));
tokenV2.decimals = getTokenDecimals(chain, getWrappedToken(token));
} else {
continue;
}
Expand Down
28 changes: 11 additions & 17 deletions wormhole-connect/src/hooks/useAmountValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type HookReturn = {
};

type Props = {
balance?: string | null;
balance?: sdkAmount.Amount | null;
routes: RouteState[];
quotesMap: Record<string, QuoteResult | undefined>;
tokenSymbol: string;
Expand Down Expand Up @@ -50,36 +50,30 @@ export const useAmountValidation = (props: Props): HookReturn => {
[props.quotesMap],
);

const allRoutesFailed = useMemo(
() => props.routes.every((route) => !props.quotesMap[route.name]?.success),
[props.routes, props.quotesMap],
);
const allRoutesFailed = useMemo(() => {
if (Object.keys(props.quotesMap).length === 0) {
return false;
}

const numAmount = Number.parseFloat(amount);
return props.routes.every((route) => {
return props.quotesMap[route.name]?.success === false;
});
}, [props.routes, props.quotesMap]);

// Don't show errors when no amount is set or it's loading
if (!amount || !numAmount || props.disabled) {
if (!amount || props.disabled) {
return {};
}

// Input errors
if (Number.isNaN(numAmount)) {
return {
error: 'Amount must be a number.',
};
}

// Balance errors
if (props.balance) {
const balanceNum = Number.parseFloat(props.balance.replaceAll(',', ''));
if (numAmount > balanceNum) {
if (sdkAmount.units(amount) > sdkAmount.units(props.balance)) {
return {
error: 'Amount exceeds available balance.',
};
}
}

// All quotes fail.
if (allRoutesFailed) {
if (minAmount) {
const formattedAmount = sdkAmount.display(minAmount);
Expand Down
8 changes: 4 additions & 4 deletions wormhole-connect/src/hooks/useComputeFees.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { Chain, finality } from '@wormhole-foundation/sdk-base';
import { Chain, finality, amount as sdkAmount } from '@wormhole-foundation/sdk';

import config from 'config';

Expand All @@ -15,7 +15,7 @@ type Props = {
destChain: Chain | undefined;
destToken: string;
route?: string;
amount: string;
amount: sdkAmount.Amount;
toNativeToken: number;
};

Expand Down Expand Up @@ -90,8 +90,8 @@ const useComputeFees = (props: Props): returnProps => {

const receiveAmount = await config.routes
.get(route)
.computeReceiveAmountWithFees(
Number.parseFloat(amount),
.computeReceiveAmount(
amount,
sourceToken,
destToken,
sourceChain,
Expand Down
9 changes: 1 addition & 8 deletions wormhole-connect/src/hooks/useComputeQuote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type Props = {
destChain: Chain | undefined;
destToken: string;
route?: string;
amount: string;
amount: sdkAmount.Amount;
toNativeToken: number;
};

Expand Down Expand Up @@ -54,13 +54,6 @@ const useComputeQuote = (props: Props): returnProps => {
try {
setIsFetching(true);

if (Number.isNaN(Number.parseFloat(amount))) {
dispatch(setReceiveAmount('0'));
dispatch(setReceiveNativeAmt(0));
dispatch(setRelayerFee(undefined));
return;
}

const quote = (
await config.routes.getQuotes([route], {
amount,
Expand Down
2 changes: 1 addition & 1 deletion wormhole-connect/src/hooks/useFetchSupportedRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const useFetchSupportedRoutes = (): void => {
const [debouncedAmount] = useDebounce(amount, 500);

useEffect(() => {
if (!fromChain || !toChain || !token || !destToken) {
if (!fromChain || !toChain || !token || !destToken || !debouncedAmount) {
dispatch(setRoutes([]));
return;
}
Expand Down
21 changes: 10 additions & 11 deletions wormhole-connect/src/hooks/useGetTokenBalances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ import { useEffect, useState } from 'react';
import { accessBalance, Balances, updateBalances } from 'store/transferInput';
import config, { getWormholeContextV2 } from 'config';
import { TokenConfig } from 'config/types';
import { formatAmount } from 'utils/amount';
import { chainToPlatform } from '@wormhole-foundation/sdk-base';
import { getTokenBridgeWrappedTokenAddress } from 'utils/sdkv2';
import { Chain, TokenAddress } from '@wormhole-foundation/sdk';
import { Chain, TokenAddress, amount } from '@wormhole-foundation/sdk';
import { getTokenDecimals } from 'utils';

// TODO: This hook shouldn't format amounts
// Instead the view should format and render accordingly
const useGetTokenBalances = (
walletAddress: string,
chain: Chain | undefined,
Expand Down Expand Up @@ -75,8 +73,10 @@ const useGetTokenBalances = (
const tokenIdMapping: Record<string, TokenConfig> = {};
const tokenAddresses: string[] = [];
for (const tokenConfig of needsUpdate) {
const decimals = getTokenDecimals(chain, tokenConfig);

updatedBalances[tokenConfig.key] = {
balance: '0',
balance: amount.fromBaseUnits(0n, decimals),
lastUpdated: now,
};

Expand Down Expand Up @@ -126,13 +126,12 @@ const useGetTokenBalances = (

for (const tokenAddress in result) {
const tokenConfig = tokenIdMapping[tokenAddress];
const balance = result[tokenAddress];
let formatted: string | null = null;
if (balance !== null) {
formatted = formatAmount(chain, tokenConfig, balance);
}
const decimals = getTokenDecimals(chain, tokenConfig);
const bus = result[tokenAddress];
const balance = amount.fromBaseUnits(bus ?? 0n, decimals);

updatedBalances[tokenConfig.key] = {
balance: formatted,
balance,
lastUpdated: now,
};
}
Expand Down
10 changes: 5 additions & 5 deletions wormhole-connect/src/hooks/useRoutesQuotesBulk.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { amount as sdkAmount } from '@wormhole-foundation/sdk';
import { useState, useEffect, useMemo } from 'react';
import { useSelector } from 'react-redux';
import type { RootState } from 'store';
Expand All @@ -19,7 +20,7 @@ type Params = {
sourceToken: string;
destChain?: Chain;
destToken: string;
amount: string;
amount?: sdkAmount.Amount;
nativeGas: number;
};

Expand Down Expand Up @@ -62,8 +63,7 @@ const useRoutesQuotesBulk = (routes: string[], params: Params): HookReturn => {
!params.sourceChain ||
!params.sourceToken ||
!params.destChain ||
!params.destToken ||
!parseFloat(params.amount)
!params.destToken
) {
return;
}
Expand Down Expand Up @@ -127,7 +127,7 @@ const useRoutesQuotesBulk = (routes: string[], params: Params): HookReturn => {
const quote = quotesMap[name];
if (quote !== undefined && quote.success) {
const usdValueOut = calculateUSDPriceRaw(
amount.whole(quote.destinationToken.amount),
quote.destinationToken.amount,
usdPrices.data,
destTokenConfig,
);
Expand Down Expand Up @@ -175,7 +175,7 @@ const useRoutesQuotesBulk = (routes: string[], params: Params): HookReturn => {
sourceTokenConfig,
);
const approxOutputUsdValue = calculateUSDPriceRaw(
amount.display(mayanQuote.destinationToken.amount),
mayanQuote.destinationToken.amount,
usdPrices.data,
config.tokens[params.destToken],
);
Expand Down
3 changes: 2 additions & 1 deletion wormhole-connect/src/hooks/useSortedRoutesWithQuotes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export const useSortedRoutesWithQuotes = (): HookReturn => {
destToken,
preferredRouteName,
} = useSelector((state: RootState) => state.transferInput);

const { toNativeToken } = useSelector((state: RootState) => state.relay);

const supportedRoutes = useMemo(
Expand All @@ -55,7 +56,7 @@ export const useSortedRoutesWithQuotes = (): HookReturn => {
destToken,
nativeGas: toNativeToken,
}),
[parseFloat(amount), fromChain, token, toChain, destToken, toNativeToken],
[amount, fromChain, token, toChain, destToken, toNativeToken],
);

const { quotesMap, isFetching } = useRoutesQuotesBulk(
Expand Down
5 changes: 3 additions & 2 deletions wormhole-connect/src/hooks/useUSDamountGetter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { useCallback } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from 'store';
import { getTokenPrice } from 'utils';
import { amount as sdkAmount } from '@wormhole-foundation/sdk';

export const useUSDamountGetter = (): ((args: {
token: string;
amount: string;
amount: sdkAmount.Amount;
}) => number | undefined) => {
const {
usdPrices: { data },
Expand All @@ -15,7 +16,7 @@ export const useUSDamountGetter = (): ((args: {
return useCallback(
({ token, amount }) => {
const prices = data || {};
const numericAmount = Number(amount);
const numericAmount = sdkAmount.whole(amount);
const tokenPrice = Number(getTokenPrice(prices, config.tokens[token]));
const USDAmount = tokenPrice * numericAmount;

Expand Down
1 change: 0 additions & 1 deletion wormhole-connect/src/routes/index.ts

This file was deleted.

15 changes: 12 additions & 3 deletions wormhole-connect/src/routes/operator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import config from 'config';
import { TokenConfig } from 'config/types';

import { Chain, routes, TransactionId } from '@wormhole-foundation/sdk';
import {
Chain,
routes,
TransactionId,
amount as sdkAmount,
} from '@wormhole-foundation/sdk';

import SDKv2Route from './sdkv2';

Expand Down Expand Up @@ -37,7 +42,7 @@ export interface QuoteParams {
sourceToken: string;
destChain: Chain;
destToken: string;
amount: string;
amount: sdkAmount.Amount;
nativeGas: number;
}

Expand Down Expand Up @@ -245,7 +250,11 @@ class QuoteCache {
}

quoteParamsKey(routeName: string, params: QuoteParams): string {
return `${routeName}:${params.sourceChain}:${params.sourceToken}:${params.destChain}:${params.destToken}:${params.amount}:${params.nativeGas}`;
return `${routeName}:${params.sourceChain}:${params.sourceToken}:${
params.destChain
}:${params.destToken}:${sdkAmount.units(params.amount)}:${
params.nativeGas
}`;
}

get(routeName: string, params: QuoteParams): QuoteResult | null {
Expand Down
Loading

0 comments on commit e13a839

Please sign in to comment.