Skip to content

Commit

Permalink
fix: move sdk initialization to provider
Browse files Browse the repository at this point in the history
  • Loading branch information
chybisov committed Sep 6, 2022
1 parent 210b2c8 commit 882e02a
Show file tree
Hide file tree
Showing 23 changed files with 113 additions and 99 deletions.
3 changes: 3 additions & 0 deletions packages/widget-embedded/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ const widgetDrawerConfig: WidgetConfig = {
// disableColorSchemes: true,
disableTelemetry: true,
integrator: 'li.fi-playground',
// sdkConfig: {
// apiUrl: 'https://developkub.li.finance/v1/',
// },
// featuredTokens: [
// {
// address: '0x195e3087ea4d7eec6e9c37e9640162fe32433d5e',
Expand Down
2 changes: 0 additions & 2 deletions packages/widget-embedded/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
// import { ethers, Signer } from 'ethers';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { App } from './App';
import { WalletProvider } from './providers/WalletProvider';

import { reportWebVitals } from './reportWebVitals';

const rootElement = document.getElementById('root');
Expand Down
51 changes: 23 additions & 28 deletions packages/widget/src/AppProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
/* eslint-disable camelcase */
/* eslint-disable react/jsx-pascal-case */
import type { QueryClientProviderProps } from '@tanstack/react-query';
import { QueryClientProvider } from '@tanstack/react-query';
import type { FC, PropsWithChildren } from 'react';
import { Fragment } from 'react';
import { MemoryRouter, useInRouterContext } from 'react-router-dom';
import type { WidgetConfig } from '.';
import { queryClient } from './config/queryClient';
import { useTelemetry } from './hooks';
import { SwapFormProvider } from './providers/SwapFormProvider';
import { ThemeProvider } from './providers/ThemeProvider';
import { WalletProvider } from './providers/WalletProvider';
import { WidgetProvider } from './providers/WidgetProvider';
import {
SDKProvider,
SwapFormProvider,
TelemetryProvider,
ThemeProvider,
WalletProvider,
WidgetProvider,
} from './providers';

export interface AppProps {
config?: WidgetConfig;
Expand All @@ -26,19 +27,21 @@ export const AppProvider: React.FC<PropsWithChildren<AppProps>> = ({
config,
}) => {
return (
<QueryProvider client={queryClient}>
<TelemetryProvider disabled={config?.disableTelemetry}>
<WalletProvider walletManagement={config?.walletManagement}>
<WidgetProvider config={config}>
<ThemeProvider>
<SwapFormProvider>
<AppRouter>{children}</AppRouter>
</SwapFormProvider>
</ThemeProvider>
</WidgetProvider>
</WalletProvider>
</TelemetryProvider>
</QueryProvider>
<WidgetProvider config={config}>
<SDKProvider>
<QueryProvider client={queryClient}>
<TelemetryProvider>
<WalletProvider>
<ThemeProvider>
<SwapFormProvider>
<AppRouter>{children}</AppRouter>
</SwapFormProvider>
</ThemeProvider>
</WalletProvider>
</TelemetryProvider>
</QueryProvider>
</SDKProvider>
</WidgetProvider>
);
};

Expand All @@ -47,11 +50,3 @@ export const AppRouter: React.FC<PropsWithChildren<{}>> = ({ children }) => {
const Router = inRouterContext ? Fragment : MemoryRouter;
return <Router>{children}</Router>;
};

export const TelemetryProvider: React.FC<{
children: React.ReactElement<any, any> | null;
disabled?: boolean;
}> = ({ children, disabled }) => {
useTelemetry(disabled);
return children;
};
2 changes: 1 addition & 1 deletion packages/widget/src/components/AppContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { styled } from '@mui/material/styles';
import type { PropsWithChildren, RefObject } from 'react';
import { useLayoutEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
import { useWidgetConfig } from '../providers/WidgetProvider';
import { useWidgetConfig } from '../providers';
import { ElementId } from '../utils';

const CssBaselineContainer = styled(ScopedCssBaseline)(({ theme }) => ({
Expand Down
2 changes: 1 addition & 1 deletion packages/widget/src/components/SelectChainAndToken.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Box, useMediaQuery } from '@mui/material';
import { useWatch } from 'react-hook-form';
import { ReverseTokensButton } from '../components/ReverseTokensButton';
import { SelectTokenButton } from '../components/SelectTokenButton';
import { SwapFormKey } from '../providers/SwapFormProvider';
import { SwapFormKey } from '../providers';

export const SelectChainAndToken: React.FC<BoxProps> = (props) => {
const prefersNarrowView = useMediaQuery((theme: Theme) =>
Expand Down
10 changes: 0 additions & 10 deletions packages/widget/src/config/lifi.ts

This file was deleted.

6 changes: 3 additions & 3 deletions packages/widget/src/hooks/useChains.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { useQuery } from '@tanstack/react-query';
import { useCallback } from 'react';
import { LiFi } from '../config/lifi';
import { useWidgetConfig } from '../providers/WidgetProvider';
import { useLiFi, useWidgetConfig } from '../providers';
import { useSetChainOrder } from '../stores/chains';

export const useChains = () => {
const { disabledChains } = useWidgetConfig();
const lifi = useLiFi();
const [, initializeChains] = useSetChainOrder();
const { data, isLoading } = useQuery(['chains'], async () => {
const chains = await LiFi.getChains();
const chains = await lifi.getChains();
const filteredChains = chains.filter(
(chain) => !disabledChains?.includes(chain.id),
);
Expand Down
2 changes: 1 addition & 1 deletion packages/widget/src/hooks/useFeaturedTokens.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
import { useWidgetConfig } from '../providers/WidgetProvider';
import { useWidgetConfig } from '../providers';

export const useFeaturedTokens = (selectedChainId: number) => {
const { featuredTokens } = useWidgetConfig();
Expand Down
3 changes: 1 addition & 2 deletions packages/widget/src/hooks/useGasSufficiency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import Big from 'big.js';
import { useMemo } from 'react';
import { useWatch } from 'react-hook-form';
import { useChains, useDebouncedWatch } from '.';
import { SwapFormKey, SwapFormKeyHelper } from '../providers/SwapFormProvider';
import { useWallet } from '../providers/WalletProvider';
import { SwapFormKey, SwapFormKeyHelper, useWallet } from '../providers';
import { useTokenBalances } from './useTokenBalances';

interface GasSufficiency {
Expand Down
6 changes: 6 additions & 0 deletions packages/widget/src/hooks/useInitializer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
/* eslint-disable no-underscore-dangle */
import { checkPackageUpdates } from '@lifi/sdk';
import { useEffect } from 'react';
import { name, version } from '../config/version';
import { useTools } from './useTools';

export const useInitializer = () => {
useTools();
useEffect(() => {
checkPackageUpdates(name, version);
}, []);
};
12 changes: 6 additions & 6 deletions packages/widget/src/hooks/useRouteExecution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import type { Route } from '@lifi/sdk';
import { useMutation } from '@tanstack/react-query';
import { useCallback, useEffect, useRef } from 'react';
import shallow from 'zustand/shallow';
import { LiFi } from '../config/lifi';
import { useWallet } from '../providers/WalletProvider';
import { useLiFi, useWallet } from '../providers';
import {
isRouteActive,
isRouteCompleted,
Expand All @@ -18,6 +17,7 @@ export const useRouteExecution = (
routeId: string,
executeInBackground?: boolean,
) => {
const lifi = useLiFi();
const { account, switchChain } = useWallet();
const resumedAfterMount = useRef(false);
const emitter = useWidgetEvents();
Expand Down Expand Up @@ -61,7 +61,7 @@ export const useRouteExecution = (
if (!routeExecution?.route) {
throw Error('Execution route not found.');
}
return LiFi.executeRoute(account.signer, routeExecution.route, {
return lifi.executeRoute(account.signer, routeExecution.route, {
updateCallback,
switchChainHook,
infiniteApproval: false,
Expand All @@ -84,7 +84,7 @@ export const useRouteExecution = (
if (!routeExecution?.route) {
throw Error('Execution route not found.');
}
return LiFi.resumeRoute(
return lifi.resumeRoute(
account.signer,
resumedRoute ?? routeExecution.route,
{
Expand Down Expand Up @@ -160,11 +160,11 @@ export const useRouteExecution = (
if (!route || !isRouteActive(route)) {
return;
}
LiFi.updateRouteExecution(route, { executeInBackground: true });
lifi.updateRouteExecution(route, { executeInBackground: true });
console.log('Move route execution to background.', routeId);
resumedAfterMount.current = false;
};
}, [routeId]);
}, [lifi, routeId]);

return {
executeRoute,
Expand Down
7 changes: 3 additions & 4 deletions packages/widget/src/hooks/useSwapRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import Big from 'big.js';
import { useWatch } from 'react-hook-form';
import { useDebouncedWatch, useToken } from '.';
import { LiFi } from '../config/lifi';
import { SwapFormKey } from '../providers/SwapFormProvider';
import { useWallet } from '../providers/WalletProvider';
import { SwapFormKey, useLiFi, useWallet } from '../providers';
import { useSettings } from '../stores';

const refetchTime = 60_000;

export const useSwapRoutes = () => {
const lifi = useLiFi();
const { account, provider } = useWallet();
const queryClient = useQueryClient();
const { slippage, enabledBridges, enabledExchanges, routePriority } =
Expand Down Expand Up @@ -91,7 +90,7 @@ export const useSwapRoutes = () => {
} catch {
toWalletAddress = isAddress(toAddress) ? toAddress : fromAddress;
}
return LiFi.getRoutes(
return lifi.getRoutes(
{
fromChainId,
fromAmount: Big(
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,8 +1,7 @@
/* eslint-disable consistent-return */
import { useQuery } from '@tanstack/react-query';
import { useState } from 'react';
import { LiFi } from '../config/lifi';
import { useWallet } from '../providers/WalletProvider';
import { useLiFi, useWallet } from '../providers';
import type { Token } from '../types';
import { formatTokenAmount } from '../utils';
import { useFeaturedTokens } from './useFeaturedTokens';
Expand All @@ -12,6 +11,7 @@ const defaultRefetchInterval = 60_000;
const minRefetchInterval = 1000;

export const useTokenBalances = (selectedChainId: number) => {
const lifi = useLiFi();
const { account } = useWallet();
const featuredTokens = useFeaturedTokens(selectedChainId);
const { tokens, isLoading } = useTokens(selectedChainId);
Expand All @@ -33,7 +33,7 @@ export const useTokenBalances = (selectedChainId: number) => {
if (!accountAddress || !tokens) {
return;
}
const tokenBalances = await LiFi.getTokenBalances(
const tokenBalances = await lifi.getTokenBalances(
accountAddress as string,
tokens,
);
Expand Down
5 changes: 3 additions & 2 deletions packages/widget/src/hooks/useTokenSearch.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import type { ChainId } from '@lifi/sdk';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { LiFi } from '../config/lifi';
import { useLiFi } from '../providers';
import type { Token } from '../types';

export const useTokenSearch = (
token: string,
chainId: number,
enabled?: boolean,
) => {
const lifi = useLiFi();
const queryClient = useQueryClient();
const { data, isLoading, isFetching, isFetched } = useQuery(
['token-search', chainId, token],
async ({ queryKey: [, chainId, token], signal }) => {
const data = await LiFi.getToken(chainId as ChainId, token as string, {
const data = await lifi.getToken(chainId as ChainId, token as string, {
signal,
});
if (data) {
Expand Down
5 changes: 3 additions & 2 deletions packages/widget/src/hooks/useTokens.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { useQuery } from '@tanstack/react-query';
import { LiFi } from '../config/lifi';
import { useLiFi } from '../providers';
import type { Token } from '../types';
import { useFeaturedTokens } from './useFeaturedTokens';

export const useTokens = (selectedChainId: number) => {
const lifi = useLiFi();
const featuredTokens = useFeaturedTokens(selectedChainId);
const {
data: tokens,
Expand All @@ -12,7 +13,7 @@ export const useTokens = (selectedChainId: number) => {
} = useQuery(
['tokens', selectedChainId, featuredTokens?.length],
async () => {
const data = await LiFi.getTokens({ chains: [selectedChainId] });
const data = await lifi.getTokens({ chains: [selectedChainId] });
const featuredTokenAddresses = new Set(
featuredTokens?.map((token) => token.address),
);
Expand Down
9 changes: 3 additions & 6 deletions packages/widget/src/hooks/useTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,17 @@
import type { Bridge, Exchange } from '@lifi/sdk';
import { useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
import { LiFi } from '../config/lifi';
import { useLiFi } from '../providers';
import { useSettingsStore } from '../stores';

type FormattedTool<T, K extends keyof T> = Record<string, Pick<T, K>>;
interface FormattedTools {
bridges: FormattedTool<Bridge, 'key' | 'name' | 'logoURI'>;
exchanges: FormattedTool<Exchange, 'key' | 'name' | 'logoURI'>;
}

export const useTools = () => {
const lifi = useLiFi();
const initializeTools = useSettingsStore((state) => state.initializeTools);
const { data } = useQuery(
['tools'],
({ signal }) => LiFi.getTools(undefined, { signal }),
({ signal }) => lifi.getTools(undefined, { signal }),
{
onSuccess(data) {
initializeTools(
Expand Down
34 changes: 34 additions & 0 deletions packages/widget/src/providers/SDKProvider/SDKProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import LIFI from '@lifi/sdk';
import { createContext, useContext, useMemo } from 'react';
import { useWidgetConfig } from '../WidgetProvider';

let lifi: LIFI;

const SDKContext = createContext<LIFI>(null!);

export const useLiFi = (): LIFI => useContext(SDKContext);

export const SDKProvider: React.FC<React.PropsWithChildren> = ({
children,
}) => {
const { sdkConfig, integrator } = useWidgetConfig();
const value = useMemo(() => {
const config = {
...sdkConfig,
defaultRouteOptions: {
...sdkConfig?.defaultRouteOptions,
integrator: integrator ?? window.location.hostname,
},
};
if (!lifi) {
lifi = new LIFI({
disableVersionCheck: true,
...config,
});
}
lifi.setConfig(config);
return lifi;
}, [integrator, sdkConfig]);

return <SDKContext.Provider value={value}>{children}</SDKContext.Provider>;
};
1 change: 1 addition & 0 deletions packages/widget/src/providers/SDKProvider/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './SDKProvider';
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { useWidgetConfig } from '..';
import { useTelemetry } from '../../hooks';

export const TelemetryProvider: React.FC<{
children: React.ReactElement<any, any> | null;
}> = ({ children }) => {
const config = useWidgetConfig();
useTelemetry(config?.disableTelemetry);
return children;
};
1 change: 1 addition & 0 deletions packages/widget/src/providers/TelemetryProvider/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './TelemetryProvider';
Loading

0 comments on commit 882e02a

Please sign in to comment.