Skip to content

Commit

Permalink
feat: multiple farm v2 contracts
Browse files Browse the repository at this point in the history
  • Loading branch information
viet-nv committed Jul 24, 2023
1 parent 9b3112f commit 94e57c7
Show file tree
Hide file tree
Showing 10 changed files with 197 additions and 149 deletions.
25 changes: 23 additions & 2 deletions src/pages/Farm/ElasticFarmCombination.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Trans } from '@lingui/macro'
import { FC, useEffect, useState } from 'react'
import { FC, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { Flex, Text } from 'rebass'

Expand All @@ -12,6 +12,7 @@ import { ApplicationModal } from 'state/application/actions'
import { useModalOpen, useOpenModal } from 'state/application/hooks'
import { useFilteredFarms } from 'state/farms/elastic/hooks'
import { useFilteredFarmsV2 } from 'state/farms/elasticv2/hooks'
import { ElasticFarmV2 } from 'state/farms/elasticv2/types'

import ElasticFarmv2 from './ElasticFarmv2'

Expand All @@ -20,6 +21,18 @@ export const ElasticFarmCombination: FC = () => {
const { filteredFarms: filteredFarmsV1, loading: loadingV1 } = useFilteredFarms()
const { filteredFarms: filteredFarmsV2, loading: loadingV2 } = useFilteredFarmsV2()

const farmByContract = useMemo(() => {
return filteredFarmsV2?.reduce((acc, cur) => {
if (acc[cur.farmAddress]) {
acc[cur.farmAddress].push(cur)
} else {
acc[cur.farmAddress] = [cur]
}

return acc
}, {} as { [address: string]: ElasticFarmV2[] })
}, [filteredFarmsV2])

const [searchParams] = useSearchParams()
const search: string = searchParams.get('search')?.toLowerCase() || ''

Expand Down Expand Up @@ -75,7 +88,15 @@ export const ElasticFarmCombination: FC = () => {
<FarmStepGuide version={showFarmStepGuide} onChangeVersion={setShowFarmStepGuide} />
<ElasticFarms onShowStepGuide={() => setShowFarmStepGuide('v1')} noStaticFarm={!filteredFarmsV2.length} />
{!!filteredFarmsV1.length && !!filteredFarmsV2.length && <Divider />}
<ElasticFarmv2 onShowStepGuide={() => setShowFarmStepGuide('v2')} noDynamicFarm={!filteredFarmsV1.length} />

{Object.keys(farmByContract).map(contract => (
<ElasticFarmv2
onShowStepGuide={() => setShowFarmStepGuide('v2')}
noDynamicFarm={!filteredFarmsV1.length}
farmAddress={contract}
key={contract}
/>
))}
</>
)
}
4 changes: 2 additions & 2 deletions src/pages/Farm/ElasticFarmv2/components/FarmCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ function FarmCard({
const [, setSharePoolAddress] = useShareFarmAddress()

const currentTimestamp = Math.floor(Date.now() / 1000)
const stakedPos = useUserFarmV2Info(farm.fId)
const stakedPos = useUserFarmV2Info(farm.farmAddress, farm.fId)
let amountToken0 = CurrencyAmount.fromRawAmount(farm.token0.wrapped, 0)
let amountToken1 = CurrencyAmount.fromRawAmount(farm.token1.wrapped, 0)

Expand Down Expand Up @@ -162,7 +162,7 @@ function FarmCard({
setAttemptingTxn(false)
}

const { harvest } = useFarmV2Action()
const { harvest } = useFarmV2Action(farm.farmAddress)

const handleHarvest = useCallback(() => {
setShowConfirmModal(true)
Expand Down
4 changes: 2 additions & 2 deletions src/pages/Farm/ElasticFarmv2/components/ListView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export const ListView = ({
const [, setSharePoolAddress] = useShareFarmAddress()

const currentTimestamp = Math.floor(Date.now() / 1000)
const stakedPos = useUserFarmV2Info(farm.fId)
const stakedPos = useUserFarmV2Info(farm.farmAddress, farm.fId)
let amountToken0 = CurrencyAmount.fromRawAmount(farm.token0.wrapped, 0)
let amountToken1 = CurrencyAmount.fromRawAmount(farm.token1.wrapped, 0)

Expand Down Expand Up @@ -116,7 +116,7 @@ export const ListView = ({
setAttemptingTxn(false)
}

const { harvest } = useFarmV2Action()
const { harvest } = useFarmV2Action(farm.farmAddress)

const handleHarvest = useCallback(() => {
setShowConfirmModal(true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,10 +211,12 @@ const StakeWithNFTsModal = ({
isOpen,
onDismiss,
farm,
farmAddress,
}: {
farm: ElasticFarmV2
isOpen: boolean
onDismiss: () => void
farmAddress: string
}) => {
const [activeRange, setActiveRange] = useState(farm.ranges.filter(item => !item.isRemoved)[0])

Expand Down Expand Up @@ -252,7 +254,7 @@ const StakeWithNFTsModal = ({
})
mixpanel.track('ElasticFarmV2 - StakeModal - NFT Clicked', { nftId: tokenId })
}, [])
const { deposit } = useFarmV2Action()
const { deposit } = useFarmV2Action(farmAddress)

const [showConfirmModal, setShowConfirmModal] = useState(false)
const [txHash, setTxHash] = useState('')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ const NFTItem = ({
pos: UserFarmV2Info
onClick?: (tokenId: string) => void
}) => {
console.log(pos.nftId.toString(), pos.unclaimedRewardsUsd)
const priceLower = getTickToPrice(
pos.position.pool.token0.wrapped,
pos.position.pool.token1.wrapped,
Expand Down Expand Up @@ -250,12 +249,14 @@ const UnstakeWithNFTsModal = ({
isOpen,
onDismiss,
farm,
farmAddress,
}: {
isOpen: boolean
onDismiss: () => void
farm: ElasticFarmV2
farmAddress: string
}) => {
const stakedPos = useUserFarmV2Info(farm.fId)
const stakedPos = useUserFarmV2Info(farmAddress, farm.fId)
const theme = useTheme()
const [selectedPos, setSelectedPos] = useState<{ [tokenId: string]: boolean }>({})

Expand All @@ -278,7 +279,7 @@ const UnstakeWithNFTsModal = ({
mixpanel.track('ElasticFarmV2 - Unstake Modal - NFT Clicked', { nftId: tokenId })
}, [])

const { withdraw } = useFarmV2Action()
const { withdraw } = useFarmV2Action(farmAddress)

const [showConfirmModal, setShowConfirmModal] = useState(false)
const [txHash, setTxHash] = useState('')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,12 +252,14 @@ const UpdateLiquidityModal = ({
isOpen,
onDismiss,
farm,
farmAddress,
}: {
isOpen: boolean
onDismiss: () => void
farm: ElasticFarmV2
farmAddress: string
}) => {
const stakedPos = useUserFarmV2Info(farm.fId)
const stakedPos = useUserFarmV2Info(farmAddress, farm.fId)

const allEligiblePositions = stakedPos.filter(item => {
const range = farm.ranges.find(r => r.index === item.rangeId)
Expand Down Expand Up @@ -287,7 +289,7 @@ const UpdateLiquidityModal = ({
mixpanel.track('ElasticFarmV2 - Update Liquidity Modal - NFT Clicked', { nftId: tokenId })
}, [])

const { updateLiquidity } = useFarmV2Action()
const { updateLiquidity } = useFarmV2Action(farmAddress)

const [showConfirmModal, setShowConfirmModal] = useState(false)
const [txHash, setTxHash] = useState('')
Expand Down
20 changes: 13 additions & 7 deletions src/pages/Farm/ElasticFarmv2/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ import { MouseoverTooltip, MouseoverTooltipDesktopOnly, TextDashed } from 'compo
import { ConnectWalletButton } from 'components/YieldPools/ElasticFarmGroup/buttons'
import { FarmList } from 'components/YieldPools/ElasticFarmGroup/styleds'
import { ClickableText, ElasticFarmV2TableHeader } from 'components/YieldPools/styleds'
import { NETWORKS_INFO } from 'constants/networks'
import { EVMNetworkInfo } from 'constants/networks/type'
import { useActiveWeb3React } from 'hooks'
import { useProAmmNFTPositionManagerContract } from 'hooks/useContract'
import useTheme from 'hooks/useTheme'
Expand Down Expand Up @@ -68,13 +66,14 @@ const Wrapper = styled.div<{ noDynamicFarm?: boolean }>`
export default function ElasticFarmv2({
onShowStepGuide,
noDynamicFarm,
farmAddress,
}: {
onShowStepGuide: () => void
noDynamicFarm: boolean
farmAddress: string
}) {
const theme = useTheme()
const { chainId, account } = useActiveWeb3React()
const farmAddress = (NETWORKS_INFO[chainId] as EVMNetworkInfo).elastic?.farmV2Contract
const { account } = useActiveWeb3React()
const above1000 = useMedia('(min-width: 1000px)')
const upToExtraSmall = useMedia(`(max-width: ${MEDIA_WIDTHS.upToExtraSmall}px)`)

Expand All @@ -83,7 +82,7 @@ export default function ElasticFarmv2({
const sortField = searchParams.get('orderBy') || SORT_FIELD.MY_DEPOSIT
const sortDirection = searchParams.get('orderDirection') || SORT_DIRECTION.DESC

const { filteredFarms, farms, updatedFarms, userInfo } = useFilteredFarmsV2()
const { filteredFarms, farms, updatedFarms, userInfo } = useFilteredFarmsV2(farmAddress)
const depositedUsd = userInfo?.reduce((acc, cur) => acc + cur.positionUsdValue, 0) || 0

const depositedTokenAmounts: { [address: string]: CurrencyAmount<Currency> } = {}
Expand All @@ -97,7 +96,7 @@ export default function ElasticFarmv2({
else depositedTokenAmounts[address1] = depositedTokenAmounts[address1].add(item.position.amount1)
})

const { approve } = useFarmV2Action()
const { approve } = useFarmV2Action(farmAddress)
const posManager = useProAmmNFTPositionManagerContract()
const [approvalTx, setApprovalTx] = useState('')
const isApprovalTxPending = useIsTransactionPending(approvalTx)
Expand Down Expand Up @@ -408,20 +407,27 @@ export default function ElasticFarmv2({
</FarmList>

{!!selectedFarm && (
<StakeWithNFTsModal farm={selectedFarm} isOpen={!!selectedFarm} onDismiss={() => setSelectedFarm(null)} />
<StakeWithNFTsModal
farm={selectedFarm}
isOpen={!!selectedFarm}
onDismiss={() => setSelectedFarm(null)}
farmAddress={farmAddress}
/>
)}
{!!selectedUnstakeFarm && (
<UnstakeWithNFTsModal
farm={selectedUnstakeFarm}
isOpen={!!selectedUnstakeFarm}
onDismiss={() => setSelectedUnstakeFarm(null)}
farmAddress={farmAddress}
/>
)}
{!!selectedUpdateFarm && (
<UpdateLiquidityModal
farm={selectedUpdateFarm}
isOpen={!!selectedUpdateFarm}
onDismiss={() => setSelectedUpdateFarm(null)}
farmAddress={farmAddress}
/>
)}
</Wrapper>
Expand Down
29 changes: 16 additions & 13 deletions src/state/farms/elasticv2/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import { useLocalStorage } from 'react-use'
import FarmV2ABI from 'constants/abis/v2/farmv2.json'
import { ELASTIC_FARM_TYPE, FARM_TAB } from 'constants/index'
import { CONTRACT_NOT_FOUND_MSG } from 'constants/messages'
import { NETWORKS_INFO } from 'constants/networks'
import { EVMNetworkInfo } from 'constants/networks/type'
import { useActiveWeb3React } from 'hooks'
import { useContract, useProAmmNFTPositionManagerContract } from 'hooks/useContract'
import { useAppSelector } from 'state/hooks'
Expand All @@ -23,9 +21,12 @@ export const useElasticFarmsV2 = () => {
return elasticFarm || {}
}

export const useUserFarmV2Info = (fId: number): UserFarmV2Info[] => {
export const useUserFarmV2Info = (farmAddress: string, fId: number): UserFarmV2Info[] => {
const { userInfo } = useElasticFarmsV2()
return useMemo(() => userInfo?.filter(item => item.fId === fId) || [], [fId, userInfo])
return useMemo(
() => userInfo?.filter(item => item.fId === fId && item.farmAddress === farmAddress) || [],
[fId, userInfo, farmAddress],
)
}

export enum SORT_FIELD {
Expand All @@ -42,7 +43,7 @@ export enum SORT_DIRECTION {
DESC = 'desc',
}

export const useFilteredFarmsV2 = () => {
export const useFilteredFarmsV2 = (farmAddress?: string) => {
const { isEVM, chainId } = useActiveWeb3React()

const [searchParams] = useSearchParams()
Expand Down Expand Up @@ -101,6 +102,8 @@ export const useFilteredFarmsV2 = () => {
: farm.endTime < now || farm.isSettled,
)

if (farmAddress) result = result?.filter(item => item.farmAddress === farmAddress)

// Filter by search value
const searchAddress = isAddressString(chainId, search)
if (searchAddress) {
Expand Down Expand Up @@ -188,6 +191,7 @@ export const useFilteredFarmsV2 = () => {
isEVM,
search,
elasticType,
farmAddress,
])

return {
Expand All @@ -199,31 +203,30 @@ export const useFilteredFarmsV2 = () => {
}
}

export const useFarmV2Action = () => {
const { chainId, account } = useActiveWeb3React()
const address = (NETWORKS_INFO[chainId] as EVMNetworkInfo).elastic?.farmV2Contract
export const useFarmV2Action = (farmAddress: string) => {
const { account } = useActiveWeb3React()
const addTransactionWithType = useTransactionAdder()
const farmContract = useContract(address, FarmV2ABI)
const farmContract = useContract(farmAddress, FarmV2ABI)
const posManager = useProAmmNFTPositionManagerContract()

const approve = useCallback(async () => {
if (!posManager) {
throw new Error(CONTRACT_NOT_FOUND_MSG)
}
const estimateGas = await posManager.estimateGas.setApprovalForAll(address, true)
const tx = await posManager.setApprovalForAll(address, true, {
const estimateGas = await posManager.estimateGas.setApprovalForAll(farmAddress, true)
const tx = await posManager.setApprovalForAll(farmAddress, true, {
gasLimit: calculateGasMargin(estimateGas),
})
addTransactionWithType({
hash: tx.hash,
type: TRANSACTION_TYPE.APPROVE,
extraInfo: {
summary: `Elastic Static Farm`,
contract: address,
contract: farmAddress,
},
})
return tx.hash
}, [posManager, address, addTransactionWithType])
}, [posManager, farmAddress, addTransactionWithType])

//Deposit
const deposit = useCallback(
Expand Down
2 changes: 2 additions & 0 deletions src/state/farms/elasticv2/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface ElasticFarmV2Range {
export interface ElasticFarmV2 {
id: string
fId: number
farmAddress: string
startTime: number
endTime: number
isSettled: boolean
Expand All @@ -33,6 +34,7 @@ export interface ElasticFarmV2 {
}

export interface UserFarmV2Info {
farmAddress: string
poolAddress: string
nftId: BigNumber
position: Position
Expand Down
Loading

0 comments on commit 94e57c7

Please sign in to comment.