Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: use SDK amount.Amount type to store token amounts #2868

Open
wants to merge 3 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
29 changes: 11 additions & 18 deletions wormhole-connect/src/hooks/useAmountValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type HookReturn = {
};

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

const allRoutesFailed = useMemo(
() =>
props.routes.every((route) => props.quotesMap[route]?.success === false),
[props.routes, props.quotesMap],
);
const allRoutesFailed = useMemo(() => {
if (Object.keys(props.quotesMap).length === 0) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this fixes a bug unrelated to amount.Amount refactor: if you run every on an empty array, it always returns true.

return false;
}

const numAmount = Number.parseFloat(amount);
return props.routes.every((route) => {
return props.quotesMap[route]?.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
1 change: 0 additions & 1 deletion wormhole-connect/src/hooks/useFetchSupportedRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ const useFetchSupportedRoutes = (): HookReturn => {
supported = await route.isRouteSupported(
token,
destToken,
amount,
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this argument was never used by isRouteSupported

fromChain,
toChain,
);
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
9 changes: 5 additions & 4 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 @@ -63,7 +64,7 @@ const useRoutesQuotesBulk = (routes: string[], params: Params): HookReturn => {
!params.sourceToken ||
!params.destChain ||
!params.destToken ||
!parseFloat(params.amount) ||
!params.amount ||
routes.length === 0
) {
return;
Expand Down Expand Up @@ -138,7 +139,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 @@ -186,7 +187,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
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
Loading