Skip to content

Commit

Permalink
refactor(dynamic-farm): using multicall from redux hooks (#2183)
Browse files Browse the repository at this point in the history
* refactor: reduce rpc of dynamic farm

* fix: re-render filtered farm v1

* revert env
  • Loading branch information
viet-nv authored Sep 20, 2023
1 parent c3cba5b commit 4a22545
Show file tree
Hide file tree
Showing 28 changed files with 609 additions and 588 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@
"@typescript-eslint/eslint-plugin": "^5.58.0",
"@typescript-eslint/parser": "^5.58.0",
"@vitejs/plugin-react": "^3.1.0",
"@welldone-software/why-did-you-render": "^7.0.1",
"babel-plugin-lodash": "^3.3.4",
"babel-plugin-macros": "^3.1.0",
"env-cmd": "^10.1.0",
Expand Down Expand Up @@ -207,4 +208,4 @@
"@lingui/core": "3.14.0",
"@lingui/conf": "3.16.0"
}
}
}
6 changes: 4 additions & 2 deletions src/components/HorizontalScroll.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CSSProperties, ReactNode, useEffect, useRef } from 'react'
import { CSSProperties, Fragment, ReactNode, useEffect, useRef } from 'react'
import ScrollContainer from 'react-indiana-drag-scroll'
import { Flex } from 'rebass'
import styled from 'styled-components'
Expand Down Expand Up @@ -61,7 +61,9 @@ const HorizontalScroll = ({
>
<ScrollContainer innerRef={scrollRef} vertical={false} className="scroll-container" onScroll={handleShadow}>
<TagContainer style={style} ref={contentRef}>
{(items ?? []).map(renderItem)}
{(items ?? []).map(i => (
<Fragment key={i}>{renderItem(i)}</Fragment>
))}
</TagContainer>
</ScrollContainer>
</ScrollContainerWithGradient>
Expand Down
8 changes: 4 additions & 4 deletions src/components/YieldPools/ElasticFarmGroup/PostionDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import PriceVisualize from 'components/ProAmm/PriceVisualize'
import { MouseoverTooltipDesktopOnly } from 'components/Tooltip'
import useIsTickAtLimit from 'hooks/useIsTickAtLimit'
import useTheme from 'hooks/useTheme'
import { useElasticFarms, useFarmAction } from 'state/farms/elastic/hooks'
import { useFarmAction, useUserInfoByFarm } from 'state/farms/elastic/hooks'
import { FarmingPool, NFTPosition } from 'state/farms/elastic/types'
import { Bound } from 'state/mint/proamm/type'
import { formatTickPrice } from 'utils/formatTickPrice'
Expand Down Expand Up @@ -42,8 +42,8 @@ const PositionDetail = ({
}: Props) => {
const theme = useTheme()

const { userFarmInfo } = useElasticFarms()
const joinedPositions = userFarmInfo?.[farmAddress]?.joinedPositions[pool.pid] || []
const userInfo = useUserInfoByFarm(farmAddress)
const joinedPositions = userInfo?.joinedPositions[pool.pid] || []
const { unstake } = useFarmAction(farmAddress)

const joinedInfo = joinedPositions.find(jp => jp.nftId.toString() === item.nftId.toString())
Expand All @@ -61,7 +61,7 @@ const PositionDetail = ({
const priceLower = !isRevertPrice ? item.token0PriceLower : item.token0PriceUpper.invert()
const priceUpper = !isRevertPrice ? item.token0PriceUpper : item.token0PriceLower.invert()

const rewardByNft = userFarmInfo?.[farmAddress]?.rewardByNft
const rewardByNft = userInfo?.rewardByNft
const rewards = rewardByNft?.[pool.pid + '_' + item.nftId.toString()] || []

const rewardValue = rewards.reduce(
Expand Down
35 changes: 15 additions & 20 deletions src/components/YieldPools/ElasticFarmGroup/Row.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { ChainId, CurrencyAmount, Fraction } from '@kyberswap/ks-sdk-core'
import { computePoolAddress } from '@kyberswap/ks-sdk-elastic'
import { CurrencyAmount, Fraction } from '@kyberswap/ks-sdk-core'
import { Trans, t } from '@lingui/macro'
import dayjs from 'dayjs'
import { BigNumber } from 'ethers'
import { useEffect, useState } from 'react'
import React, { useEffect, useState } from 'react'
import { Info, Minus, Plus, Share2 } from 'react-feather'
import { Link } from 'react-router-dom'
import { useMedia } from 'react-use'
Expand All @@ -19,15 +18,15 @@ import Harvest from 'components/Icons/Harvest'
import InfoHelper from 'components/InfoHelper'
import { MouseoverTooltip, MouseoverTooltipDesktopOnly } from 'components/Tooltip'
import { APP_PATHS, ELASTIC_BASE_FEE_UNIT } from 'constants/index'
import { NETWORKS_INFO, isEVM } from 'constants/networks'
import { TOBE_EXTENDED_FARMING_POOLS } from 'constants/v2'
import { useActiveWeb3React } from 'hooks'
import { useProMMFarmContract } from 'hooks/useContract'
import { useProAmmPositions } from 'hooks/useProAmmPositions'
import useTheme from 'hooks/useTheme'
import { useShareFarmAddress } from 'state/farms/classic/hooks'
import { useElasticFarms, usePositionFilter } from 'state/farms/elastic/hooks'
import { useDepositedNftsByFarm, usePositionFilter, useUserInfoByFarm } from 'state/farms/elastic/hooks'
import { FarmingPool, NFTPosition } from 'state/farms/elastic/types'
import { getPoolAddress } from 'state/mint/proamm/utils'
import { useViewMode } from 'state/user/hooks'
import { VIEW_MODE } from 'state/user/reducer'
import { shortenAddress } from 'utils'
Expand Down Expand Up @@ -73,26 +72,22 @@ const Row = ({
const above1000 = useMedia('(min-width: 1000px)')

const [isRevertPrice, setIsRevertPrice] = useState(false)
const { userFarmInfo } = useElasticFarms()
const joinedPositions = userFarmInfo?.[fairlaunchAddress]?.joinedPositions[farmingPool.pid] || []
const userInfo = useUserInfoByFarm(fairlaunchAddress)

const joinedPositions = userInfo?.joinedPositions[farmingPool.pid] || []

const depositedPositionsByFarm = useDepositedNftsByFarm(fairlaunchAddress)

const depositedPositions =
userFarmInfo?.[fairlaunchAddress]?.depositedPositions.filter(pos => {
depositedPositionsByFarm.filter(pos => {
return (
pos.liquidity.toString() !== '0' &&
farmingPool.poolAddress.toLowerCase() ===
computePoolAddress({
factoryAddress: NETWORKS_INFO[isEVM(chainId) ? chainId : ChainId.MAINNET].elastic.coreFactory,
tokenA: pos.pool.token0,
tokenB: pos.pool.token1,
fee: pos.pool.fee,
initCodeHashManualOverride: NETWORKS_INFO[isEVM(chainId) ? chainId : ChainId.MAINNET].elastic.initCodeHash,
}).toLowerCase()
farmingPool.poolAddress.toLowerCase() === getPoolAddress(pos.pool).toLowerCase()
)
}) || []

const rewardPendings =
userFarmInfo?.[fairlaunchAddress]?.rewardPendings[farmingPool.pid] ||
userInfo?.rewardPendings[farmingPool.pid] ||
farmingPool.rewardTokens.map(token => CurrencyAmount.fromRawAmount(token, 0))

const rewardValue = rewardPendings.reduce(
Expand All @@ -108,7 +103,7 @@ const Row = ({
useEffect(() => {
const getFeeTargetInfo = async () => {
if (!contract || farmingPool.feeTarget === '0') return
const userJoinedPos = userFarmInfo?.[fairlaunchAddress].joinedPositions[farmingPool.pid] || []
const userJoinedPos = userInfo.joinedPositions[farmingPool.pid] || []

if (!userJoinedPos.length) {
setTargetPercent('')
Expand Down Expand Up @@ -143,7 +138,7 @@ const Row = ({
}

getFeeTargetInfo()
}, [contract, farmingPool.feeTarget, fairlaunchAddress, farmingPool.pid, userFarmInfo])
}, [contract, farmingPool.feeTarget, fairlaunchAddress, farmingPool.pid, userInfo])

const { positions } = useProAmmPositions(account)

Expand Down Expand Up @@ -537,4 +532,4 @@ const Row = ({
)
}

export default Row
export default React.memo(Row)
24 changes: 13 additions & 11 deletions src/components/YieldPools/ElasticFarmGroup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import { useProAmmNFTPositionManagerContract } from 'hooks/useContract'
import useTheme from 'hooks/useTheme'
import { Dots } from 'pages/Pool/styleds'
import { useWalletModalToggle } from 'state/application/hooks'
import { useElasticFarms, useFarmAction } from 'state/farms/elastic/hooks'
import { FarmingPool, UserInfo } from 'state/farms/elastic/types'
import { useDepositedNftsByFarm, useElasticFarms, useFarmAction, useUserInfoByFarm } from 'state/farms/elastic/hooks'
import { FarmingPool } from 'state/farms/elastic/types'
import { useSingleCallResult } from 'state/multicall/hooks'
import { useIsTransactionPending } from 'state/transactions/hooks'
import { useViewMode } from 'state/user/hooks'
Expand Down Expand Up @@ -61,7 +61,6 @@ type Props = {
pool?: FarmingPool,
) => void
pools: FarmingPool[]
userInfo?: UserInfo
onShowStepGuide: () => void
tokenPrices: { [key: string]: number }
}
Expand All @@ -80,19 +79,22 @@ enum SORT_DIRECTION {
DESC = 'desc',
}

const ProMMFarmGroup: React.FC<Props> = ({ address, onOpenModal, pools, userInfo, onShowStepGuide, tokenPrices }) => {
const ElasticFarmGroup: React.FC<Props> = ({ address, onOpenModal, pools, onShowStepGuide, tokenPrices }) => {
const theme = useTheme()
const { account, chainId } = useActiveWeb3React()
const above1000 = useMedia('(min-width: 1000px)')

const depositedPositions = useDepositedNftsByFarm(address)
const userInfo = useUserInfoByFarm(address)

const [searchParams, setSearchParams] = useSearchParams()
const sortField = searchParams.get('orderBy') || SORT_FIELD.MY_DEPOSIT
const sortDirection = searchParams.get('orderDirection') || SORT_DIRECTION.DESC

const { poolFeeLast24h } = useElasticFarms()

const depositedUsd =
userInfo?.depositedPositions.reduce(
depositedPositions.reduce(
(acc, cur) =>
acc +
Number(cur.amount0.toExact()) * (tokenPrices[cur.amount0.currency.wrapped.address] || 0) +
Expand All @@ -101,7 +103,7 @@ const ProMMFarmGroup: React.FC<Props> = ({ address, onOpenModal, pools, userInfo
) || 0

const userDepositedTokenAmounts =
userInfo?.depositedPositions.reduce<{
depositedPositions.reduce<{
[address: string]: CurrencyAmount<Token>
}>((result, pos) => {
const address0 = pos.amount0.currency.address
Expand Down Expand Up @@ -156,8 +158,8 @@ const ProMMFarmGroup: React.FC<Props> = ({ address, onOpenModal, pools, userInfo
}

const joinedPositions = userInfo?.joinedPositions[pool.pid] || []
const depositedPositions =
userInfo?.depositedPositions.filter(pos => {
const poolDepositedPositions =
depositedPositions.filter(pos => {
return (
pool.poolAddress.toLowerCase() ===
computePoolAddress({
Expand All @@ -171,7 +173,7 @@ const ProMMFarmGroup: React.FC<Props> = ({ address, onOpenModal, pools, userInfo
)
}) || []

const depositedUsd = depositedPositions.reduce(
const depositedUsd = poolDepositedPositions.reduce(
(usd, pos) =>
usd +
Number(pos.amount1.toExact()) * (tokenPrices[pos.pool.token1.address.toLowerCase()] || 0) +
Expand Down Expand Up @@ -258,7 +260,7 @@ const ProMMFarmGroup: React.FC<Props> = ({ address, onOpenModal, pools, userInfo
if (!pools) return null

const canHarvest = Object.values(userInfo?.rewardPendings || {}).some(rw => rw.some(item => item.greaterThan('0')))
const canWithdraw = !!userInfo?.depositedPositions.length
const canWithdraw = !!depositedPositions.length

const renderApproveButton = () => {
if (isApprovedForAll || tab === 'ended') {
Expand Down Expand Up @@ -747,4 +749,4 @@ const ProMMFarmGroup: React.FC<Props> = ({ address, onOpenModal, pools, userInfo
)
}

export default ProMMFarmGroup
export default ElasticFarmGroup
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ function ProMMDepositNFTModal({
<Select role="button" onClick={() => setShowMenu(prev => !prev)}>
{filterOptions.find(item => item.code === activeFilter)?.value}

<DropdownIcon rotate={showMenu} />
<DropdownIcon isRotate={showMenu} />

{showMenu && (
<SelectMenu ref={ref}>
Expand Down
5 changes: 3 additions & 2 deletions src/components/YieldPools/ElasticFarmModals/HarvestModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import Modal from 'components/Modal'
import { MouseoverTooltip } from 'components/Tooltip'
import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel'
import useTheme from 'hooks/useTheme'
import { useElasticFarms, useFarmAction } from 'state/farms/elastic/hooks'
import { useElasticFarms, useFarmAction, useJoinedPositions } from 'state/farms/elastic/hooks'
import { useTokenPrices } from 'state/tokenPrices/hooks'
import { formatDollarAmount } from 'utils/numbers'

Expand Down Expand Up @@ -42,7 +42,8 @@ function HarvestModal({
onDismiss: () => void
}) {
const theme = useTheme()
const { farms, userFarmInfo } = useElasticFarms()
const { farms } = useElasticFarms()
const userFarmInfo = useJoinedPositions()
const selectedFarm = farms?.find(farm => farm.id.toLowerCase() === farmsAddress.toLowerCase())

const { harvest } = useFarmAction(farmsAddress)
Expand Down
17 changes: 13 additions & 4 deletions src/components/YieldPools/ElasticFarmModals/StakeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,14 @@ import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel'
import { useProAmmPositions } from 'hooks/useProAmmPositions'
import useTheme from 'hooks/useTheme'
import { Tab } from 'pages/Pools/styleds'
import { StakeParam, useElasticFarms, useFarmAction, usePositionFilter } from 'state/farms/elastic/hooks'
import {
StakeParam,
useDepositedNftsByFarm,
useElasticFarms,
useFarmAction,
useJoinedPositions,
usePositionFilter,
} from 'state/farms/elastic/hooks'
import { NFTPosition } from 'state/farms/elastic/types'
import { useTokenPrices } from 'state/tokenPrices/hooks'
import { StyledInternalLink } from 'theme'
Expand Down Expand Up @@ -236,20 +243,22 @@ function StakeModal({

const { eligiblePositions } = usePositionFilter(positions || [], [poolAddress])

const { farms, userFarmInfo } = useElasticFarms()
const { farms } = useElasticFarms()
const userFarmInfo = useJoinedPositions()
const selectedFarm = farms?.find(farm => farm.id.toLowerCase() === selectedFarmAddress.toLowerCase())

const { stake, unstake, depositAndJoin } = useFarmAction(selectedFarmAddress)

const selectedPool = selectedFarm?.pools.find(pool => Number(pool.pid) === Number(poolId))

const { token0, token1 } = selectedPool || {}
const allDepositedPositions = useDepositedNftsByFarm(selectedFarmAddress)

const depositedNfts: ExplicitNFT[] = useMemo(() => {
if (!isEVM(chainId)) return []
const joinedPositions = userFarmInfo?.[selectedFarmAddress]?.joinedPositions?.[poolId] || []
const depositedPositions =
userFarmInfo?.[selectedFarmAddress].depositedPositions.filter(pos => {
allDepositedPositions.filter(pos => {
return (
selectedPool?.poolAddress.toLowerCase() ===
computePoolAddress({
Expand Down Expand Up @@ -294,7 +303,7 @@ function StakeModal({
})

return depositedNfts
}, [type, selectedPool, chainId, poolId, poolAddress, selectedFarmAddress, userFarmInfo])
}, [type, selectedPool, chainId, poolId, poolAddress, selectedFarmAddress, allDepositedPositions, userFarmInfo])

const depositAndJoinNfts = useMemo(
() =>
Expand Down
19 changes: 14 additions & 5 deletions src/components/YieldPools/ElasticFarmModals/WithdrawModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ import { useOnClickOutside } from 'hooks/useOnClickOutside'
import useParsedQueryString from 'hooks/useParsedQueryString'
import { usePool } from 'hooks/usePools'
import useTheme from 'hooks/useTheme'
import { useElasticFarms, useFarmAction, usePositionFilter } from 'state/farms/elastic/hooks'
import {
useDepositedNftsByFarm,
useElasticFarms,
useFarmAction,
useJoinedPositions,
usePositionFilter,
} from 'state/farms/elastic/hooks'
import { UserPositionFarm } from 'state/farms/elastic/types'
import { useTokenPrices } from 'state/tokenPrices/hooks'
import { PositionDetails } from 'types/position'
Expand Down Expand Up @@ -57,9 +63,10 @@ const PositionRow = ({
}) => {
const { token0: token0Address, token1: token1Address, fee: feeAmount, liquidity, tickLower, tickUpper } = position
const { unstake } = useFarmAction(farmAddress)
const { userFarmInfo } = useElasticFarms()
const userFarmInfo = useJoinedPositions()

const joinedPositions = userFarmInfo?.[farmAddress]?.joinedPositions

let pid: null | string = null
if (joinedPositions) {
Object.keys(joinedPositions).forEach(key => {
Expand Down Expand Up @@ -215,7 +222,8 @@ function WithdrawModal({
const { type: tab = 'active' } = useParsedQueryString<{ type: string }>()

const checkboxGroupRef = useRef<any>()
const { farms, userFarmInfo } = useElasticFarms()
const { farms } = useElasticFarms()
const userFarmInfo = useJoinedPositions()

const selectedFarm = farms?.find(farm => farm.id.toLowerCase() === selectedFarmAddress.toLowerCase())

Expand All @@ -229,7 +237,8 @@ function WithdrawModal({
)
.map(pool => pool.poolAddress.toLowerCase()) || []

const { depositedPositions = [], joinedPositions = {} } = userFarmInfo?.[selectedFarm?.id || ''] || {}
const depositedPositions = useDepositedNftsByFarm(selectedFarmAddress)
const { joinedPositions = {} } = userFarmInfo?.[selectedFarm?.id || ''] || {}

const userDepositedNFTs: PositionDetails[] = useMemo(
() =>
Expand Down Expand Up @@ -338,7 +347,7 @@ function WithdrawModal({
<Select role="button" onClick={() => setShowMenu(prev => !prev)}>
{filterOptions.find(item => item.code === activeFilter)?.value}

<DropdownIcon rotate={showMenu} />
<DropdownIcon isRotate={showMenu} />

{showMenu && (
<SelectMenu ref={ref}>
Expand Down
6 changes: 3 additions & 3 deletions src/components/YieldPools/ElasticFarmModals/styled.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,13 @@ export const SelectOption = styled.div`
color: ${({ theme }) => theme.subText};
`

export const DropdownIcon = styled.div<{ rotate?: boolean }>`
transform: rotate(${({ rotate }) => (rotate ? '-180deg' : '0')});
export const DropdownIcon = styled.div<{ isRotate?: boolean }>`
transform: rotate(${({ isRotate: rotate }) => (rotate ? '-180deg' : '0')});
height: 0;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 4px solid ${({ theme }) => theme.text};
transition: transform 300ms;
transform: rotate(${({ rotate }) => (rotate ? '-180deg' : '0')});
transform: rotate(${({ isRotate: rotate }) => (rotate ? '-180deg' : '0')});
`
Loading

0 comments on commit 4a22545

Please sign in to comment.