Skip to content

Commit

Permalink
refactor: delete getTokenBalance and getNativeBalance from routes
Browse files Browse the repository at this point in the history
  • Loading branch information
anondev2323 committed Sep 8, 2023
1 parent a02850c commit e7a3f50
Show file tree
Hide file tree
Showing 18 changed files with 157 additions and 222 deletions.
5 changes: 1 addition & 4 deletions wormhole-connect/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@
<body style="margin: 0">
<noscript>You need to enable JavaScript to run this app.</noscript>
<!-- <div id="wormhole-connect" config='{"networks": ["goerli", "mumbai"], "tokens": ["ETH", "WETH", "MATIC", "WMATIC"], "theme": "light"}'></div> -->
<div
id="wormhole-connect"
config='{"routes": ["bridge", "cctpManual"]}'
></div>
<div id="wormhole-connect"></div>
</body>
</html>
4 changes: 2 additions & 2 deletions wormhole-connect/src/components/ChainsModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
ChainConfig,
ChainName,
} from '@wormhole-foundation/wormhole-connect-sdk';
import { CHAINS_ARR, CHAINS, ROUTES } from '../config';
import { CHAINS_ARR, CHAINS } from '../config';
import { CENTER, joinClass } from '../utils/style';

import Header from './Header';
Expand Down Expand Up @@ -85,7 +85,7 @@ function ChainsModal(props: Props) {
return chains.filter((chain) => {
return supported.includes(chain.key);
});
}, [ROUTES, chains]);
}, [chains]);

const searchChains = (
e:
Expand Down
31 changes: 24 additions & 7 deletions wormhole-connect/src/components/TokensModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ import { CHAINS, TOKENS_ARR } from 'config';
import { TokenConfig } from 'config/types';
import { setBalance, formatBalance, clearBalances } from 'store/transferInput';
import { displayAddress } from 'utils';
import { wh } from 'utils/sdk';
import { CENTER, NO_INPUT } from 'utils/style';
import { isCosmWasmChain } from 'utils/cosmos';
import RouteOperator from 'utils/routes/operator';

import Header from './Header';
import Modal from './Modal';
Expand All @@ -29,6 +29,7 @@ import Scroll from './Scroll';
import TokenIcon from '../icons/TokenIcons';
import CircularProgress from '@mui/material/CircularProgress';
import Tabs from './Tabs';
import { CosmosGatewayRoute } from 'utils/routes';

const useStyles = makeStyles()((theme: any) => ({
tokensContainer: {
Expand Down Expand Up @@ -337,20 +338,36 @@ function TokensModal(props: Props) {
}, [chain, walletAddress]);

const getBalances = useCallback(async () => {
if (!walletAddress || !chain || !route) return;
if (!walletAddress || !chain) return;
// fetch all N tokens and trigger a single update action
const balancesArr = await Promise.all(
allTokens.map(async (t) => {
let balance: BigNumber | null = null;
try {
balance = t.tokenId
? await RouteOperator.getTokenBalance(
route,
if (t.tokenId) {
// TODO: going to do some refactoring of gateway/cosmos contexts
if (isCosmWasmChain(wh.toChainId(chain))) {
const denom = await new CosmosGatewayRoute().getForeignAsset(
t.tokenId,
chain,
);
if (denom) {
balance = await wh.getNativeBalance(
walletAddress,
chain,
denom,
);
}
} else {
balance = await wh.getTokenBalance(
walletAddress,
t.tokenId,
chain,
)
: await RouteOperator.getNativeBalance(route, walletAddress, chain);
);
}
} else {
balance = await wh.getNativeBalance(walletAddress, chain);
}
} catch (e) {
console.warn('Failed to fetch balance', e);
}
Expand Down
20 changes: 14 additions & 6 deletions wormhole-connect/src/store/transferInput.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { ChainName } from '@wormhole-foundation/wormhole-connect-sdk';
import { BigNumber } from 'ethers';
import { ROUTES, TOKENS, config } from 'config';
import { TOKENS, config } from 'config';
import { Route, TokenConfig } from 'config/types';
import { getTokenDecimals } from 'utils';
import { toDecimals } from 'utils/balance';
Expand Down Expand Up @@ -48,7 +48,7 @@ export interface TransferInputState {
destToken: string;
amount: string;
receiveAmount: string;
route: Route;
route: Route | undefined;
sourceBalances: Balances;
destBalances: Balances;
foreignAsset: string;
Expand Down Expand Up @@ -78,14 +78,14 @@ const initialState: TransferInputState = {
foreignAsset: '',
associatedTokenAccount: '',
},
availableRoutes: ROUTES,
availableRoutes: [],
fromChain: config?.bridgeDefaults?.fromNetwork || undefined,
toChain: config?.bridgeDefaults?.toNetwork || undefined,
token: config?.bridgeDefaults?.token || '',
destToken: '',
amount: '',
receiveAmount: '',
route: ROUTES[0] as Route,
route: undefined,
sourceBalances: {},
destBalances: {},
foreignAsset: '',
Expand Down Expand Up @@ -218,9 +218,17 @@ export const transferInputSlice = createSlice({
},
setTransferRoute: (
state: TransferInputState,
{ payload }: PayloadAction<Route>,
{ payload }: PayloadAction<Route | undefined>,
) => {
state.route = payload;
if (!payload) {
state.route = undefined;
return;
}
if (state.availableRoutes.includes(payload)) {
state.route = payload;
} else {
state.route = undefined;
}
},
// gas estimates
setSendingGasEst: (
Expand Down
15 changes: 0 additions & 15 deletions wormhole-connect/src/utils/routes/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,21 +245,6 @@ export class BridgeRoute extends BaseRoute {
];
}

getNativeBalance(
address: string,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
return wh.getNativeBalance(address, chain);
}

getTokenBalance(
address: string,
tokenId: TokenId,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
return wh.getTokenBalance(address, tokenId, chain);
}

async getRelayerFee(
sourceChain: ChainName | ChainId,
destChain: ChainName | ChainId,
Expand Down
15 changes: 0 additions & 15 deletions wormhole-connect/src/utils/routes/cctpManual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,21 +468,6 @@ export class CCTPManualRoute extends BaseRoute {
];
}

getNativeBalance(
address: string,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
return wh.getNativeBalance(address, chain);
}

getTokenBalance(
address: string,
tokenId: TokenId,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
return wh.getTokenBalance(address, tokenId, chain);
}

async getRelayerFee(
sourceChain: ChainName | ChainId,
destChain: ChainName | ChainId,
Expand Down
21 changes: 0 additions & 21 deletions wormhole-connect/src/utils/routes/cosmosGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,27 +415,6 @@ export class CosmosGatewayRoute extends BaseRoute {
];
}

async getNativeBalance(
address: string,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
return wh.getNativeBalance(address, chain);
}

async getTokenBalance(
address: string,
tokenId: TokenId,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
if (isCosmWasmChain(wh.toChainId(chain))) {
const denom = await this.getForeignAsset(tokenId, chain);
if (!denom) return null;
return wh.getNativeBalance(address, chain, denom);
}

return wh.getTokenBalance(address, tokenId, chain);
}

private isNativeDenom(denom: string, chain: ChainName | ChainId): boolean {
const chainId = wh.toChainId(chain);
switch (chainId) {
Expand Down
15 changes: 1 addition & 14 deletions wormhole-connect/src/utils/routes/hashflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,20 +108,7 @@ export class HashflowRoute extends RouteAbstract {
): Promise<string> {
throw new Error('Method not implemented.');
}
public getPreview<P>(params: P): Promise<TransferDisplayData> {
throw new Error('Method not implemented.');
}
getNativeBalance(
address: string,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
throw new Error('Method not implemented.');
}
getTokenBalance(
address: string,
tokenId: TokenId,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
getPreview<P>(params: P): Promise<TransferDisplayData> {
throw new Error('Method not implemented.');
}
async getRelayerFee(
Expand Down
19 changes: 0 additions & 19 deletions wormhole-connect/src/utils/routes/operator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,25 +417,6 @@ export class Operator {
);
}

async getNativeBalance(
route: Route,
address: string,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
const r = this.getRoute(route);
return r.getNativeBalance(address, chain);
}

async getTokenBalance(
route: Route,
address: string,
tokenId: TokenId,
chain: ChainName | ChainId,
): Promise<BigNumber | null> {
const r = this.getRoute(route);
return r.getTokenBalance(address, tokenId, chain);
}

async getRelayerFee(
route: Route,
sourceChain: ChainName | ChainId,
Expand Down
11 changes: 0 additions & 11 deletions wormhole-connect/src/utils/routes/routeAbstract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,17 +134,6 @@ export default abstract class RouteAbstract {
): Promise<TransferDisplayData>;

// send, validate, estimate gas, isRouteAvailable, parse data from VAA/fetch data, claim

abstract getNativeBalance(
address: string,
chain: ChainName | ChainId,
): Promise<BigNumber | null>;
abstract getTokenBalance(
address: string,
tokenId: TokenId,
chain: ChainName | ChainId,
): Promise<BigNumber | null>;

abstract getRelayerFee(
sourceChain: ChainName | ChainId,
destChain: ChainName | ChainId,
Expand Down
28 changes: 19 additions & 9 deletions wormhole-connect/src/utils/transferValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ export const validateDestToken = (
export const validateAmount = (
amount: string,
balance: string | null,
route: Route,
minAmt: number | undefined,
): ValidationErr => {
const numAmount = Number.parseFloat(amount);
Expand Down Expand Up @@ -138,10 +137,10 @@ export const validateToNativeAmt = (
};

export const validateRoute = (
route: Route,
route: Route | undefined,
availableRoutes: string[],
): ValidationErr => {
if (!availableRoutes || !availableRoutes.includes(route)) {
if (!route || !availableRoutes || !availableRoutes.includes(route)) {
return 'No bridge or swap route available for selected tokens';
}
return '';
Expand Down Expand Up @@ -169,6 +168,18 @@ export const validateSolanaTokenAccount = (
return '';
};

export const getMinAmt = (route: Route | undefined, relayData: any): number => {
if (!route) return 0;
const r = RouteOperator.getRoute(route);
return r.getMinSendAmount(relayData);
};

export const getIsAutomatic = (route: Route | undefined): boolean => {
if (!route) return false;
const r = RouteOperator.getRoute(route);
return r.AUTOMATIC_DEPOSIT;
};

export const validateAll = async (
transferData: TransferInputState,
relayData: RelayState,
Expand All @@ -188,18 +199,17 @@ export const validateAll = async (
} = transferData;
const { maxSwapAmt, toNativeToken } = relayData;
const { sending, receiving } = walletData;
if (!route) throw new Error('no route selected');
const r = RouteOperator.getRoute(route);
const isAutomatic = r.AUTOMATIC_DEPOSIT;
const minAmt = r.getMinSendAmount(relayData);
const isAutomatic = getIsAutomatic(route);
const minAmt = getMinAmt(route, relayData);

const baseValidations = {
sendingWallet: await validateWallet(sending, fromChain),
receivingWallet: await validateWallet(receiving, toChain),
fromChain: validateFromChain(fromChain),
toChain: validateToChain(toChain, fromChain),
token: validateToken(token, fromChain),
destToken: validateDestToken(destToken, toChain),
amount: validateAmount(amount, balances[token], route, minAmt),
amount: validateAmount(amount, balances[token], minAmt),
route: validateRoute(route, availableRoutes),
toNativeToken: '',
foreignAsset: validateForeignAsset(foreignAsset),
Expand All @@ -212,7 +222,7 @@ export const validateAll = async (
if (!isAutomatic) return baseValidations;
return {
...baseValidations,
amount: validateAmount(amount, balances[token], route, minAmt),
amount: validateAmount(amount, balances[token], minAmt),
toNativeToken: validateToNativeAmt(toNativeToken, maxSwapAmt),
};
};
Expand Down
Loading

0 comments on commit e7a3f50

Please sign in to comment.