Skip to content

Commit

Permalink
refactor: use meta aggregator api only when authen success (#2080)
Browse files Browse the repository at this point in the history
  • Loading branch information
nguyenhoaidanh authored Jul 24, 2023
1 parent b49bef8 commit 780644f
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 6 deletions.
4 changes: 3 additions & 1 deletion src/components/SwapForm/hooks/useBuildRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import routeApi from 'services/route'
import { BuildRouteData, BuildRoutePayload } from 'services/route/types/buildRoute'
import { RouteSummary } from 'services/route/types/getRoute'

import { useRouteApiDomain } from 'components/SwapForm/hooks/useGetRoute'
import { AGGREGATOR_API_PATHS } from 'constants/index'
import { NETWORKS_INFO } from 'constants/networks'
import { useActiveWeb3React } from 'hooks'
Expand Down Expand Up @@ -31,8 +32,9 @@ const useBuildRoute = (args: Args) => {
const { recipient, routeSummary, slippage, transactionTimeout, permit } = args
const { chainId, account } = useActiveWeb3React()
const abortControllerRef = useRef(new AbortController())
const { aggregatorDomain, isEnableAuthenAggregator } = useKyberswapGlobalConfig()
const { isEnableAuthenAggregator } = useKyberswapGlobalConfig()
const [buildRoute] = routeApi.useBuildRouteMutation()
const aggregatorDomain = useRouteApiDomain()

const fetcher = useCallback(async (): Promise<BuildRouteResult> => {
if (!account) {
Expand Down
12 changes: 11 additions & 1 deletion src/components/SwapForm/hooks/useGetRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { GetRouteParams } from 'services/route/types/getRoute'

import useGetSwapFeeConfig, { SwapFeeConfig } from 'components/SwapForm/hooks/useGetSwapFeeConfig'
import useSelectedDexes from 'components/SwapForm/hooks/useSelectedDexes'
import { AGGREGATOR_API } from 'constants/env'
import {
AGGREGATOR_API_PATHS,
ETHER_ADDRESS,
Expand All @@ -17,6 +18,7 @@ import { NETWORKS_INFO, isEVM } from 'constants/networks'
import { useActiveWeb3React } from 'hooks'
import useDebounce from 'hooks/useDebounce'
import { useKyberswapGlobalConfig } from 'hooks/useKyberSwapConfig'
import { useSessionInfo } from 'state/authen/hooks'
import { useAppDispatch } from 'state/hooks'
import { ChargeFeeBy } from 'types/route'
import { Aggregator } from 'utils/aggregator'
Expand Down Expand Up @@ -76,13 +78,21 @@ const getFeeConfigParams = (
}
}

// default use aggregator, utils the first time sign-in successfully (guest/sign in eth) => use meta
export const useRouteApiDomain = () => {
const { aggregatorDomain } = useKyberswapGlobalConfig()
const { authenticationSuccess } = useSessionInfo()
return authenticationSuccess ? aggregatorDomain : AGGREGATOR_API
}

const useGetRoute = (args: ArgsGetRoute) => {
const { aggregatorDomain, isEnableAuthenAggregator } = useKyberswapGlobalConfig()
const { isEnableAuthenAggregator } = useKyberswapGlobalConfig()
const { isSaveGas, parsedAmount, currencyIn, currencyOut, customChain, isProcessingSwap } = args
const { chainId: currentChain } = useActiveWeb3React()
const chainId = customChain || currentChain

const [trigger, _result] = routeApi.useLazyGetRouteQuery()
const aggregatorDomain = useRouteApiDomain()

const getSwapFeeConfig = useGetSwapFeeConfig()

Expand Down
2 changes: 1 addition & 1 deletion src/pages/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ const preloadImages = () => {
const SwapPage = () => {
const { chainId } = useActiveWeb3React()
useSyncNetworkParamWithStore()
return <ProtectedRoute>{chainId === ChainId.SOLANA ? <SwapV2 /> : <SwapV3 />}</ProtectedRoute>
return chainId === ChainId.SOLANA ? <SwapV2 /> : <SwapV3 />
}

const RedirectWithNetworkPrefix = () => {
Expand Down
3 changes: 3 additions & 0 deletions src/state/authen/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface AuthenState {
readonly signedUserInfo: UserProfile | undefined
readonly isLogin: boolean // is sign in eth
readonly pendingAuthentication: boolean
readonly authenticationSuccess: boolean
readonly isConnectingWallet: boolean
readonly showConfirmProfile: boolean
readonly autoSignIn: AutoSignIn // auto sign in after connect wallet
Expand All @@ -31,6 +32,7 @@ const DEFAULT_AUTHEN_STATE: AuthenState = {
signedUserInfo: undefined,
isLogin: false,
pendingAuthentication: true,
authenticationSuccess: false,
isConnectingWallet: false,
showConfirmProfile: false,
autoSignIn: {
Expand Down Expand Up @@ -61,6 +63,7 @@ const slice = createSlice({
state.anonymousUserInfo = undefined
}
state.isLogin = !isAnonymous
if (profile) state.authenticationSuccess = true
},
setConfirmChangeProfile: (state, { payload }: PayloadAction<boolean>) => {
state.showConfirmProfile = payload
Expand Down
1 change: 0 additions & 1 deletion src/state/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ import vesting from './vesting/reducer'

const PERSISTED_KEYS: string[] = ['user', 'transactions', 'profile']
ENV_LEVEL < ENV_TYPE.PROD && PERSISTED_KEYS.push('customizeDexes')
// ENV_LEVEL < ENV_TYPE.PROD && PERSISTED_KEYS.push('mintV2')

const store = configureStore({
devTools: process.env.NODE_ENV !== 'production',
Expand Down
19 changes: 17 additions & 2 deletions src/utils/iamError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const ErrorInfo = {
sentAlertRouteApi: false,
}

const apiDowns: string[] = []

const isIamApiDown = () => ErrorInfo.iamApoError >= ErrorInfo.errorThreshold
const isRouteApiDown = () => ErrorInfo.routeApiError >= ErrorInfo.errorThreshold

Expand All @@ -26,6 +28,16 @@ const sendError = (name: string, apiUrl: string, trackData: any) => {
// hot fix to prevent spam for now.
const blacklistPathBff = ['/v1/notification/me', '/v1/tokens/score']

let isOnline = true
function onConnect() {
isOnline = true
}
function onDisconnect() {
isOnline = false
}
window.addEventListener('online', onConnect, false)
window.addEventListener('offline', onDisconnect, false)

/**
* check error status: blocked, maybe cors issues or server down
* only check bff api + 2 route apis
Expand All @@ -35,12 +47,15 @@ export const checkIamDown = (axiosErr: AxiosError) => {
const response = axiosErr?.response?.data

const isDie =
navigator.onLine && // not track when internet issue
isOnline && // not track when internet issue
statusCode !== 401 && // not track when token expired
(!response || // block cors
(statusCode === 404 && response === '404 page not found') || // wrong path
(statusCode && statusCode >= 500 && statusCode <= 599)) // server down

const apiUrl = axiosErr?.config?.url ?? ''
if (isDie) apiDowns.push(apiUrl)

const trackData = {
config: {
data: axiosErr?.config?.data,
Expand All @@ -55,8 +70,8 @@ export const checkIamDown = (axiosErr: AxiosError) => {
tokenInfoSignIn: localStorage.o2_sign_in,
tokenInfoGuest: localStorage.o2_guest,
profileInfo: localStorage.redux_localstorage_simple_profile,
apiDowns,
}
const apiUrl = axiosErr?.config?.url ?? ''

const isRouteApiDie =
isDie && (apiUrl.endsWith(AGGREGATOR_API_PATHS.GET_ROUTE) || apiUrl.endsWith(AGGREGATOR_API_PATHS.BUILD_ROUTE))
Expand Down

0 comments on commit 780644f

Please sign in to comment.