Skip to content

Commit

Permalink
Improvement/zap (#2364)
Browse files Browse the repository at this point in the history
* fix: add tracking

* fix: price impact

* fix: red2

* fix: token symbol
  • Loading branch information
viet-nv authored Nov 7, 2023
1 parent d2acde1 commit eaae88f
Show file tree
Hide file tree
Showing 15 changed files with 228 additions and 76 deletions.
117 changes: 59 additions & 58 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,65 @@
s.parentNode.insertBefore(g, s)
})()
</script>

<script>
!(function () {
var analytics = (window.analytics = window.analytics || [])
if (!analytics.initialize)
if (analytics.invoked) window.console && console.error && console.error('Segment snippet included twice.')
else {
analytics.invoked = !0
analytics.methods = [
'trackSubmit',
'trackClick',
'trackLink',
'trackForm',
'pageview',
'identify',
'reset',
'group',
'track',
'ready',
'alias',
'debug',
'page',
'once',
'off',
'on',
'addSourceMiddleware',
'addIntegrationMiddleware',
'setAnonymousId',
'addDestinationMiddleware',
]
analytics.factory = function (e) {
return function () {
if (window.analytics.initialized) return window.analytics[e].apply(window.analytics, arguments)
var i = Array.prototype.slice.call(arguments)
i.unshift(e)
analytics.push(i)
return analytics
}
}
for (var i = 0; i < analytics.methods.length; i++) {
var key = analytics.methods[i]
analytics[key] = analytics.factory(key)
}
analytics.load = function (key, i) {
var t = document.createElement('script')
t.type = 'text/javascript'
t.async = !0
t.src = '/libs/red2.js'
var n = document.getElementsByTagName('script')[0]
n.parentNode.insertBefore(t, n)
analytics._loadOptions = i
}
analytics._writeKey = 'DgnqvAHbWsKaPnkdvC19EMC8DbXh1G52'
analytics.SNIPPET_VERSION = '4.16.1'
analytics.load('DgnqvAHbWsKaPnkdvC19EMC8DbXh1G52')
analytics.page()
}
})()
</script>
</head>

<body>
Expand Down Expand Up @@ -220,64 +279,6 @@
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script>
!(function () {
var analytics = (window.analytics = window.analytics || [])
if (!analytics.initialize)
if (analytics.invoked) window.console && console.error && console.error('Segment snippet included twice.')
else {
analytics.invoked = !0
analytics.methods = [
'trackSubmit',
'trackClick',
'trackLink',
'trackForm',
'pageview',
'identify',
'reset',
'group',
'track',
'ready',
'alias',
'debug',
'page',
'once',
'off',
'on',
'addSourceMiddleware',
'addIntegrationMiddleware',
'setAnonymousId',
'addDestinationMiddleware',
]
analytics.factory = function (e) {
return function () {
if (window.analytics.initialized) return window.analytics[e].apply(window.analytics, arguments)
var i = Array.prototype.slice.call(arguments)
i.unshift(e)
analytics.push(i)
return analytics
}
}
for (var i = 0; i < analytics.methods.length; i++) {
var key = analytics.methods[i]
analytics[key] = analytics.factory(key)
}
analytics.load = function (key, i) {
var t = document.createElement('script')
t.type = 'text/javascript'
t.async = !0
t.src = '/libs/red2.js'
var n = document.getElementsByTagName('script')[0]
n.parentNode.insertBefore(t, n)
analytics._loadOptions = i
}
analytics._writeKey = 'DgnqvAHbWsKaPnkdvC19EMC8DbXh1G52'
analytics.SNIPPET_VERSION = '4.16.1'
analytics.load('DgnqvAHbWsKaPnkdvC19EMC8DbXh1G52')
analytics.page()
}
})()
</script>
</body>

</html>
36 changes: 34 additions & 2 deletions src/components/ElasticZap/QuickZap.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { FeeAmount, Pool, Position } from '@kyberswap/ks-sdk-elastic'
import { Trans } from '@lingui/macro'
import { BigNumber } from 'ethers'
import mixpanel from 'mixpanel-browser'
import { rgba } from 'polished'
import { ReactElement, useMemo, useState } from 'react'
import { ReactElement, useEffect, useMemo, useState } from 'react'
import { Flex, Text } from 'rebass'
import styled from 'styled-components'

Expand Down Expand Up @@ -231,6 +232,20 @@ function QuickZapModal({ isOpen, onDismiss, poolAddress, tokenId, expectedChainI
const debouncedValue = useDebounce(typedValue, 300)

const amountIn = useParsedAmount(selectedCurrency, debouncedValue)

useEffect(() => {
if (amountIn?.toExact()) {
mixpanel.track('Zap - Input detailed', {
token0: selectedCurrency?.symbol,
token1: quoteCurrency?.symbol,
zap_token: selectedCurrency?.symbol,
token_amount: amountIn.toExact(),
source: tokenId ? 'my_pool_page' : 'pool_page',
})
}
// eslint-disable-next-line
}, [amountIn?.toExact(), selectedCurrency])

const equivalentQuoteAmount =
amountIn && pool && selectedCurrency && amountIn.multiply(pool.priceOf(selectedCurrency.wrapped))

Expand Down Expand Up @@ -376,6 +391,13 @@ function QuickZapModal({ isOpen, onDismiss, poolAddress, tokenId, expectedChainI
})

setAttempingTx(false)
mixpanel.track('Zap - Confirmed', {
token0: selectedCurrency?.symbol,
token1: quoteCurrency?.symbol,
zap_token: selectedCurrency?.symbol,
token_amount: amountIn.toExact(),
source: tokenId ? 'my_pool_page' : 'pool_page',
})
} catch (e) {
setAttempingTx(false)
setError(e?.message || JSON.stringify(e))
Expand Down Expand Up @@ -545,7 +567,17 @@ function QuickZapModal({ isOpen, onDismiss, poolAddress, tokenId, expectedChainI
</Overlay>

<Flex sx={{ gap: '1rem' }} marginTop="1.25rem">
<ButtonOutlined onClick={onDismiss}>
<ButtonOutlined
onClick={() => {
mixpanel.track('Zap - Canceled', {
source: tokenId ? 'my_pool_page' : 'pool_page',
token0: pool?.token0.symbol,
token1: pool?.token1.symbol,
zap_token: selectedCurrency?.symbol,
})
onDismiss()
}}
>
<Trans>Cancel</Trans>
</ButtonOutlined>

Expand Down
21 changes: 18 additions & 3 deletions src/components/ElasticZap/ZapDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,15 @@ export const useZapDetail = ({
newPooledAmount1 = newPooledAmount1.add(position.amount1)
}

const remainAmount0 =
pool?.token0 &&
result?.remainingAmount0 &&
CurrencyAmount.fromRawAmount(pool.token0, result.remainingAmount0.toString())
const remainAmount1 =
pool?.token1 &&
result?.remainingAmount1 &&
CurrencyAmount.fromRawAmount(pool.token1, result.remainingAmount1.toString())

const prices = useTokenPrices(
[WETH[chainId].address, currency0?.wrapped.address, currency1?.wrapped.address].filter(Boolean) as string[],
)
Expand All @@ -137,16 +146,22 @@ export const useZapDetail = ({

const amountInUsd = +(amountIn?.toExact() || '0') * (prices[amountIn?.currency?.wrapped.address || ''] || 0)

const amountUSDAfterSwap =
const remainAmountUsd =
currency0 && currency1
? +(remainAmount0?.toExact() || 0) * (prices[currency0.wrapped.address] || 0) +
+(remainAmount1?.toExact() || 0) * (prices[currency1.wrapped.address] || 0)
: 0

const amountUsdAfterSwap =
(currency0 && currency1
? +(newPooledAmount0?.toExact() || 0) * (prices[currency0.wrapped.address] || 0) +
+(newPooledAmount1?.toExact() || 0) * (prices[currency1.wrapped.address] || 0)
: 0
: 0) + remainAmountUsd

const priceImpact =
!prices[currency0?.wrapped?.address || ''] || !prices[currency1?.wrapped?.address || '']
? NaN
: ((amountInUsd - amountUSDAfterSwap) * 100) / amountInUsd
: ((amountInUsd - amountUsdAfterSwap) * 100) / amountInUsd
const priceImpactRes = checkPriceImpact(priceImpact)

const [gas, setGas] = useState('') // GWei
Expand Down
4 changes: 3 additions & 1 deletion src/components/SwapForm/SwapModal/SwapDetails/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ export default function SwapDetails({

const isPartnerSwap = window.location.pathname.includes(APP_PATHS.PARTNER_SWAP)

const feeAmount = routeSummary?.extraFee?.feeAmount

return (
<>
<AutoColumn
Expand Down Expand Up @@ -247,7 +249,7 @@ export default function SwapDetails({
</RowBetween>
)}

{!!routeSummary?.extraFee?.feeAmount && (
{!!feeAmount && feeAmount !== '0' && (
<RowBetween height="20px" style={{ gap: '16px' }}>
<RowFixed>
<TextDashed fontSize={12} fontWeight={400} color={theme.subText}>
Expand Down
2 changes: 1 addition & 1 deletion src/components/SwapForm/hooks/useBuildRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ const useBuildRoute = (args: Args) => {
slippageTolerance: slippage,
sender: account,
recipient: to || account,
source: clientId || 'kyberswap-ui',
source: clientId || 'kyberswap',
skipSimulateTx: false,
permit,
}
Expand Down
14 changes: 12 additions & 2 deletions src/components/YieldPools/ElasticFarmGroup/FarmCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { PartnerFarmTag } from 'components/YieldPools/PartnerFarmTag'
import { APP_PATHS, ELASTIC_BASE_FEE_UNIT } from 'constants/index'
import { TOBE_EXTENDED_FARMING_POOLS } from 'constants/v2'
import { useActiveWeb3React } from 'hooks'
import { useAllTokens } from 'hooks/Tokens'
import useTheme from 'hooks/useTheme'
import { useShareFarmAddress } from 'state/farms/classic/hooks'
import { FarmingPool, NFTPosition } from 'state/farms/elastic/types'
Expand Down Expand Up @@ -73,6 +74,7 @@ const FarmCard = ({
targetPercent,
targetPercentByNFT,
}: Props) => {
const allTokens = useAllTokens()
const { chainId, networkInfo } = useActiveWeb3React()
const [isRevertPrice, setIsRevertPrice] = useState(false)
const theme = useTheme()
Expand Down Expand Up @@ -104,8 +106,16 @@ const FarmCard = ({
pos => pos.pool.tickCurrent >= pos.tickLower && pos.pool.tickCurrent < pos.tickUpper,
).length

const token0Symbol = getTokenSymbolWithHardcode(chainId, pool?.token0?.wrapped?.address, pool.token0.symbol)
const token1Symbol = getTokenSymbolWithHardcode(chainId, pool?.token1?.wrapped?.address, pool.token1.symbol)
const token0Symbol = getTokenSymbolWithHardcode(
chainId,
pool?.token0?.wrapped?.address,
pool.token0.isNative ? pool.token0.symbol : allTokens[pool.token0.wrapped.address].symbol,
)
const token1Symbol = getTokenSymbolWithHardcode(
chainId,
pool?.token1?.wrapped?.address,
pool.token1.isNative ? pool.token1.symbol : allTokens[pool.token1.wrapped.address].symbol,
)

return (
<FlipCard flip={showPosition} joined={!!depositedPositions.length} data-testid={pool.id}>
Expand Down
14 changes: 12 additions & 2 deletions src/components/YieldPools/ElasticFarmGroup/Row.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { PartnerFarmTag } from 'components/YieldPools/PartnerFarmTag'
import { APP_PATHS, ELASTIC_BASE_FEE_UNIT } from 'constants/index'
import { TOBE_EXTENDED_FARMING_POOLS } from 'constants/v2'
import { useActiveWeb3React } from 'hooks'
import { useAllTokens } from 'hooks/Tokens'
import { useProMMFarmReadingContract } from 'hooks/useContract'
import { useProAmmPositions } from 'hooks/useProAmmPositions'
import useTheme from 'hooks/useTheme'
Expand Down Expand Up @@ -66,6 +67,7 @@ const Row = ({
onHarvest: () => void
tokenPrices: { [key: string]: number }
}) => {
const allTokens = useAllTokens()
const { chainId, networkInfo, account } = useActiveWeb3React()
const theme = useTheme()
const currentTimestamp = Math.floor(Date.now() / 1000)
Expand Down Expand Up @@ -306,8 +308,16 @@ const Row = ({
</Flex>
)

const symbol0 = getTokenSymbolWithHardcode(chainId, farmingPool.token0.wrapped.address, farmingPool.token0.symbol)
const symbol1 = getTokenSymbolWithHardcode(chainId, farmingPool.token1.wrapped.address, farmingPool.token1.symbol)
const symbol0 = getTokenSymbolWithHardcode(
chainId,
farmingPool.token0.wrapped.address,
farmingPool.token0.isNative ? farmingPool.token0.symbol : allTokens[farmingPool.token0.wrapped.address].symbol,
)
const symbol1 = getTokenSymbolWithHardcode(
chainId,
farmingPool.token1.wrapped.address,
farmingPool.token1.isNative ? farmingPool.token1.symbol : allTokens[farmingPool.token1.wrapped.address].symbol,
)

return (
<RowWrapper isOpen={rowOpen && !!depositedPositions.length} data-testid={farmingPool.id}>
Expand Down
2 changes: 1 addition & 1 deletion src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ export const CAMPAIGN_LEADERBOARD_ITEM_PER_PAGE = 10
export const CAMPAIGN_YOUR_TRANSACTIONS_ITEM_PER_PAGE = 10000

export const ELASTIC_BASE_FEE_UNIT = 100_000
export const KYBERSWAP_SOURCE = '{"source":"kyberswap-ui"}'
export const KYBERSWAP_SOURCE = '{"source":"kyberswap"}'

export const SWR_KEYS = {
getGrantProgramLeaderBoard: (id: number | string) => `${CAMPAIGN_BASE_URL}/api/v1/competitions/${id}/leaderboard`,
Expand Down
1 change: 1 addition & 0 deletions src/hooks/elasticZap/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ export function useZapInPoolResult(params?: {
}
}, [data, loadingAggregator, aggregatorOutputs, params])

console.debug('Zap: best return from zap helper ', bestRes)
return bestRes
}

Expand Down
Loading

0 comments on commit eaae88f

Please sign in to comment.