Skip to content

Commit

Permalink
refactor: update token types
Browse files Browse the repository at this point in the history
  • Loading branch information
chybisov committed Apr 27, 2023
1 parent 0b9b30e commit 1d1833c
Show file tree
Hide file tree
Showing 21 changed files with 62 additions and 59 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Token } from '@lifi/sdk';
import type { StaticToken } from '@lifi/sdk';
import { ethers } from 'ethers';
import events from 'events';
import type {
Expand Down Expand Up @@ -153,7 +153,7 @@ export class InjectedConnector extends events.EventEmitter implements Wallet {
return addChain(this.windowProvider, chainId);
}

public async addToken(chainId: number, token: Token) {
public async addToken(chainId: number, token: StaticToken) {
if (window === undefined) {
throw new Error('window is not defined. This should not have happened.');
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Token } from '@lifi/sdk';
import type { StaticToken } from '@lifi/sdk';
import WalletConnectProvider from '@walletconnect/ethereum-provider';
import { ethers } from 'ethers';
import events from 'events';
Expand Down Expand Up @@ -116,7 +116,7 @@ export class WalletConnectConnector
return addChain(this.provider, chainId);
}

public async addToken(chainId: number, token: Token) {
public async addToken(chainId: number, token: StaticToken) {
if (!this.provider) {
throw new Error('provider is not defined.');
}
Expand Down
4 changes: 2 additions & 2 deletions packages/wallet-management/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Signer } from '@ethersproject/abstract-signer';
import type { Token } from '@lifi/sdk';
import type { StaticToken } from '@lifi/sdk';
import type { ethers } from 'ethers';
import type events from 'events';
import type EventEmitter from 'node:events';
Expand Down Expand Up @@ -55,7 +55,7 @@ export interface Wallet extends events.EventEmitter {
disconnect: () => void;
switchChain: (chainId: number) => Promise<boolean>;
addChain: (chainId: number) => Promise<boolean>;
addToken: (chainId: number, token: Token) => Promise<boolean>;
addToken: (chainId: number, token: StaticToken) => Promise<boolean>;
}

export enum ProviderIdentityFlag {
Expand Down
8 changes: 4 additions & 4 deletions packages/wallet-management/src/walletAutomation.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable radix */
import type { Token } from '@lifi/sdk';
import type { StaticToken } from '@lifi/sdk';
import {
getChainById,
MetaMaskProviderErrorCode,
getChainById,
prefixChainId,
} from '@lifi/sdk';
import type { Provider } from './types';
Expand Down Expand Up @@ -56,7 +56,7 @@ export const addChain = async (provider: Provider, chainId: number) => {
return false;
};

export const addToken = async (provider: Provider, token: Token) => {
export const addToken = async (provider: Provider, token: StaticToken) => {
try {
// wasAdded is a boolean. Like any RPC method, an error may be thrown.
const wasAdded = await provider.request({
Expand All @@ -81,7 +81,7 @@ export const addToken = async (provider: Provider, token: Token) => {
export const switchChainAndAddToken = async (
provider: Provider,
chainId: number,
token: Token,
token: StaticToken,
) => {
const chainIdPrefixed = prefixChainId(chainId);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ChainId, TokenAmount } from '@lifi/sdk';
import type { WidgetContract } from '@lifi/widget';
import { NFT, useWallet } from '@lifi/widget';
import { Box, Typography } from '@mui/material';
Expand All @@ -10,7 +11,7 @@ import type {
NFTOpenSeaProps,
OrdersQueryResponse,
} from './types';
import { ChainId } from './types';
import { ChainId as OpenSeaChainId } from './types';
import { deserializeOrder } from './utils';

export const NFTOpenSea: React.FC<NFTOpenSeaProps> = ({
Expand Down Expand Up @@ -86,7 +87,9 @@ export const NFTOpenSea: React.FC<NFTOpenSeaProps> = ({
});
} catch (error: any) {
if (error.code === 'CALL_EXCEPTION') {
const switched = await switchChain(ChainId[network as NFTNetwork]);
const switched = await switchChain(
OpenSeaChainId[network as NFTNetwork],
);
if (switched) {
await fulfillOrder();
} else {
Expand All @@ -108,13 +111,14 @@ export const NFTOpenSea: React.FC<NFTOpenSeaProps> = ({
order?.maker.user?.username || order?.maker.address
}`,
};
const token = {
const token: TokenAmount = {
symbol: order?.takerAssetBundle.assets[0]?.assetContract?.tokenSymbol!,
amount: order?.currentPrice!,
decimals: order?.takerAssetBundle.assets[0].decimals!,
address: order?.takerAssetBundle.assets[0].tokenAddress!,
chainId: ChainId[network as NFTNetwork],
chainId: OpenSeaChainId[network as NFTNetwork] as number as ChainId,
name: order?.takerAssetBundle.assets[0]?.assetContract.tokenSymbol!,
priceUSD: '',
};

return {
Expand Down
4 changes: 2 additions & 2 deletions packages/widget-embedded/src/providers/WalletProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Signer } from '@ethersproject/abstract-signer';
import type { Token } from '@lifi/sdk';
import type { StaticToken } from '@lifi/sdk';
import type { Wallet } from '@lifi/wallet-management';
import { LiFiWalletManagement } from '@lifi/wallet-management';
import type { WalletAccount, WalletContextProps } from '@lifi/widget/providers';
Expand Down Expand Up @@ -87,7 +87,7 @@ export const WalletProvider: FC<PropsWithChildren<{}>> = ({ children }) => {
);

const addToken = useCallback(
async (chainId: number, token: Token) => {
async (chainId: number, token: StaticToken) => {
await currentWallet?.addToken(chainId, token);
handleWalletUpdate(currentWallet);

Expand Down
5 changes: 2 additions & 3 deletions packages/widget-playground/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { Token } from '@lifi/sdk';

import type { StaticToken } from '@lifi/sdk';
import type { WidgetVariant } from '@lifi/widget';
import { LiFiWidget } from '@lifi/widget';
import {
Expand Down Expand Up @@ -140,7 +139,7 @@ export const App = () => {
}
throw Error('No signer object after chain switch');
},
addToken: async (token: Token, chainId: number) => {
addToken: async (token: StaticToken, chainId: number) => {
await METAMASK_WALLET!.addToken(chainId, token);
},
addChain: async (chainId: number) => {
Expand Down
1 change: 0 additions & 1 deletion packages/widget-playground/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ export const widgetBaseConfig: WidgetConfig = {
decimals: 9,
chainId: 56,
name: 'Chihuahua',
priceUSD: '2.8497281105098143e-11',
logoURI:
'https://s2.coinmarketcap.com/static/img/coins/64x64/21334.png',
},
Expand Down
8 changes: 3 additions & 5 deletions packages/widget-playground/src/providers/WalletProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Signer } from '@ethersproject/abstract-signer';
import type { Token } from '@lifi/sdk';
import type { StaticToken } from '@lifi/sdk';
import type { Wallet } from '@lifi/wallet-management';
import { LiFiWalletManagement } from '@lifi/wallet-management';
import type { WalletAccount, WalletContextProps } from '@lifi/widget/providers';
Expand All @@ -8,11 +8,9 @@ import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { METAMASK_WALLET } from '../config';

const stub = (): never => {
throw new Error(
Expand Down Expand Up @@ -87,7 +85,7 @@ export const WalletProvider: FC<PropsWithChildren<{}>> = ({ children }) => {
);

const addToken = useCallback(
async (chainId: number, token: Token) => {
async (chainId: number, token: StaticToken) => {
await currentWallet?.addToken(chainId, token);
handleWalletUpdate(currentWallet);

Expand All @@ -105,7 +103,7 @@ export const WalletProvider: FC<PropsWithChildren<{}>> = ({ children }) => {
addToken,
account,
}),
[account.address, addChain, addToken, connect, disconnect, switchChain],
[account, addChain, addToken, connect, disconnect, switchChain],
);

return (
Expand Down
6 changes: 3 additions & 3 deletions packages/widget/src/components/Step/StepList.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import type { Route } from '@lifi/sdk';
import type { Route, TokenAmount } from '@lifi/sdk';
import { Fragment } from 'react';
import { StepDivider } from '../../components/StepDivider';
import { Step } from './Step';

export const getStepList = (route?: Route) =>
route?.steps.map((step, index, steps) => {
const lastIndex = steps.length - 1;
const fromToken =
const fromToken: TokenAmount | undefined =
index === 0
? { ...step.action.fromToken, amount: step.action.fromAmount }
: undefined;
const toToken =
const toToken: TokenAmount | undefined =
index === lastIndex
? {
...(step.execution?.toToken ?? step.action?.toToken),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { TokenAmount } from '@lifi/sdk';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import VerifiedUserIcon from '@mui/icons-material/VerifiedUser';
Expand Down Expand Up @@ -26,7 +27,7 @@ export const SwapRouteCard: React.FC<
setCardExpanded((expanded) => !expanded);
};

const token =
const token: TokenAmount =
widgetVariant === 'nft'
? { ...route.fromToken, amount: route.fromAmount }
: { ...route.toToken, amount: route.toAmount };
Expand Down
8 changes: 4 additions & 4 deletions packages/widget/src/components/TokenAvatar/TokenAvatar.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { Chain, Token } from '@lifi/sdk';
import type { Chain, StaticToken } from '@lifi/sdk';
import type { SxProps, Theme } from '@mui/material';
import { Avatar, Badge, Skeleton } from '@mui/material';
import { useChain, useToken } from '../../hooks';
import { SmallAvatar, SmallAvatarSkeleton } from '../SmallAvatar';
import { AvatarDefault, AvatarDefaultBadge } from './TokenAvatar.style';

export const TokenAvatarFallback: React.FC<{
token?: Token;
token?: StaticToken;
isLoading?: boolean;
sx?: SxProps<Theme>;
}> = ({ token, isLoading, sx }) => {
Expand All @@ -26,7 +26,7 @@ export const TokenAvatarFallback: React.FC<{
};

export const TokenAvatarBase: React.FC<{
token?: Token;
token?: StaticToken;
chain?: Chain;
isLoading?: boolean;
sx?: SxProps<Theme>;
Expand Down Expand Up @@ -58,7 +58,7 @@ export const TokenAvatarBase: React.FC<{
};

export const TokenAvatar: React.FC<{
token?: Token;
token?: StaticToken;
chain?: Chain;
isLoading?: boolean;
sx?: SxProps<Theme>;
Expand Down
8 changes: 5 additions & 3 deletions packages/widget/src/components/TokenList/TokenList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import {
useTokenSearch,
} from '../../hooks';
import { SwapFormKey, SwapFormKeyHelper, useWallet } from '../../providers';
import type { Token } from '../../types';
import type { TokenAmount } from '../../types';
import { TokenNotFound } from './TokenNotFound';
import { VirtualizedTokenList } from './VirtualizedTokenList';
import type { TokenListProps } from './types';
import { useTokenSelect } from './useTokenSelect';
import { VirtualizedTokenList } from './VirtualizedTokenList';

export const TokenList: FC<TokenListProps> = ({
formType,
Expand All @@ -37,7 +37,9 @@ export const TokenList: FC<TokenListProps> = ({
featuredTokens,
} = useTokenBalances(selectedChainId);

let filteredTokens = (tokensWithBalance ?? chainTokens ?? []) as Token[];
let filteredTokens = (tokensWithBalance ??
chainTokens ??
[]) as TokenAmount[];
const searchFilter = tokenSearchFilter?.toUpperCase() ?? '';
filteredTokens = tokenSearchFilter
? filteredTokens.filter(
Expand Down
5 changes: 2 additions & 3 deletions packages/widget/src/components/TokenList/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { TokenAmount } from '@lifi/sdk';
import type { MutableRefObject } from 'react';
import type { SwapFormType } from '../../providers';
import type { Token } from '../../types';
import type { TokenAmount } from '../../types';

export interface TokenListProps {
formType: SwapFormType;
Expand All @@ -10,7 +9,7 @@ export interface TokenListProps {
}

export interface VirtualizedTokenListProps {
tokens: Token[];
tokens: TokenAmount[];
featuredTokensLength?: number;
scrollElementRef: MutableRefObject<HTMLElement | null>;
isLoading: boolean;
Expand Down
6 changes: 3 additions & 3 deletions packages/widget/src/hooks/useTokenBalances.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useQuery } from '@tanstack/react-query';
import { useLiFi, useWallet } from '../providers';
import type { Token } from '../types';
import type { TokenAmount } from '../types';
import { formatTokenAmount } from '../utils';
import { useFeaturedTokens } from './useFeaturedTokens';
import { useTokens } from './useTokens';
Expand Down Expand Up @@ -34,12 +34,12 @@ export const useTokenBalances = (selectedChainId?: number) => {
featuredTokens?.map((token) => token.address),
);

const sortFn = (a: Token, b: Token) =>
const sortFn = (a: TokenAmount, b: TokenAmount) =>
parseFloat(b.amount ?? '0') * parseFloat(b.priceUSD ?? '0') -
parseFloat(a.amount ?? '0') * parseFloat(a.priceUSD ?? '0');

const formattedTokens = (
(tokenBalances.length === 0 ? tokens : tokenBalances) as Token[]
(tokenBalances.length === 0 ? tokens : tokenBalances) as TokenAmount[]
).map((token) => {
token.amount = formatTokenAmount(token.amount);
return token;
Expand Down
6 changes: 3 additions & 3 deletions packages/widget/src/hooks/useTokenSearch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ChainId, TokensResponse } from '@lifi/sdk';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useLiFi } from '../providers';
import type { Token } from '../types';
import type { TokenAmount } from '../types';

export const useTokenSearch = (
chainId?: number,
Expand Down Expand Up @@ -30,12 +30,12 @@ export const useTokenSearch = (
)
) {
const clonedData = { ...data };
clonedData.tokens[chainId as number]?.push(token as Token);
clonedData.tokens[chainId as number]?.push(token as TokenAmount);
return clonedData;
}
});
}
return token as Token;
return token as TokenAmount;
},
{
enabled: Boolean(chainId && tokenQuery && enabled),
Expand Down
6 changes: 3 additions & 3 deletions packages/widget/src/hooks/useTokens.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
import { isItemAllowed, useLiFi, useWidgetConfig } from '../providers';
import type { Token } from '../types';
import type { TokenAmount } from '../types';
import { useChains } from './useChains';
import { useFeaturedTokens } from './useFeaturedTokens';

Expand Down Expand Up @@ -44,13 +44,13 @@ export const useTokens = (selectedChainId?: number) => {
);
const tokens = [
...(featuredTokens?.map((token) => {
(token as Token).featured = true;
(token as TokenAmount).featured = true;
return token;
}) ?? []),
...(filteredTokens?.filter(
(token) => !featuredTokenAddresses.has(token.address),
) ?? []),
] as Token[];
] as TokenAmount[];

return tokens;
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Signer } from '@ethersproject/abstract-signer';
import type { Token } from '@lifi/sdk';
import type { StaticToken } from '@lifi/sdk';
import {
LiFiWalletManagement,
readActiveWallets,
Expand Down Expand Up @@ -134,7 +134,7 @@ export const WalletProvider: FC<PropsWithChildren> = ({ children }) => {
);

const addToken = useCallback(
async (chainId: number, token: Token) => {
async (chainId: number, token: StaticToken) => {
if (walletManagement?.addToken) {
return walletManagement.addToken(token, chainId);
}
Expand Down
Loading

0 comments on commit 1d1833c

Please sign in to comment.