Skip to content

Commit

Permalink
feat: Fetch pool's public data in global state
Browse files Browse the repository at this point in the history
  • Loading branch information
RabbitDoge committed Dec 15, 2020
1 parent 27fc4ce commit 27c9c90
Show file tree
Hide file tree
Showing 12 changed files with 148 additions and 185 deletions.
55 changes: 8 additions & 47 deletions src/hooks/useEarnings.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
import { useEffect, useState } from 'react'
import BigNumber from 'bignumber.js'
import { useWallet } from 'use-wallet'
import {
getEarned,
getSousEarned,
getSousChefContract,
getMasterChefContract,
getSousEndBlock,
getSousStartBlock,
} from '../sushi/utils'
import { getEarned, getSousEarned, getSousChefContract, getMasterChefContract } from 'sushi/utils'
import { usePoolFromPid } from 'state/hooks'
import useSushi from './useSushi'
import useBlock from './useBlock'

Expand Down Expand Up @@ -40,45 +34,12 @@ export const useSousEarnings = (sousId) => {
}

export const useSousLeftBlocks = (sousId) => {
const [state, setState] = useState({
text: '', // TODO: deprecate this in favor of lettings consumer format the message
farmStart: 0,
blocksRemaining: 0,
isFinished: false,
})
const { account }: { account: string } = useWallet()
const sushi = useSushi()
const sousChefContract = getSousChefContract(sushi, sousId)
const { startBlock, endBlock, isFinished } = usePoolFromPid(sousId)
const block = useBlock()

useEffect(() => {
const fetchBalance = async () => {
const start = await getSousStartBlock(sousChefContract)
const end = await getSousEndBlock(sousChefContract)
const blocksRemaining = end - block

let buttonText = ''
if (!block) {
buttonText = '-'
} else if (block < start) {
buttonText = `Farming starts in ${(start - block).toLocaleString()} Blocks`
} else if (block > end) {
buttonText = 'finished'
} else {
buttonText = `Farming ends in ${blocksRemaining.toLocaleString()} Blocks`
}
setState({
text: buttonText,
farmStart: block < start ? start - block : 0,
blocksRemaining: blocksRemaining > 0 ? blocksRemaining : 0,
isFinished: sousId === 0 ? false : block > end,
})
}

if (account && sousChefContract && sushi) {
fetchBalance()
}
}, [account, block, sousChefContract, sousId, sushi])

return state
return {
blocksUntilStart: Math.max(startBlock - block, 0),
blocksRemaining: Math.max(endBlock - block, 0),
isFinished: sousId === 0 ? false : isFinished || block > endBlock,
}
}
34 changes: 3 additions & 31 deletions src/hooks/useStakedBalance.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,11 @@
import { useCallback, useEffect, useState } from 'react'
import BigNumber from 'bignumber.js'
import { useWallet } from 'use-wallet'

import {
getStaked,
getMasterChefContract,
getSousChefContract,
getSousStaked,
getTotalStaked,
getTotalStakedBNB,
} from '../sushi/utils'
import { getStaked, getMasterChefContract, getSousChefContract, getSousStaked } from '../sushi/utils'
import useSushi from './useSushi'
import useBlock from './useBlock'

export const useSousStakedBalance = (sousId) => {
const useSousStakedBalance = (sousId) => {
const [balance, setBalance] = useState(new BigNumber(0))
const { account }: { account: string } = useWallet()
const sushi = useSushi()
Expand All @@ -40,24 +32,4 @@ export const useSousStakedBalance = (sousId) => {
return balance
}

export const useSousTotalStaked = (sousId, isUsingBnb = false) => {
const [balance, setBalance] = useState(new BigNumber(0))
const sushi = useSushi()
const sousChefContract = getSousChefContract(sushi, sousId)
const block = useBlock()

useEffect(() => {
const fetchBalance = async () => {
const res = isUsingBnb
? await getTotalStakedBNB(sushi, sousChefContract)
: await getTotalStaked(sushi, sousChefContract)
setBalance(new BigNumber(res))
}

if (sushi) {
fetchBalance()
}
}, [isUsingBnb, sousChefContract, sushi, block])

return balance
}
export default useSousStakedBalance
1 change: 1 addition & 0 deletions src/state/actions.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { fetchFarmsPublicDataAsync, fetchFarmUserDataAsync } from './farms'
export { fetchPoolsPublicDataAsync } from './pools'
12 changes: 9 additions & 3 deletions src/state/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import BigNumber from 'bignumber.js'
import { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { fetchFarmsPublicDataAsync, fetchFarmUserDataAsync } from './actions'
import { State, Farm } from './types'
import { fetchFarmsPublicDataAsync, fetchFarmUserDataAsync, fetchPoolsPublicDataAsync } from './actions'
import { State, Farm, Pool } from './types'

const ZERO = new BigNumber(0)

const useStateInit = () => {
const dispatch = useDispatch()
useEffect(() => {
dispatch(fetchFarmsPublicDataAsync())
dispatch(fetchPoolsPublicDataAsync())
}, [dispatch])
}

Expand Down Expand Up @@ -51,11 +52,16 @@ export const useFarmUser = (pid, account) => {

// Pools

export const usePools = () => {
export const usePools = (): Pool[] => {
const pools = useSelector((state: State) => state.pools.data)
return pools
}

export const usePoolFromPid = (sousId): Pool => {
const pool = useSelector((state: State) => state.pools.data.find((p) => p.sousId === sousId))
return pool
}

// Prices

export const usePriceBnbBusd = (): BigNumber => {
Expand Down
15 changes: 0 additions & 15 deletions src/state/pools/fetch.ts

This file was deleted.

74 changes: 74 additions & 0 deletions src/state/pools/fetchPools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import poolsConfig from 'sushi/lib/constants/pools'
import sousChefABI from 'sushi/lib/abi/sousChef.json'
import cakeABI from 'sushi/lib/abi/sushi.json'
import wbnbABI from 'sushi/lib/abi/weth.json'
import addresses from 'sushi/lib/constants/contracts'
import { QuoteToken } from 'sushi/lib/constants/types'
import multicall from 'utils/multicall'
import BigNumber from 'bignumber.js'

const CHAIN_ID = process.env.REACT_APP_CHAIN_ID

export const fetchPoolsBlockLimits = async () => {
const poolsWithEnd = poolsConfig.filter((p) => p.sousId !== 0)
const callsStartBlock = poolsWithEnd.map((poolConfig) => {
return {
address: poolConfig.contractAddress[CHAIN_ID],
name: 'startBlock',
}
})
const callsEndBlock = poolsWithEnd.map((poolConfig) => {
return {
address: poolConfig.contractAddress[CHAIN_ID],
name: 'bonusEndBlock',
}
})

const starts = await multicall(sousChefABI, callsStartBlock)
const ends = await multicall(sousChefABI, callsEndBlock)

return poolsWithEnd.map((cakePoolConfig, index) => {
const startBlock = starts[index]
const endBlock = ends[index]
return {
sousId: cakePoolConfig.sousId,
startBlock: new BigNumber(startBlock).toNumber(),
endBlock: new BigNumber(endBlock).toNumber(),
}
})
}

export const fetchPoolsTotalStatking = async () => {
const cakePools = poolsConfig.filter((p) => p.stakingTokenName !== QuoteToken.BNB)
const bnbPool = poolsConfig.filter((p) => p.stakingTokenName === QuoteToken.BNB)

const callsCakePools = cakePools.map((poolConfig) => {
return {
address: addresses.sushi[CHAIN_ID],
name: 'balanceOf',
params: [poolConfig.contractAddress[CHAIN_ID]],
}
})

const callsBnbPools = bnbPool.map((poolConfig) => {
return {
address: addresses.wbnb[CHAIN_ID],
name: 'balanceOf',
params: [poolConfig.contractAddress[CHAIN_ID]],
}
})

const cakePoolsTotalStaked = await multicall(cakeABI, callsCakePools)
const bnbPoolsTotalStaked = await multicall(wbnbABI, callsBnbPools)

return [
...cakePools.map((p, index) => ({
sousId: p.sousId,
totalStaked: new BigNumber(cakePoolsTotalStaked[index]).toNumber(),
})),
...bnbPool.map((p, index) => ({
sousId: p.sousId,
totalStaked: new BigNumber(bnbPoolsTotalStaked[index]).toNumber(),
})),
]
}
29 changes: 20 additions & 9 deletions src/state/pools/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable no-param-reassign */
import { createSlice } from '@reduxjs/toolkit'
import poolsConfig from 'sushi/lib/constants/pools'
import fetchPools from './fetch'
import { fetchPoolsBlockLimits, fetchPoolsTotalStatking } from './fetchPools'
import { PoolsState, Pool } from '../types'

const initialState: PoolsState = { data: [...poolsConfig] }
Expand All @@ -10,23 +10,34 @@ export const PoolsSlice = createSlice({
name: 'Pools',
initialState,
reducers: {
updatePoolPublicData: (state, action) => {
setPoolsPublicData: (state, action) => {
const livePoolsData: Pool[] = action.payload
state.data = state.data.map((pool) => {
const livePoolData = livePoolsData.find((p) => p.sousId === pool.sousId)
return { ...pool, ...livePoolData }
state.data = state.data.map((farm) => {
const livePoolData = livePoolsData.find((f) => f.sousId === farm.sousId)
return { ...farm, ...livePoolData }
})
},
},
})

// Actions
export const { updatePoolPublicData } = PoolsSlice.actions
export const { setPoolsPublicData } = PoolsSlice.actions

// Thunks
export const updatePoolPublicDataAsync = () => async (dispatch) => {
const pools = await fetchPools()
dispatch(updatePoolPublicData(pools))
export const fetchPoolsPublicDataAsync = () => async (dispatch) => {
const blockLimits = await fetchPoolsBlockLimits()
const totalStakings = await fetchPoolsTotalStatking()

const liveData = poolsConfig.map((pool) => {
const blockLimit = blockLimits.find((entry) => entry.sousId === pool.sousId)
const totalStaking = totalStakings.find((entry) => entry.sousId === pool.sousId)
return {
...blockLimit,
...totalStaking,
}
})

dispatch(setPoolsPublicData(liveData))
}

export default PoolsSlice.reducer
38 changes: 0 additions & 38 deletions src/sushi/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,6 @@ export const getSyrupAddress = (sushi) => {
export const getSyrupContract = (sushi) => {
return sushi && sushi.contracts && sushi.contracts.syrup
}
export const getWbnbContract = (sushi) => {
return sushi && sushi.contracts && sushi.contracts.wbnb
}
export const getBusdContract = (sushi) => {
return sushi && sushi.contracts && sushi.contracts.busd
}

export const getMasterChefContract = (sushi) => {
return sushi && sushi.contracts && sushi.contracts.masterChef
}
Expand All @@ -47,20 +40,6 @@ export const getSousEarned = async (sousChefContract, account) => {
return sousChefContract.methods.pendingReward(account).call()
}

export const getTotalStaked = async (sushi, sousChefContract) => {
const syrup = await getSyrupContract(sushi)
const sushi2 = await getSushiContract(sushi)
const syrupBalance = await syrup.methods.balanceOf(sousChefContract.options.address).call()
const sushiBalance = await sushi2.methods.balanceOf(sousChefContract.options.address).call()
return syrupBalance > sushiBalance ? syrupBalance : sushiBalance
}

export const getTotalStakedBNB = async (sushi, sousChefContract) => {
const wbnb = await getWbnbContract(sushi)
const wbnbBalance = await wbnb.methods.balanceOf(sousChefContract.options.address).call()
return wbnbBalance
}

export const approve = async (lpContract, masterChefContract, account) => {
return lpContract.methods
.approve(masterChefContract.options.address, ethers.constants.MaxUint256)
Expand Down Expand Up @@ -212,20 +191,3 @@ export const getSousStaked = async (sousChefContract, account) => {
return new BigNumber(0)
}
}

export const getSousStartBlock = async (sousChefContract) => {
try {
const startBlock = await sousChefContract.methods.startBlock().call()
return startBlock
} catch {
return 0
}
}
export const getSousEndBlock = async (sousChefContract) => {
try {
const endBlcok = await sousChefContract.methods.bonusEndBlock().call()
return endBlcok
} catch {
return 0
}
}
2 changes: 1 addition & 1 deletion src/utils/formatBalance.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import BigNumber from 'bignumber.js'

export const getBalanceNumber = (balance: BigNumber, decimals = 18) => {
const displayBalance = balance.dividedBy(new BigNumber(10).pow(decimals))
const displayBalance = new BigNumber(balance).dividedBy(new BigNumber(10).pow(decimals))
return displayBalance.toNumber()
}

Expand Down
4 changes: 2 additions & 2 deletions src/views/Pools/Syrup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,11 @@ const Farm: React.FC = () => {
</Hero>
<Pools>
{orderBy(openPools, ['sortOrder']).map((pool) => (
<PoolCard key={pool.sousId} cakePriceVsBNB={cakePriceVsBNB} userBnbBalance={userBnbBalance} {...pool} />
<PoolCard key={pool.sousId} cakePriceVsBNB={cakePriceVsBNB} userBnbBalance={userBnbBalance} pool={pool} />
))}
<Coming />
{orderBy(finishedPools, ['sortOrder']).map((pool) => (
<PoolCard key={pool.sousId} cakePriceVsBNB={cakePriceVsBNB} userBnbBalance={userBnbBalance} {...pool} />
<PoolCard key={pool.sousId} cakePriceVsBNB={cakePriceVsBNB} userBnbBalance={userBnbBalance} pool={pool} />
))}
</Pools>
</Page>
Expand Down
Loading

0 comments on commit 27c9c90

Please sign in to comment.