types#SyrupInfo TypeScript Examples
The following examples show how to use
types#SyrupInfo.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SyrupAPR.tsx From interface-v2 with GNU General Public License v3.0 | 6 votes |
SyrupAPR: React.FC<{ syrup: SyrupInfo; dQUICKAPY: string }> = ({
syrup,
dQUICKAPY,
}) => {
const { palette } = useTheme();
const isDQUICKStakingToken = syrup.stakingToken.equals(
returnTokenFromKey('DQUICK'),
);
return (
<>
<Typography variant='body2' style={{ color: palette.success.main }}>
{getTokenAPRSyrup(syrup).toLocaleString()}%
</Typography>
{isDQUICKStakingToken && (
<Box display='flex'>
<Box
borderRadius='4px'
border={`1px solid ${palette.grey.A400}`}
padding='4px'
marginTop='4px'
display='flex'
alignItems='center'
>
<CurrencyLogo currency={returnTokenFromKey('QUICK')} size='12px' />
<Typography variant='caption' style={{ marginLeft: 4 }}>
{dQUICKAPY}% <span style={{ color: palette.text.hint }}>APY</span>
</Typography>
</Box>
</Box>
)}
</>
);
}
Example #2
Source File: index.ts From interface-v2 with GNU General Public License v3.0 | 5 votes |
export function getTokenAPRSyrup(syrup: SyrupInfo) {
return syrup.valueOfTotalStakedAmountInUSDC &&
syrup.valueOfTotalStakedAmountInUSDC > 0
? ((syrup.rewards ?? 0) / syrup.valueOfTotalStakedAmountInUSDC) *
getDaysCurrentYear() *
100
: 0;
}
Example #3
Source File: index.ts From interface-v2 with GNU General Public License v3.0 | 5 votes |
export function getEarnedUSDSyrup(syrup?: SyrupInfo) {
if (!syrup || !syrup.earnedAmount || !syrup.rewardTokenPriceinUSD) return '-';
const earnedUSD =
Number(syrup.earnedAmount.toExact()) * Number(syrup.rewardTokenPriceinUSD);
if (earnedUSD > 0 && earnedUSD < 0.001) return '< $0.001';
return `$${earnedUSD.toLocaleString()}`;
}
Example #4
Source File: index.ts From interface-v2 with GNU General Public License v3.0 | 5 votes |
export function getSyrupLPToken(info: SyrupBasic | SyrupInfo) {
const lp = info.lp;
if (lp && lp !== '') return new Token(137, lp, 18, 'SLP', 'Staked LP');
return info.stakingToken;
}
Example #5
Source File: SyrupCard.tsx From interface-v2 with GNU General Public License v3.0 | 4 votes |
SyrupCard: React.FC<{ syrup: SyrupInfo; dQUICKAPY: string }> = ({
syrup,
dQUICKAPY,
}) => {
const { palette, breakpoints } = useTheme();
const isMobile = useMediaQuery(breakpoints.down('xs'));
const [expanded, setExpanded] = useState(false);
const classes = useStyles();
const currency = unwrappedToken(syrup.token);
const depositAmount = syrup.valueOfTotalStakedAmountInUSDC
? `$${syrup.valueOfTotalStakedAmountInUSDC.toLocaleString()}`
: `${formatTokenAmount(syrup.totalStakedAmount)} ${
syrup.stakingToken.symbol
}`;
return (
<Box className={classes.syrupCard}>
<Box
display='flex'
flexWrap='wrap'
alignItems='center'
width={1}
padding={2}
style={{ cursor: 'pointer' }}
onClick={() => setExpanded(!expanded)}
>
{isMobile ? (
<>
<Box
display='flex'
alignItems='center'
width={expanded ? 0.95 : 0.5}
>
<CurrencyLogo currency={currency} size='32px' />
<Box ml={1.5}>
<Typography variant='body2'>{currency.symbol}</Typography>
</Box>
</Box>
{!expanded && (
<Box width={0.45}>
<SyrupAPR syrup={syrup} dQUICKAPY={dQUICKAPY} />
</Box>
)}
<Box
width={0.05}
display='flex'
justifyContent='flex-end'
color={palette.primary.main}
>
{expanded ? <KeyboardArrowUp /> : <KeyboardArrowDown />}
</Box>
</>
) : (
<>
<Box width={0.3} display='flex' alignItems='center'>
<CurrencyLogo currency={currency} size='32px' />
<Box ml={1.5}>
<Typography variant='body2'>{currency.symbol}</Typography>
<Box display='flex' mt={0.25}>
<Typography variant='caption'>
{syrup.rate >= 1000000
? formatCompact(syrup.rate)
: syrup.rate.toLocaleString()}
<span style={{ color: palette.text.secondary }}>
{' '}
/ day
</span>
</Typography>
</Box>
<Box display='flex' mt={0.25}>
<Typography variant='caption'>
$
{syrup.rewardTokenPriceinUSD
? (
syrup.rate * syrup.rewardTokenPriceinUSD
).toLocaleString()
: '-'}{' '}
<span style={{ color: palette.text.secondary }}>/ day</span>
</Typography>
</Box>
</Box>
</Box>
<Box width={0.3}>
<Typography variant='body2'>{depositAmount}</Typography>
</Box>
<Box width={0.2} textAlign='left'>
<SyrupAPR syrup={syrup} dQUICKAPY={dQUICKAPY} />
</Box>
<Box width={0.2} textAlign='right'>
<Box
display='flex'
alignItems='center'
justifyContent='flex-end'
mb={0.25}
>
<CurrencyLogo currency={currency} size='16px' />
<Typography variant='body2' style={{ marginLeft: 5 }}>
{formatTokenAmount(syrup.earnedAmount)}
</Typography>
</Box>
<Typography
variant='body2'
style={{ color: palette.text.secondary }}
>
{getEarnedUSDSyrup(syrup)}
</Typography>
</Box>
</>
)}
</Box>
{expanded && syrup && (
<SyrupCardDetails syrup={syrup} dQUICKAPY={dQUICKAPY} />
)}
</Box>
);
}
Example #6
Source File: SyrupCardDetails.tsx From interface-v2 with GNU General Public License v3.0 | 4 votes |
SyrupCardDetails: React.FC<{ syrup: SyrupInfo; dQUICKAPY: string }> = ({
syrup,
dQUICKAPY,
}) => {
const syrupCurrency = unwrappedToken(syrup.token);
const { palette, breakpoints } = useTheme();
const { t } = useTranslation();
const isMobile = useMediaQuery(breakpoints.down('xs'));
const [attemptingClaim, setAttemptingClaim] = useState(false);
const [attemptingUnstake, setAttemptingUnstake] = useState(false);
const [openStakeModal, setOpenStakeModal] = useState(false);
const classes = useStyles();
const stakingTokenPrice = useUSDCPriceToken(syrup.stakingToken);
const stakingContract = useStakingContract(syrup?.stakingRewardAddress);
const addTransaction = useTransactionAdder();
const finalizedTransaction = useTransactionFinalizer();
const { account } = useActiveWeb3React();
const currency = syrup ? unwrappedToken(syrup.token) : undefined;
const userLiquidityUnstaked = useTokenBalance(
account ?? undefined,
syrup.stakedAmount?.token,
);
const exactEnd = syrup ? syrup.periodFinish : 0;
const depositAmount =
syrup && syrup.valueOfTotalStakedAmountInUSDC
? `$${Number(syrup.valueOfTotalStakedAmountInUSDC).toLocaleString()}`
: `${formatTokenAmount(syrup?.totalStakedAmount)} ${
syrup?.stakingToken.symbol
}`;
const onClaimReward = async () => {
if (syrup && stakingContract && syrup.stakedAmount) {
setAttemptingClaim(true);
await stakingContract
.getReward({ gasLimit: 350000 })
.then(async (response: TransactionResponse) => {
addTransaction(response, {
summary: `Claim accumulated` + syrup.token.symbol + `rewards`,
});
try {
const receipt = await response.wait();
finalizedTransaction(receipt, {
summary: `Claim accumulated` + syrup.token.symbol + `rewards`,
});
setAttemptingClaim(false);
} catch (e) {
setAttemptingClaim(false);
}
})
.catch((error: any) => {
setAttemptingClaim(false);
console.log(error);
});
}
};
const onWithdraw = async () => {
if (syrup && stakingContract && syrup.stakedAmount) {
setAttemptingUnstake(true);
await stakingContract
.exit({ gasLimit: 300000 })
.then(async (response: TransactionResponse) => {
addTransaction(response, {
summary: `Withdraw deposited liquidity`,
});
try {
const receipt = await response.wait();
finalizedTransaction(receipt, {
summary: `Withdraw deposited dQUICK`,
});
setAttemptingUnstake(false);
} catch (e) {
setAttemptingUnstake(false);
}
})
.catch((error: any) => {
setAttemptingUnstake(false);
console.log(error);
});
}
};
const StakeButton = () => (
<Box
className={classes.syrupButton}
onClick={() => setOpenStakeModal(true)}
>
<Typography variant='body2'>Stake</Typography>
</Box>
);
const UnstakeButton = () => (
<Box
className={classes.syrupButton}
style={{ opacity: attemptingUnstake ? 0.6 : 1 }}
onClick={() => {
if (!attemptingUnstake) {
onWithdraw();
}
}}
>
<Typography variant='body2'>
{attemptingUnstake ? 'Unstaking...' : 'Unstake'}
</Typography>
</Box>
);
const ClaimButton = () => (
<Box
className={classes.syrupButton}
style={{ opacity: attemptingClaim ? 0.6 : 1 }}
onClick={() => {
if (!attemptingClaim) {
onClaimReward();
}
}}
>
<Typography variant='body2'>
{attemptingClaim ? 'Claiming...' : 'Claim'}
</Typography>
</Box>
);
return (
<>
{openStakeModal && syrup && (
<StakeSyrupModal
open={openStakeModal}
onClose={() => setOpenStakeModal(false)}
syrup={syrup}
/>
)}
{syrup && (
<>
<Divider />
<Box padding={3}>
{isMobile && (
<Box mb={3}>
<Box display='flex' justifyContent='space-between' mb={2}>
<Typography
variant='body2'
style={{ color: palette.text.secondary }}
>
{syrup.stakingToken.symbol} {t('deposits')}:
</Typography>
<Typography variant='body2'>{depositAmount}</Typography>
</Box>
<Box display='flex' justifyContent='space-between' mb={2}>
<Typography
variant='body2'
style={{ color: palette.text.secondary }}
>
{t('dailyRewards')}:
</Typography>
<Typography variant='body2'>
{syrup.rate >= 1000000
? formatCompact(syrup.rate)
: syrup.rate.toLocaleString()}{' '}
{syrup.token.symbol}
<span style={{ color: palette.text.secondary }}>
{' '}
/ {t('day')}
</span>
</Typography>
</Box>
<Box mb={2}>
<SyrupTimerLabel exactEnd={exactEnd} isEnded={syrup?.ended} />
</Box>
<Box display='flex' justifyContent='space-between' mb={3}>
<Box display='flex' alignItems='center'>
<Typography
variant='body2'
style={{ color: palette.text.secondary }}
>
APR:
</Typography>
<Box ml={0.5} height={16}>
<img src={CircleInfoIcon} alt={'arrow up'} />
</Box>
</Box>
<Box textAlign='right'>
<SyrupAPR syrup={syrup} dQUICKAPY={dQUICKAPY} />
</Box>
</Box>
<Divider />
</Box>
)}
<Box
display='flex'
alignItems='center'
justifyContent='space-between'
mb={1}
>
<Typography
variant='body2'
style={{ color: palette.text.secondary }}
>
{t('inwallet')}
</Typography>
<Typography variant='body2'>
<span style={{ color: palette.text.primary }}>
{userLiquidityUnstaked
? formatTokenAmount(userLiquidityUnstaked)
: 0}{' '}
{syrup.stakingToken.symbol}
</span>
<span style={{ color: palette.text.secondary, marginLeft: 4 }}>
$
{userLiquidityUnstaked
? (
stakingTokenPrice *
Number(userLiquidityUnstaked.toExact())
).toLocaleString()
: 0}
</span>
</Typography>
</Box>
<Box
display='flex'
alignItems='center'
justifyContent='space-between'
mb={1}
>
<Typography
variant='body2'
style={{ color: palette.text.secondary }}
>
{t('staked')}
</Typography>
<Typography variant='body2'>
<span style={{ color: palette.text.primary }}>
{formatTokenAmount(syrup.stakedAmount)}{' '}
{syrup.stakingToken.symbol}
</span>
<span style={{ color: palette.text.secondary, marginLeft: 4 }}>
{syrup.stakedAmount
? `$${(
stakingTokenPrice * Number(syrup.stakedAmount.toExact())
).toLocaleString()}`
: '-'}
</span>
</Typography>
</Box>
<Box
display='flex'
alignItems='center'
justifyContent='space-between'
mb={2}
>
<Typography
variant='body2'
style={{ color: palette.text.secondary }}
>
{t('earned')} {currency?.symbol}
</Typography>
<Box display='flex' alignItems='center'>
<CurrencyLogo currency={currency} size='16px' />
<Typography variant='body2' style={{ marginLeft: 4 }}>
<span style={{ color: palette.text.primary }}>
{formatTokenAmount(syrup.earnedAmount)}
</span>
<span
style={{ color: palette.text.secondary, marginLeft: 4 }}
>
{getEarnedUSDSyrup(syrup)}
</span>
</Typography>
</Box>
</Box>
<Box
display='flex'
flexWrap='wrap'
alignItems='center'
justifyContent='space-between'
>
{!isMobile && (
<SyrupTimerLabel exactEnd={exactEnd} isEnded={syrup?.ended} />
)}
{isMobile ? (
<>
{syrup.earnedAmount && syrup.earnedAmount.greaterThan('0') && (
<Box
width={1}
mb={1.5}
display='flex'
justifyContent='flex-end'
>
<ClaimButton />
</Box>
)}
<Box
width={1}
mb={1.5}
display='flex'
justifyContent={
syrup.stakedAmount && syrup.stakedAmount.greaterThan('0')
? 'space-between'
: 'flex-end'
}
>
{!syrup.ended && <StakeButton />}
{syrup.stakedAmount &&
syrup.stakedAmount.greaterThan('0') && <UnstakeButton />}
</Box>
</>
) : (
<Box display='flex' flexWrap='wrap' my={1}>
{!syrup.ended && <StakeButton />}
{syrup.stakedAmount && syrup.stakedAmount.greaterThan('0') && (
<Box ml={1}>
<UnstakeButton />
</Box>
)}
{syrup.earnedAmount && syrup.earnedAmount.greaterThan('0') && (
<Box ml={1}>
<ClaimButton />
</Box>
)}
</Box>
)}
</Box>
{syrup.rewardRate?.greaterThan('0') && (
<Box className={classes.dailyRateWrapper}>
<Box
display='flex'
alignItems='center'
justifyContent={isMobile ? 'space-between' : 'flex-start'}
width={isMobile ? 1 : 'auto'}
flexWrap='wrap'
>
<Box display='flex' mr={1}>
<Typography variant='body2' color='textSecondary'>
{t('yourRate')}:
</Typography>
</Box>
<Typography variant='body2' color='textPrimary'>
{formatMulDivTokenAmount(
syrup.rewardRate,
GlobalConst.utils.ONEDAYSECONDS,
)}{' '}
{syrupCurrency.symbol} / {t('day')}
</Typography>
</Box>
</Box>
)}
</Box>
</>
)}
</>
);
}
Example #7
Source File: DragonsSyrup.tsx From interface-v2 with GNU General Public License v3.0 | 4 votes |
DragonsSyrup: React.FC = () => {
const { palette, breakpoints } = useTheme();
const isMobile = useMediaQuery(breakpoints.down('xs'));
const [isEndedSyrup, setIsEndedSyrup] = useState(false);
const [pageIndex, setPageIndex] = useState(0);
const [sortBy, setSortBy] = useState(0);
const [sortDesc, setSortDesc] = useState(false);
const [stakedOnly, setStakeOnly] = useState(false);
const [syrupSearch, setSyrupSearch] = useState('');
const [syrupSearchInput, setSyrupSearchInput] = useDebouncedChangeHandler(
syrupSearch,
setSyrupSearch,
);
const lairInfo = useLairInfo();
const dQUICKAPY = useLairDQUICKAPY(lairInfo);
const addedStakingSyrupInfos = useSyrupInfo(
null,
isEndedSyrup ? 0 : undefined,
isEndedSyrup ? 0 : undefined,
{ search: syrupSearch, isStaked: stakedOnly },
);
const addedOldSyrupInfos = useOldSyrupInfo(
null,
isEndedSyrup ? undefined : 0,
isEndedSyrup ? undefined : 0,
{ search: syrupSearch, isStaked: stakedOnly },
);
const addedSyrupInfos = isEndedSyrup
? addedOldSyrupInfos
: addedStakingSyrupInfos;
const sortIndex = sortDesc ? 1 : -1;
const sortByToken = useCallback(
(a: SyrupInfo, b: SyrupInfo) => {
const syrupStrA = a.token.symbol ?? '';
const syrupStrB = b.token.symbol ?? '';
return (syrupStrA > syrupStrB ? -1 : 1) * sortIndex;
},
[sortIndex],
);
const sortByDeposit = useCallback(
(a: SyrupInfo, b: SyrupInfo) => {
const depositA =
a.valueOfTotalStakedAmountInUSDC ??
getExactTokenAmount(a.totalStakedAmount);
const depositB =
b.valueOfTotalStakedAmountInUSDC ??
getExactTokenAmount(b.totalStakedAmount);
return (depositA > depositB ? -1 : 1) * sortIndex;
},
[sortIndex],
);
const sortByAPR = useCallback(
(a: SyrupInfo, b: SyrupInfo) => {
return (getTokenAPRSyrup(a) > getTokenAPRSyrup(b) ? -1 : 1) * sortIndex;
},
[sortIndex],
);
const sortByEarned = useCallback(
(a: SyrupInfo, b: SyrupInfo) => {
const earnedUSDA =
getExactTokenAmount(a.earnedAmount) * (a.rewardTokenPriceinUSD ?? 0);
const earnedUSDB =
getExactTokenAmount(b.earnedAmount) * (b.rewardTokenPriceinUSD ?? 0);
return (earnedUSDA > earnedUSDB ? -1 : 1) * sortIndex;
},
[sortIndex],
);
const sortedSyrupInfos = useMemo(() => {
return addedSyrupInfos.sort((a, b) => {
if (sortBy === TOKEN_COLUMN) {
return sortByToken(a, b);
} else if (sortBy === DEPOSIT_COLUMN) {
return sortByDeposit(a, b);
} else if (sortBy === APR_COLUMN) {
return sortByAPR(a, b);
} else if (sortBy === EARNED_COLUMN) {
return sortByEarned(a, b);
}
return 1;
});
}, [
addedSyrupInfos,
sortBy,
sortByToken,
sortByDeposit,
sortByAPR,
sortByEarned,
]);
const syrupRewardAddress = useMemo(
() =>
sortedSyrupInfos
.map((syrupInfo) => syrupInfo.stakingRewardAddress.toLowerCase())
.reduce((totStr, str) => totStr + str, ''),
[sortedSyrupInfos],
);
useEffect(() => {
setPageIndex(0);
}, [syrupRewardAddress]);
const syrupInfos = useMemo(() => {
return sortedSyrupInfos
? sortedSyrupInfos.slice(
0,
getPageItemsToLoad(pageIndex, LOADSYRUP_COUNT),
)
: null;
}, [sortedSyrupInfos, pageIndex]);
const loadNext = () => {
setPageIndex(pageIndex + 1);
};
const { loadMoreRef } = useInfiniteLoading(loadNext);
const renderStakedOnly = () => (
<Box display='flex' alignItems='center'>
<Typography
variant='body2'
style={{ color: palette.text.disabled, marginRight: 8 }}
>
Staked Only
</Typography>
<ToggleSwitch
toggled={stakedOnly}
onToggle={() => setStakeOnly(!stakedOnly)}
/>
</Box>
);
const syrupStatusItems = [
{
text: 'Active',
onClick: () => setIsEndedSyrup(false),
condition: !isEndedSyrup,
},
{
text: 'Ended',
onClick: () => setIsEndedSyrup(true),
condition: isEndedSyrup,
},
];
const sortColumns = [
{
text: 'Earn',
index: TOKEN_COLUMN,
width: 0.3,
},
{
text: 'Deposits',
index: DEPOSIT_COLUMN,
width: 0.3,
},
{
text: 'APR',
index: APR_COLUMN,
width: 0.2,
},
{
text: 'Earned',
index: EARNED_COLUMN,
width: 0.2,
justify: 'flex-end',
},
];
const sortByDesktopItems = sortColumns.map((item) => {
return {
...item,
onClick: () => {
if (sortBy === item.index) {
setSortDesc(!sortDesc);
} else {
setSortBy(item.index);
setSortDesc(false);
}
},
};
});
const sortByMobileItems = sortColumns.map((item) => {
return { text: item.text, onClick: () => setSortBy(item.index) };
});
return (
<>
<Box display='flex' flexWrap='wrap' alignItems='center' mb={3.5}>
<Box
display='flex'
justifyContent='space-between'
width={returnFullWidthMobile(isMobile)}
flex={isMobile ? 'unset' : 1}
>
<Box width={isMobile ? 'calc(100% - 150px)' : 1} mr={2} my={2}>
<SearchInput
placeholder={
isMobile ? 'Search' : 'Search name, symbol or paste address'
}
value={syrupSearchInput}
setValue={setSyrupSearchInput}
/>
</Box>
{isMobile && renderStakedOnly()}
</Box>
<Box
width={returnFullWidthMobile(isMobile)}
display='flex'
flexWrap='wrap'
alignItems='center'
>
<Box mr={2}>
<CustomSwitch width={160} height={40} items={syrupStatusItems} />
</Box>
{isMobile ? (
<>
<Box height={40} flex={1}>
<CustomMenu title='Sort By' menuItems={sortByMobileItems} />
</Box>
<Box mt={2} width={1} display='flex' alignItems='center'>
<Typography
variant='body2'
style={{ color: palette.text.disabled, marginRight: 8 }}
>
Sort {sortDesc ? 'Desc' : 'Asc'}
</Typography>
<ToggleSwitch
toggled={sortDesc}
onToggle={() => setSortDesc(!sortDesc)}
/>
</Box>
</>
) : (
renderStakedOnly()
)}
</Box>
</Box>
<Divider />
{!isMobile && (
<Box mt={2.5} display='flex' paddingX={2}>
{sortByDesktopItems.map((item) => (
<Box
key={item.index}
display='flex'
alignItems='center'
width={item.width}
style={{ cursor: 'pointer' }}
justifyContent={item.justify}
onClick={item.onClick}
color={
sortBy === item.index
? palette.text.primary
: palette.text.secondary
}
>
<Typography variant='body2'>{item.text}</Typography>
<Box display='flex' ml={0.5}>
{sortBy === item.index && sortDesc ? (
<ArrowDown size={20} />
) : (
<ArrowUp size={20} />
)}
</Box>
</Box>
))}
</Box>
)}
{syrupInfos ? (
syrupInfos.map((syrup, ind) => (
<SyrupCard key={ind} syrup={syrup} dQUICKAPY={dQUICKAPY} />
))
) : (
<>
<Skeleton width='100%' height={120} />
<Skeleton width='100%' height={120} />
<Skeleton width='100%' height={120} />
<Skeleton width='100%' height={120} />
<Skeleton width='100%' height={120} />
</>
)}
<div ref={loadMoreRef} />
</>
);
}
Example #8
Source File: hooks.ts From interface-v2 with GNU General Public License v3.0 | 4 votes |
export function useSyrupInfo(
tokenToFilterBy?: Token | null,
startIndex?: number,
endIndex?: number,
filter?: { search: string; isStaked: boolean },
): SyrupInfo[] {
const { chainId, account } = useActiveWeb3React();
const currentTimestamp = dayjs().unix();
const info = useMemo(
() =>
chainId
? returnSyrupInfo()
[chainId]?.slice(startIndex, endIndex)
.filter(
(syrupInfo) =>
syrupInfo.ending > currentTimestamp &&
(tokenToFilterBy === undefined || tokenToFilterBy === null
? getSearchFiltered(syrupInfo, filter ? filter.search : '')
: tokenToFilterBy.equals(syrupInfo.token)),
) ?? []
: [],
[chainId, tokenToFilterBy, startIndex, endIndex, filter, currentTimestamp],
);
const uni = chainId ? GlobalValue.tokens.UNI[chainId] : undefined;
const rewardsAddresses = useMemo(
() => info.map(({ stakingRewardAddress }) => stakingRewardAddress),
[info],
);
const accountArg = useMemo(() => [account ?? undefined], [account]);
// get all the info from the staking rewards contracts
const balances = useMultipleContractSingleData(
rewardsAddresses,
STAKING_REWARDS_INTERFACE,
'balanceOf',
accountArg,
);
const earnedAmounts = useMultipleContractSingleData(
rewardsAddresses,
STAKING_REWARDS_INTERFACE,
'earned',
accountArg,
);
const totalSupplies = useMultipleContractSingleData(
rewardsAddresses,
STAKING_REWARDS_INTERFACE,
'totalSupply',
);
const rewardRates = useMultipleContractSingleData(
rewardsAddresses,
STAKING_REWARDS_INTERFACE,
'rewardRate',
undefined,
NEVER_RELOAD,
);
const stakingTokenPairs = usePairs(
info.map((item) => [
unwrappedToken(item.token),
unwrappedToken(item.baseToken),
]),
);
const usdBaseTokenPrices = useUSDCPrices(
info.map((item) => unwrappedToken(item.baseToken)),
);
const stakingTokenPrices = useUSDCPricesToken(
info.map((item) => item.stakingToken),
);
return useMemo(() => {
if (!chainId || !uni) return [];
return rewardsAddresses.reduce<SyrupInfo[]>(
(memo, rewardsAddress, index) => {
// these two are dependent on account
const balanceState = balances[index];
const earnedAmountState = earnedAmounts[index];
const stakingTokenPrice = stakingTokenPrices[index];
// these get fetched regardless of account
const totalSupplyState = totalSupplies[index];
const rewardRateState = rewardRates[index];
const syrupInfo = info[index];
if (
// these may be undefined if not logged in
!balanceState?.loading &&
!earnedAmountState?.loading &&
// always need these
totalSupplyState &&
!totalSupplyState.loading &&
rewardRateState &&
!rewardRateState.loading
) {
// get the LP token
const token = syrupInfo.token;
const [, stakingTokenPair] = stakingTokenPairs[index];
const tokenPairPrice = stakingTokenPair?.priceOf(token);
const usdPriceBaseToken = usdBaseTokenPrices[index];
const priceOfRewardTokenInUSD =
tokenPairPrice && usdPriceBaseToken
? Number(tokenPairPrice.toSignificant()) *
Number(usdPriceBaseToken.toSignificant())
: undefined;
const rewards = syrupInfo.rate * (priceOfRewardTokenInUSD ?? 0);
// check for account, if no account set to 0
const rate = web3.utils.toWei(syrupInfo.rate.toString());
const syrupToken = getSyrupLPToken(syrupInfo);
const stakedAmount = initTokenAmountFromCallResult(
syrupToken,
balanceState,
);
const totalStakedAmount = initTokenAmountFromCallResult(
syrupToken,
totalSupplyState,
);
const totalRewardRate = new TokenAmount(token, JSBI.BigInt(rate));
//const pair = info[index].pair.toLowerCase();
//const fees = (pairData && pairData[pair] ? pairData[pair].oneDayVolumeUSD * 0.0025: 0);
const rewardRate = initTokenAmountFromCallResult(
token,
rewardRateState,
);
const getHypotheticalRewardRate = (
stakedAmount?: TokenAmount,
totalStakedAmount?: TokenAmount,
): TokenAmount | undefined => {
if (!stakedAmount || !totalStakedAmount || !rewardRate) return;
return new TokenAmount(
token,
JSBI.greaterThan(totalStakedAmount.raw, JSBI.BigInt(0))
? JSBI.divide(
JSBI.multiply(rewardRate.raw, stakedAmount.raw),
totalStakedAmount.raw,
)
: JSBI.BigInt(0),
);
};
const individualRewardRate = getHypotheticalRewardRate(
stakedAmount,
totalStakedAmount,
);
const periodFinishMs = syrupInfo.ending;
memo.push({
stakingRewardAddress: rewardsAddress,
token: syrupInfo.token,
ended: syrupInfo.ended,
name: syrupInfo.name,
lp: syrupInfo.lp,
periodFinish: periodFinishMs,
earnedAmount: initTokenAmountFromCallResult(
token,
earnedAmountState,
),
rewardRate: individualRewardRate,
totalRewardRate: totalRewardRate,
stakedAmount: stakedAmount,
totalStakedAmount: totalStakedAmount,
getHypotheticalRewardRate,
baseToken: syrupInfo.baseToken,
rate: syrupInfo.rate,
rewardTokenPriceinUSD: priceOfRewardTokenInUSD,
rewards,
stakingToken: syrupInfo.stakingToken,
valueOfTotalStakedAmountInUSDC: totalStakedAmount
? Number(totalStakedAmount.toExact()) * stakingTokenPrice
: undefined,
});
}
return memo;
},
[],
);
}, [
balances,
chainId,
earnedAmounts,
info,
rewardsAddresses,
totalSupplies,
uni,
rewardRates,
stakingTokenPairs,
usdBaseTokenPrices,
stakingTokenPrices,
]).filter((syrupInfo) =>
filter && filter.isStaked
? syrupInfo.stakedAmount && syrupInfo.stakedAmount.greaterThan('0')
: true,
);
}
Example #9
Source File: hooks.ts From interface-v2 with GNU General Public License v3.0 | 4 votes |
export function useOldSyrupInfo(
tokenToFilterBy?: Token | null,
startIndex?: number,
endIndex?: number,
filter?: { search: string; isStaked: boolean },
): SyrupInfo[] {
const { chainId, account } = useActiveWeb3React();
const currentTimestamp = dayjs().unix();
const info = useMemo(() => {
if (!chainId) return [];
const endedSyrupInfos =
returnSyrupInfo(false)[chainId]?.filter(
(syrupInfo) => syrupInfo.ending <= currentTimestamp,
) ?? [];
const oldSyrupInfos = returnSyrupInfo(true)[chainId] ?? [];
const allOldSyrupInfos = endedSyrupInfos.concat(oldSyrupInfos);
return allOldSyrupInfos
.slice(startIndex, endIndex)
.filter((syrupInfo) =>
tokenToFilterBy === undefined || tokenToFilterBy === null
? getSearchFiltered(syrupInfo, filter ? filter.search : '')
: tokenToFilterBy.equals(syrupInfo.token),
);
}, [
chainId,
tokenToFilterBy,
startIndex,
endIndex,
filter,
currentTimestamp,
]);
const uni = chainId ? GlobalValue.tokens.UNI[chainId] : undefined;
const rewardsAddresses = useMemo(
() => info.map(({ stakingRewardAddress }) => stakingRewardAddress),
[info],
);
const accountArg = useMemo(() => [account ?? undefined], [account]);
// get all the info from the staking rewards contracts
const balances = useMultipleContractSingleData(
rewardsAddresses,
STAKING_REWARDS_INTERFACE,
'balanceOf',
accountArg,
);
const earnedAmounts = useMultipleContractSingleData(
rewardsAddresses,
STAKING_REWARDS_INTERFACE,
'earned',
accountArg,
);
const totalSupplies = useMultipleContractSingleData(
rewardsAddresses,
STAKING_REWARDS_INTERFACE,
'totalSupply',
);
const rewardRates = useMultipleContractSingleData(
rewardsAddresses,
STAKING_REWARDS_INTERFACE,
'rewardRate',
undefined,
NEVER_RELOAD,
);
const stakingTokenPairs = usePairs(
info.map((item) => [
unwrappedToken(item.token),
unwrappedToken(item.baseToken),
]),
);
const usdBaseTokenPrices = useUSDCPrices(
info.map((item) => unwrappedToken(item.baseToken)),
);
const stakingTokenPrices = useUSDCPricesToken(
info.map((item) => item.stakingToken),
);
return useMemo(() => {
if (!chainId || !uni) return [];
return rewardsAddresses.reduce<SyrupInfo[]>(
(memo, rewardsAddress, index) => {
// these two are dependent on account
const balanceState = balances[index];
const earnedAmountState = earnedAmounts[index];
// these get fetched regardless of account
const totalSupplyState = totalSupplies[index];
const rewardRateState = rewardRates[index];
const syrupInfo = info[index];
const stakingTokenPrice = stakingTokenPrices[index];
if (
// these may be undefined if not logged in
!balanceState?.loading &&
!earnedAmountState?.loading &&
// always need these
totalSupplyState &&
!totalSupplyState.loading &&
rewardRateState &&
!rewardRateState.loading
) {
// get the LP token
const token = syrupInfo.token;
// check for account, if no account set to 0
const rate = web3.utils.toWei(syrupInfo.rate.toString());
const stakedAmount = initTokenAmountFromCallResult(
getSyrupLPToken(syrupInfo),
balanceState,
);
const totalStakedAmount = initTokenAmountFromCallResult(
getSyrupLPToken(syrupInfo),
totalSupplyState,
);
const totalRewardRate = new TokenAmount(token, JSBI.BigInt(rate));
//const pair = info[index].pair.toLowerCase();
//const fees = (pairData && pairData[pair] ? pairData[pair].oneDayVolumeUSD * 0.0025: 0);
const rewardRate = initTokenAmountFromCallResult(
token,
rewardRateState,
);
const getHypotheticalRewardRate = (
stakedAmount?: TokenAmount,
totalStakedAmount?: TokenAmount,
): TokenAmount | undefined => {
if (!stakedAmount || !totalStakedAmount || !rewardRate) return;
return new TokenAmount(
token,
JSBI.greaterThan(totalStakedAmount.raw, JSBI.BigInt(0))
? JSBI.divide(
JSBI.multiply(rewardRate.raw, stakedAmount.raw),
totalStakedAmount.raw,
)
: JSBI.BigInt(0),
);
};
const individualRewardRate = getHypotheticalRewardRate(
stakedAmount,
totalStakedAmount,
);
const periodFinishMs = syrupInfo.ending;
const [, stakingTokenPair] = stakingTokenPairs[index];
const tokenPairPrice = stakingTokenPair?.priceOf(token);
const usdPriceBaseToken = usdBaseTokenPrices[index];
const priceOfRewardTokenInUSD =
Number(tokenPairPrice?.toSignificant()) *
Number(usdPriceBaseToken?.toSignificant());
memo.push({
stakingRewardAddress: rewardsAddress,
token: syrupInfo.token,
ended: true,
name: syrupInfo.name,
lp: syrupInfo.lp,
periodFinish: periodFinishMs,
earnedAmount: initTokenAmountFromCallResult(
token,
earnedAmountState,
),
rewardRate: individualRewardRate,
totalRewardRate: totalRewardRate,
stakedAmount: stakedAmount,
totalStakedAmount: totalStakedAmount,
getHypotheticalRewardRate,
baseToken: syrupInfo.baseToken,
rate: 0,
rewardTokenPriceinUSD: priceOfRewardTokenInUSD,
stakingToken: syrupInfo.stakingToken,
valueOfTotalStakedAmountInUSDC: totalStakedAmount
? Number(totalStakedAmount.toExact()) * stakingTokenPrice
: undefined,
});
}
return memo;
},
[],
);
}, [
balances,
chainId,
earnedAmounts,
info,
rewardsAddresses,
totalSupplies,
uni,
rewardRates,
stakingTokenPairs,
usdBaseTokenPrices,
stakingTokenPrices,
]).filter((syrupInfo) =>
filter && filter.isStaked
? syrupInfo.stakedAmount && syrupInfo.stakedAmount.greaterThan('0')
: true,
);
}