From b1b1813ec90c574ec543b2ada5fba4f2659d2df7 Mon Sep 17 00:00:00 2001 From: XiaoYhun Date: Fri, 21 Jul 2023 11:36:57 +0700 Subject: [PATCH 1/8] try fix long number kyberdao approve issue (#2083) * try fix long number approve * update approve parsed amount * fix compare float incorrect * chore --- src/pages/KyberDAO/StakeKNC/MigrateModal.tsx | 22 ++++++---------- .../KyberDAO/StakeKNC/StakeKNCComponent.tsx | 25 ++++++++----------- 2 files changed, 19 insertions(+), 28 deletions(-) diff --git a/src/pages/KyberDAO/StakeKNC/MigrateModal.tsx b/src/pages/KyberDAO/StakeKNC/MigrateModal.tsx index 047840df45..5b70004289 100644 --- a/src/pages/KyberDAO/StakeKNC/MigrateModal.tsx +++ b/src/pages/KyberDAO/StakeKNC/MigrateModal.tsx @@ -1,4 +1,4 @@ -import { ChainId, Token, TokenAmount } from '@kyberswap/ks-sdk-core' +import { ChainId, Token } from '@kyberswap/ks-sdk-core' import { Trans, t } from '@lingui/macro' import { parseUnits } from 'ethers/lib/utils' import { useEffect, useState } from 'react' @@ -10,6 +10,7 @@ import { ButtonLight, ButtonPrimary } from 'components/Button' import { AutoColumn } from 'components/Column' import Modal from 'components/Modal' import Row, { AutoRow, RowBetween } from 'components/Row' +import useParsedAmount from 'components/SwapForm/hooks/useParsedAmount' import { useActiveWeb3React } from 'hooks' import { useKyberDAOInfo, useKyberDaoStakeActions } from 'hooks/kyberdao' import { ApprovalState, useApproveCallback } from 'hooks/useApproveCallback' @@ -49,20 +50,13 @@ export default function MigrateModal({ const { migrate } = useKyberDaoStakeActions() const [value, setValue] = useState('1') const [error, setError] = useState('') - const [approval, approveCallback] = useApproveCallback( - value - ? TokenAmount.fromRawAmount( - new Token( - chainId === ChainId.GÖRLI ? ChainId.GÖRLI : ChainId.MAINNET, - kyberDAOInfo?.KNCLAddress || '', - 18, - 'KNCL', - ), - parseUnits((+value).toFixed(18).toString(), 18).toString(), - ) - : undefined, - kyberDAOInfo?.KNCAddress, + const parsedAmount = useParsedAmount( + new Token(chainId === ChainId.GÖRLI ? ChainId.GÖRLI : ChainId.MAINNET, kyberDAOInfo?.KNCLAddress || '', 18, 'KNCL'), + value, ) + + const [approval, approveCallback] = useApproveCallback(parsedAmount, kyberDAOInfo?.KNCAddress) + const oldKNCBalance = useTokenBalance(kyberDAOInfo?.KNCLAddress || '') useEffect(() => { // Check if too many decimals diff --git a/src/pages/KyberDAO/StakeKNC/StakeKNCComponent.tsx b/src/pages/KyberDAO/StakeKNC/StakeKNCComponent.tsx index 78544d1a66..da369e03a5 100644 --- a/src/pages/KyberDAO/StakeKNC/StakeKNCComponent.tsx +++ b/src/pages/KyberDAO/StakeKNC/StakeKNCComponent.tsx @@ -1,4 +1,4 @@ -import { ChainId, Token, TokenAmount } from '@kyberswap/ks-sdk-core' +import { ChainId, Token } from '@kyberswap/ks-sdk-core' import { Trans, t } from '@lingui/macro' import { formatUnits, parseUnits } from 'ethers/lib/utils' import { lighten } from 'polished' @@ -18,6 +18,7 @@ import WarningIcon from 'components/Icons/WarningIcon' import InfoHelper from 'components/InfoHelper' import Input from 'components/NumericalInput' import Row, { AutoRow, RowBetween, RowFit } from 'components/Row' +import useParsedAmount from 'components/SwapForm/hooks/useParsedAmount' import { MouseoverTooltip } from 'components/Tooltip' import TransactionConfirmationModal, { TransactionErrorContent } from 'components/TransactionConfirmationModal' import { useActiveWeb3React } from 'hooks' @@ -204,6 +205,7 @@ export default function StakeKNCComponent() { const { account, chainId } = useActiveWeb3React() const kyberDAOInfo = useKyberDAOInfo() const { stakedBalance, KNCBalance, delegatedAddress } = useStakingInfo() + console.log('🚀 ~ file: StakeKNCComponent.tsx:208 ~ StakeKNCComponent ~ KNCBalance:', KNCBalance) const { calculateVotingPower } = useVotingInfo() const isDelegated = !!delegatedAddress && delegatedAddress !== account const { stake, unstake, delegate, undelegate } = useKyberDaoStakeActions() @@ -235,8 +237,8 @@ export default function StakeKNCComponent() { if (!inputValue || isNaN(parseFloat(inputValue)) || parseFloat(inputValue) <= 0) { setErrorMessage(t`Invalid amount`) } else if ( - (parseFloat(inputValue) > parseFloat(formatUnits(KNCBalance)) && activeTab === STAKE_TAB.Stake) || - (parseFloat(inputValue) > parseFloat(formatUnits(stakedBalance)) && activeTab === STAKE_TAB.Unstake) + (parseUnits(inputValue, 18).gt(KNCBalance) && activeTab === STAKE_TAB.Stake) || + (parseUnits(inputValue, 18).gt(stakedBalance) && activeTab === STAKE_TAB.Unstake) ) { setErrorMessage(t`Insufficient amount`) } else if (activeTab === STAKE_TAB.Delegate && !isAddress(chainId, delegateAddress)) { @@ -265,18 +267,13 @@ export default function StakeKNCComponent() { const toggleYourTransactions = useToggleModal(ApplicationModal.YOUR_TRANSACTIONS_STAKE_KNC) const { switchToEthereum } = useSwitchToEthereum() const { mixpanelHandler } = useMixpanel() + const parsedAmount = useParsedAmount( + new Token(chainId === ChainId.GÖRLI ? ChainId.GÖRLI : ChainId.MAINNET, kyberDAOInfo?.KNCAddress || '', 18, 'KNC'), + inputValue, + ) + const [approvalKNC, approveCallback] = useApproveCallback( - activeTab === STAKE_TAB.Stake && inputValue - ? TokenAmount.fromRawAmount( - new Token( - chainId === ChainId.GÖRLI ? ChainId.GÖRLI : ChainId.MAINNET, - kyberDAOInfo?.KNCAddress || '', - 18, - 'KNC', - ), - parseUnits((+inputValue).toFixed(18).toString(), 18).toString(), - ) - : undefined, + activeTab === STAKE_TAB.Stake && inputValue ? parsedAmount : undefined, kyberDAOInfo?.staking, ) From af8672454e48540c7b639aff05d261e27e628c01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Ho=C3=A0i=20Danh?= <33005392+nguyenhoaidanh@users.noreply.github.com> Date: Fri, 21 Jul 2023 14:48:18 +0700 Subject: [PATCH 2/8] chore: hide bridge noti + update number rate order (#2096) * fix number rate order * hide bridge --- src/components/swapv2/LimitOrder/helpers.ts | 3 ++- src/pages/NotificationCenter/Menu/index.tsx | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/components/swapv2/LimitOrder/helpers.ts b/src/components/swapv2/LimitOrder/helpers.ts index e783095ece..7bbefc2d0d 100644 --- a/src/components/swapv2/LimitOrder/helpers.ts +++ b/src/components/swapv2/LimitOrder/helpers.ts @@ -116,7 +116,8 @@ export const formatRateLimitOrder = (order: LimitOrder, invert: boolean) => { } catch (error) { console.log(error) } - return formatNumberWithPrecisionRange(parseFloat(rateValue.toFixed(16)), 0, 8) + const float = parseFloat(rateValue.toFixed(16)) + return formatNumberWithPrecisionRange(float, 0, float < 1e-8 ? 16 : 8) } export const calcPercentFilledOrder = (value: string, total: string, decimals: number) => { diff --git a/src/pages/NotificationCenter/Menu/index.tsx b/src/pages/NotificationCenter/Menu/index.tsx index b389ce3720..c4ef4afc92 100644 --- a/src/pages/NotificationCenter/Menu/index.tsx +++ b/src/pages/NotificationCenter/Menu/index.tsx @@ -92,10 +92,10 @@ const menuItems: MenuItemType[] = [ route: PROFILE_MANAGE_ROUTES.LIMIT_ORDERS, type: PrivateAnnouncementType.LIMIT_ORDER, }, - { - route: PROFILE_MANAGE_ROUTES.BRIDGE, - type: PrivateAnnouncementType.BRIDGE_ASSET, - }, + // { + // route: PROFILE_MANAGE_ROUTES.BRIDGE, + // type: PrivateAnnouncementType.BRIDGE_ASSET, + // }, { route: PROFILE_MANAGE_ROUTES.CROSS_CHAIN, type: PrivateAnnouncementType.CROSS_CHAIN, From 4f1196b43ffa62a170856cef4d422ae52ea014f7 Mon Sep 17 00:00:00 2001 From: XiaoYhun Date: Fri, 21 Jul 2023 16:30:35 +0700 Subject: [PATCH 3/8] fix some minor UI bugs (#2097) --- src/components/KyberAITokenBanner/index.tsx | 6 +++--- src/components/swapv2/styleds.tsx | 2 +- src/pages/SwapV3/index.tsx | 2 +- .../TrueSightV2/components/FeedbackSurvey.tsx | 18 ++++++------------ .../TrueSightV2/components/TutorialModal.tsx | 4 ++-- 5 files changed, 13 insertions(+), 19 deletions(-) diff --git a/src/components/KyberAITokenBanner/index.tsx b/src/components/KyberAITokenBanner/index.tsx index 59a4b0f0c5..2729469d6c 100644 --- a/src/components/KyberAITokenBanner/index.tsx +++ b/src/components/KyberAITokenBanner/index.tsx @@ -46,17 +46,17 @@ const KyberAITokenBanner = ({ const { data: tokenInputOverview } = useTokenDetailQuery( { address: token0?.address, chain }, - { skip: !token0?.address || !account || !isWhiteList, refetchOnMountOrArgChange: true }, + { skip: !token0?.address || !account || !isWhiteList || !chain, refetchOnMountOrArgChange: true }, ) const { data: tokenOutputOverview } = useTokenDetailQuery( { address: token1?.address, chain }, - { skip: !token1?.address || !account || !isWhiteList, refetchOnMountOrArgChange: true }, + { skip: !token1?.address || !account || !isWhiteList || !chain, refetchOnMountOrArgChange: true }, ) const { data: tokenNativeOverview } = useTokenDetailQuery( { address: NativeCurrencies[chainId].wrapped.address, chain }, - { skip: !account || !isWhiteList, refetchOnMountOrArgChange: true }, + { skip: !account || !isWhiteList || !chain, refetchOnMountOrArgChange: true }, ) const token: { kyberScore?: number; label?: string; address?: string; logo?: string; symbol?: string } | undefined = diff --git a/src/components/swapv2/styleds.tsx b/src/components/swapv2/styleds.tsx index 1265ec2a89..47a125b201 100644 --- a/src/components/swapv2/styleds.tsx +++ b/src/components/swapv2/styleds.tsx @@ -221,7 +221,7 @@ export const InfoComponentsWrapper = styled.div` export const KyberAIBannerWrapper = styled.div` width: 100%; - height: 84px; + max-height: 84px; margin-bottom: 16px; ${({ theme }) => theme.mediaWidth.upToSmall` diff --git a/src/pages/SwapV3/index.tsx b/src/pages/SwapV3/index.tsx index b0bdd9a61a..af26823214 100644 --- a/src/pages/SwapV3/index.tsx +++ b/src/pages/SwapV3/index.tsx @@ -291,7 +291,7 @@ export default function Swap() { - - - - - - - - - + + + Feedback diff --git a/src/pages/TrueSightV2/components/TutorialModal.tsx b/src/pages/TrueSightV2/components/TutorialModal.tsx index ab286e1d70..1e517119bb 100644 --- a/src/pages/TrueSightV2/components/TutorialModal.tsx +++ b/src/pages/TrueSightV2/components/TutorialModal.tsx @@ -114,8 +114,8 @@ const steps = [

For traders who are in discovery mode, start with the Rankings section. Here you will see top tokens under each of the 7 categories -{' '} - Bullish, Bearish, Top CEX Inflow, Top CEX Outflow, Top Traded, Trending Soon, Currently Trending. - We update the token rankings multiple times a day! + Bullish, Bearish, Top CEX Inflow, Top CEX Outflow, Top Traded, Trending Soon, Currently Trending. We + update the token rankings multiple times a day!

{' '}

For traders looking to spot alpha on specific tokens, start with the Explore section. You will find a number From 8e35f010336e9d12b892a1797c403e59019b93d8 Mon Sep 17 00:00:00 2001 From: Nam Nguyen Date: Fri, 21 Jul 2023 18:17:37 +0700 Subject: [PATCH 4/8] refactor: clean code (#2099) --- src/constants/connectors/utils.ts | 2 +- src/pages/KyberDAO/KNCUtility/Table.tsx | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/constants/connectors/utils.ts b/src/constants/connectors/utils.ts index a5baf69dd5..4baa970750 100644 --- a/src/constants/connectors/utils.ts +++ b/src/constants/connectors/utils.ts @@ -21,7 +21,7 @@ export const getIsMetaMaskWallet = () => export const getIsCoinbaseWallet = () => Boolean( (window.ethereum?.isCoinbaseWallet || window.ethereum?.providers?.some(p => p?.isCoinbaseWallet)) && - !window.ethereum.isKrystalWallet, + !window.ethereum?.isKrystalWallet, ) export const getIsBraveWallet = () => Boolean(checkForBraveBrowser() && window.ethereum?.isBraveWallet) diff --git a/src/pages/KyberDAO/KNCUtility/Table.tsx b/src/pages/KyberDAO/KNCUtility/Table.tsx index c07dfbedca..2ddde54e3e 100644 --- a/src/pages/KyberDAO/KNCUtility/Table.tsx +++ b/src/pages/KyberDAO/KNCUtility/Table.tsx @@ -42,7 +42,6 @@ export const Row = styled.div<{ $background?: string }>` export const TableHeader = styled(Row)` border-top: none; - background: linear-gradient(0deg, #134134 0%, #0f221e 100%); background: linear-gradient( 0deg, ${({ theme }) => transparentize(0.5, theme.primary)} 0%, From 1dab0a56b44992d0d8b091b296f7e28ab1be46ce Mon Sep 17 00:00:00 2001 From: Nam Nguyen Date: Fri, 21 Jul 2023 18:48:26 +0700 Subject: [PATCH 5/8] fix: arrow scroll down menu (#2100) --- src/components/Menu/index.tsx | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/components/Menu/index.tsx b/src/components/Menu/index.tsx index 4d1383051a..ef7cabfe5f 100644 --- a/src/components/Menu/index.tsx +++ b/src/components/Menu/index.tsx @@ -1,5 +1,5 @@ import { Trans, t } from '@lingui/macro' -import { useEffect, useRef, useState } from 'react' +import { useEffect, useState } from 'react' import { isMobile } from 'react-device-detect' import { Award, @@ -266,28 +266,27 @@ export default function Menu() { mixpanelHandler(MIXPANEL_TYPE.MENU_PREFERENCE_CLICK, { menu: name }) } - const wrapperNode = useRef(null) + const [wrapperNode, setWrapperNode] = useState(null) const [showScroll, setShowScroll] = useState(false) useEffect(() => { - const wrapper = wrapperNode.current - if (wrapper) { + if (wrapperNode) { const abortController = new AbortController() const onScroll = () => { if (abortController.signal.aborted) return - setShowScroll(Math.abs(wrapper.offsetHeight + wrapper.scrollTop - wrapper.scrollHeight) > 10) //no need to show scroll down when scrolled to last 10px + setShowScroll(Math.abs(wrapperNode.offsetHeight + wrapperNode.scrollTop - wrapperNode.scrollHeight) > 10) //no need to show scroll down when scrolled to last 10px } onScroll() - wrapper.addEventListener('scroll', onScroll) + wrapperNode.addEventListener('scroll', onScroll) window.addEventListener('resize', onScroll) return () => { abortController.abort() - wrapper.removeEventListener('scroll', onScroll) + wrapperNode.removeEventListener('scroll', onScroll) window.removeEventListener('resize', onScroll) } } return - }, []) + }, [wrapperNode]) return ( @@ -308,7 +307,7 @@ export default function Menu() { ) : ( - + setWrapperNode(wrapperNode)}> <Trans>Menu</Trans> From b49bef8c61fe4ffa64144b287556e698fd63682e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Ho=C3=A0i=20Danh?= <33005392+nguyenhoaidanh@users.noreply.github.com> Date: Mon, 24 Jul 2023 10:15:11 +0700 Subject: [PATCH 6/8] Fix otp modal can not paste at the second time (#2111) * fix can not paste otp at the second time ++ * remove nested if block --- src/pages/App.tsx | 2 +- src/pages/{ => Verify}/VerifyAuth/index.tsx | 0 src/pages/Verify/VerifyCodeModal/OtpInput.tsx | 20 +- src/state/transactions/updater.tsx | 196 +++++++++--------- 4 files changed, 107 insertions(+), 111 deletions(-) rename src/pages/{ => Verify}/VerifyAuth/index.tsx (100%) diff --git a/src/pages/App.tsx b/src/pages/App.tsx index cf5711d63b..526159bd25 100644 --- a/src/pages/App.tsx +++ b/src/pages/App.tsx @@ -43,7 +43,7 @@ import { getLimitOrderContract, isAddressString, shortenAddress } from 'utils' import ElasticLegacyNotice from './ElasticLegacy/ElasticLegacyNotice' import Icons from './Icons' -import VerifyAuth from './VerifyAuth' +import VerifyAuth from './Verify/VerifyAuth' // test page for swap only through elastic const ElasticSwap = lazy(() => import('./ElasticSwap')) diff --git a/src/pages/VerifyAuth/index.tsx b/src/pages/Verify/VerifyAuth/index.tsx similarity index 100% rename from src/pages/VerifyAuth/index.tsx rename to src/pages/Verify/VerifyAuth/index.tsx diff --git a/src/pages/Verify/VerifyCodeModal/OtpInput.tsx b/src/pages/Verify/VerifyCodeModal/OtpInput.tsx index d870a866ce..ad076a5419 100644 --- a/src/pages/Verify/VerifyCodeModal/OtpInput.tsx +++ b/src/pages/Verify/VerifyCodeModal/OtpInput.tsx @@ -160,29 +160,27 @@ const OTPInput = ({ onChange(otpValue) } - const onPaste = (event: React.ClipboardEvent) => { + const onPaste = (event: React.ClipboardEvent, index: number) => { event.preventDefault() const otp = getOTPValue() - let nextActiveInput = activeInput + let nextActiveInput = index - // Get pastedData in an array of max size (num of inputs - current position) - const pastedData = event.clipboardData - .getData('text/plain') - .slice(0, numInputs - activeInput) - .split('') + const pastedData = event.clipboardData.getData('text/plain').split('').slice(0, numInputs) // Prevent pasting if the clipboard data contains non-numeric values for number inputs if (isInputNum && pastedData.some(value => isNaN(Number(value)))) { return } + let count = 0 // Paste data from focused input onwards for (let pos = 0; pos < numInputs; ++pos) { - if (pos >= activeInput && pastedData.length > 0) { - otp[pos] = pastedData.shift() ?? '' - nextActiveInput++ + if (pos >= index) { + otp[pos] = pastedData[count++] ?? '' + otp[pos] && nextActiveInput++ } + otp[pos] ||= '' } focusInput(nextActiveInput) @@ -201,7 +199,7 @@ const OTPInput = ({ onFocus: () => handleFocus()(index), onBlur: handleBlur, onKeyDown, - onPaste, + onPaste: e => onPaste(e, index), autoComplete: 'off', maxLength: 1, 'aria-label': `Please enter OTP character ${index + 1}`, diff --git a/src/state/transactions/updater.tsx b/src/state/transactions/updater.tsx index 4df5afbdfb..bf03eee505 100644 --- a/src/state/transactions/updater.tsx +++ b/src/state/transactions/updater.tsx @@ -81,122 +81,120 @@ export default function Updater(): null { .getTransaction(hash) .then(res => { const transaction = findTx(transactions, hash) - if (!transaction) return + if (!transaction || !res) return // !res this mean tx was drop + const { sentAtBlock, from, to, nonce, data } = transaction - // this mean tx was drop - if (res === null) { - if (sentAtBlock && from && to && nonce && data) - findReplacementTx(readProvider, sentAtBlock, { - from, - to, - nonce, - data, + if (sentAtBlock && from && to && nonce && data) + findReplacementTx(readProvider, sentAtBlock, { + from, + to, + nonce, + data, + }) + .then(newTx => { + if (newTx) { + dispatch( + replaceTx({ + chainId, + oldHash: hash, + newHash: newTx.hash, + }), + ) + } }) - .then(newTx => { - if (newTx) { - dispatch( - replaceTx({ - chainId, - oldHash: hash, - newHash: newTx.hash, - }), - ) - } - }) - .catch(() => { - dispatch(removeTx({ chainId, hash })) - }) - else { - dispatch(removeTx({ chainId, hash })) - } + .catch(() => { + dispatch(removeTx({ chainId, hash })) + }) + else { + dispatch(removeTx({ chainId, hash })) } }) .catch(console.warn) readProvider .getTransactionReceipt(hash) .then(receipt => { - if (receipt) { - const transaction = findTx(transactions, receipt.transactionHash) - if (!transaction) return - dispatch( - finalizeTransaction({ - chainId, - hash: receipt.transactionHash, - receipt: { - blockHash: receipt.blockHash, - status: receipt.status, - }, - needCheckSubgraph: includes(NEED_CHECK_SUBGRAPH_TRANSACTION_TYPES, transaction.type), - }), - ) + if (!receipt) { + dispatch(checkedTransaction({ chainId, hash, blockNumber: lastBlockNumber })) + return + } - transactionNotify({ + const transaction = findTx(transactions, receipt.transactionHash) + if (!transaction) return + dispatch( + finalizeTransaction({ + chainId, hash: receipt.transactionHash, - type: receipt.status === 1 ? NotificationType.SUCCESS : NotificationType.ERROR, - }) - if (receipt.status === 1 && transaction) { - const arbitrary = transaction.extraInfo?.arbitrary - switch (transaction.type) { - case TRANSACTION_TYPE.SWAP: { - if (arbitrary) { - if (account && arbitrary.isPermitSwap) { - dispatch(revokePermit({ chainId, address: arbitrary.inputAddress, account })) - } - mixpanelHandler(MIXPANEL_TYPE.SWAP_COMPLETED, { - arbitrary, - actual_gas: receipt.gasUsed || BigNumber.from(0), - gas_price: receipt.effectiveGasPrice || BigNumber.from(0), - tx_hash: receipt.transactionHash, - feeInfo: arbitrary.feeInfo, - }) - } - break - } - case TRANSACTION_TYPE.BRIDGE: { - if (arbitrary) { - mixpanelHandler(MIXPANEL_TYPE.BRIDGE_TRANSACTION_SUBMIT, { - ...arbitrary, - tx_hash: receipt.transactionHash, - }) - } - break + receipt: { + blockHash: receipt.blockHash, + status: receipt.status, + }, + needCheckSubgraph: includes(NEED_CHECK_SUBGRAPH_TRANSACTION_TYPES, transaction.type), + }), + ) + + transactionNotify({ + hash: receipt.transactionHash, + type: receipt.status === 1 ? NotificationType.SUCCESS : NotificationType.ERROR, + }) + if (receipt.status === 1) { + const arbitrary = transaction.extraInfo?.arbitrary + switch (transaction.type) { + case TRANSACTION_TYPE.SWAP: { + if (!arbitrary) return + if (account && arbitrary.isPermitSwap) { + dispatch(revokePermit({ chainId, address: arbitrary.inputAddress, account })) } - case TRANSACTION_TYPE.ELASTIC_COLLECT_FEE: { - if (arbitrary) { - mixpanelHandler(MIXPANEL_TYPE.ELASTIC_COLLECT_FEES_COMPLETED, arbitrary) - } - break + mixpanelHandler(MIXPANEL_TYPE.SWAP_COMPLETED, { + arbitrary, + actual_gas: receipt.gasUsed || BigNumber.from(0), + gas_price: receipt.effectiveGasPrice || BigNumber.from(0), + tx_hash: receipt.transactionHash, + feeInfo: arbitrary.feeInfo, + }) + break + } + case TRANSACTION_TYPE.BRIDGE: { + if (arbitrary) { + mixpanelHandler(MIXPANEL_TYPE.BRIDGE_TRANSACTION_SUBMIT, { + ...arbitrary, + tx_hash: receipt.transactionHash, + }) } - case TRANSACTION_TYPE.ELASTIC_INCREASE_LIQUIDITY: { - if (arbitrary) { - mixpanelHandler(MIXPANEL_TYPE.ELASTIC_INCREASE_LIQUIDITY_COMPLETED, { - ...arbitrary, - tx_hash: receipt.transactionHash, - }) - } - break + break + } + case TRANSACTION_TYPE.ELASTIC_COLLECT_FEE: { + if (arbitrary) { + mixpanelHandler(MIXPANEL_TYPE.ELASTIC_COLLECT_FEES_COMPLETED, arbitrary) } - case TRANSACTION_TYPE.CLAIM_REWARD: { - // claim campaign reward successfully - // reset id claiming when finished - if (window.location.pathname.startsWith(APP_PATHS.CAMPAIGN)) setClaimingCampaignRewardId(null) - break + break + } + case TRANSACTION_TYPE.ELASTIC_INCREASE_LIQUIDITY: { + if (arbitrary) { + mixpanelHandler(MIXPANEL_TYPE.ELASTIC_INCREASE_LIQUIDITY_COMPLETED, { + ...arbitrary, + tx_hash: receipt.transactionHash, + }) } - case TRANSACTION_TYPE.CANCEL_LIMIT_ORDER: { - if (arbitrary) { - mixpanelHandler(MIXPANEL_TYPE.LO_CANCEL_ORDER_SUBMITTED, { - ...arbitrary, - tx_hash: receipt.transactionHash, - }) - } - break + break + } + case TRANSACTION_TYPE.CLAIM_REWARD: { + // claim campaign reward successfully + // reset id claiming when finished + if (window.location.pathname.startsWith(APP_PATHS.CAMPAIGN)) setClaimingCampaignRewardId(null) + break + } + case TRANSACTION_TYPE.CANCEL_LIMIT_ORDER: { + if (arbitrary) { + mixpanelHandler(MIXPANEL_TYPE.LO_CANCEL_ORDER_SUBMITTED, { + ...arbitrary, + tx_hash: receipt.transactionHash, + }) } - default: - break + break } + default: + break } - } else { - dispatch(checkedTransaction({ chainId, hash, blockNumber: lastBlockNumber })) } }) .catch((error: any) => { From 780644f9e1cddac24513b25747c6515d82790bd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Ho=C3=A0i=20Danh?= <33005392+nguyenhoaidanh@users.noreply.github.com> Date: Mon, 24 Jul 2023 10:29:51 +0700 Subject: [PATCH 7/8] refactor: use meta aggregator api only when authen success (#2080) --- .../SwapForm/hooks/useBuildRoute.tsx | 4 +++- src/components/SwapForm/hooks/useGetRoute.ts | 12 +++++++++++- src/pages/App.tsx | 2 +- src/state/authen/reducer.ts | 3 +++ src/state/index.ts | 1 - src/utils/iamError.ts | 19 +++++++++++++++++-- 6 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/components/SwapForm/hooks/useBuildRoute.tsx b/src/components/SwapForm/hooks/useBuildRoute.tsx index 31008fd5ea..458c784ab8 100644 --- a/src/components/SwapForm/hooks/useBuildRoute.tsx +++ b/src/components/SwapForm/hooks/useBuildRoute.tsx @@ -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' @@ -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 => { if (!account) { diff --git a/src/components/SwapForm/hooks/useGetRoute.ts b/src/components/SwapForm/hooks/useGetRoute.ts index 3a3b9e4fc9..49e17673bd 100644 --- a/src/components/SwapForm/hooks/useGetRoute.ts +++ b/src/components/SwapForm/hooks/useGetRoute.ts @@ -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, @@ -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' @@ -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() diff --git a/src/pages/App.tsx b/src/pages/App.tsx index 526159bd25..d306a5e500 100644 --- a/src/pages/App.tsx +++ b/src/pages/App.tsx @@ -119,7 +119,7 @@ const preloadImages = () => { const SwapPage = () => { const { chainId } = useActiveWeb3React() useSyncNetworkParamWithStore() - return {chainId === ChainId.SOLANA ? : } + return chainId === ChainId.SOLANA ? : } const RedirectWithNetworkPrefix = () => { diff --git a/src/state/authen/reducer.ts b/src/state/authen/reducer.ts index 993f7dedd7..7310fcf4f4 100644 --- a/src/state/authen/reducer.ts +++ b/src/state/authen/reducer.ts @@ -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 @@ -31,6 +32,7 @@ const DEFAULT_AUTHEN_STATE: AuthenState = { signedUserInfo: undefined, isLogin: false, pendingAuthentication: true, + authenticationSuccess: false, isConnectingWallet: false, showConfirmProfile: false, autoSignIn: { @@ -61,6 +63,7 @@ const slice = createSlice({ state.anonymousUserInfo = undefined } state.isLogin = !isAnonymous + if (profile) state.authenticationSuccess = true }, setConfirmChangeProfile: (state, { payload }: PayloadAction) => { state.showConfirmProfile = payload diff --git a/src/state/index.ts b/src/state/index.ts index 19f678d72b..e043d036d9 100644 --- a/src/state/index.ts +++ b/src/state/index.ts @@ -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', diff --git a/src/utils/iamError.ts b/src/utils/iamError.ts index 2b388d6c41..e75f3ec6c2 100644 --- a/src/utils/iamError.ts +++ b/src/utils/iamError.ts @@ -13,6 +13,8 @@ const ErrorInfo = { sentAlertRouteApi: false, } +const apiDowns: string[] = [] + const isIamApiDown = () => ErrorInfo.iamApoError >= ErrorInfo.errorThreshold const isRouteApiDown = () => ErrorInfo.routeApiError >= ErrorInfo.errorThreshold @@ -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 @@ -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, @@ -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)) From dc80333fcf788ca84ab02facc4e1337e37b5c92a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nguy=E1=BB=85n=20Ho=C3=A0i=20Danh?= <33005392+nguyenhoaidanh@users.noreply.github.com> Date: Mon, 24 Jul 2023 13:09:53 +0700 Subject: [PATCH 8/8] update: logic rank kyberai (#2112) --- .../TrueSightV2/pages/RegisterWhitelist/WaitListForm.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/pages/TrueSightV2/pages/RegisterWhitelist/WaitListForm.tsx b/src/pages/TrueSightV2/pages/RegisterWhitelist/WaitListForm.tsx index c522e71100..4adbae66fb 100644 --- a/src/pages/TrueSightV2/pages/RegisterWhitelist/WaitListForm.tsx +++ b/src/pages/TrueSightV2/pages/RegisterWhitelist/WaitListForm.tsx @@ -85,7 +85,9 @@ export default function EmailForm({ ) : rankNo === 2 ? ( 1 user is ahead of you ) : ( - {rankNo ? formattedNum(rankNo - 1 + '') : t`Many`} users are ahead of you! + + {rankNo && rankNo <= 101 ? formattedNum(rankNo - 1 + '') : t`Many`} users are ahead of you! + )} )}