config#DEFAULT_TOKEN_DECIMAL TypeScript Examples
The following examples show how to use
config#DEFAULT_TOKEN_DECIMAL.
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: farms.ts From glide-frontend with GNU General Public License v3.0 | 6 votes |
unstakeFarm = async (masterChefContract, pid, amount) => {
const value = new BigNumber(amount).times(DEFAULT_TOKEN_DECIMAL).toString()
if (pid === 0) {
const tx = await masterChefContract.leaveStaking(value, options)
const receipt = await tx.wait()
return receipt.status
}
const tx = await masterChefContract.withdraw(pid, value, options)
const receipt = await tx.wait()
return receipt.status
}
Example #2
Source File: useStakePool.ts From vvs-ui with GNU General Public License v3.0 | 6 votes |
sousStakeBnb = async (sousChefContract, amount) => {
const gasPrice = getGasPrice()
const tx = await sousChefContract.deposit(new BigNumber(amount).times(DEFAULT_TOKEN_DECIMAL).toString(), {
...options,
gasPrice,
})
const receipt = await tx.wait()
return receipt.status
}
Example #3
Source File: useFarmsWithBalance.tsx From vvs-ui with GNU General Public License v3.0 | 6 votes |
useFarmsWithBalance = () => {
const [farmsWithStakedBalance, setFarmsWithStakedBalance] = useState<FarmWithBalance[]>([])
const [earningsSum, setEarningsSum] = useState<number>(null)
const { account } = useWeb3React()
const { fastRefresh } = useRefresh()
useEffect(() => {
const fetchBalances = async () => {
const calls = farmsConfig.map((farm) => ({
address: getMasterChefAddress(),
name: 'pendingVVS',
params: [farm.pid, account],
}))
const rawResults = await multicall(masterChefABI, calls)
const results = farmsConfig.map((farm, index) => ({ ...farm, balance: new BigNumber(rawResults[index]) }))
const farmsWithBalances = results.filter((balanceType) => balanceType.balance.gt(0))
const totalEarned = farmsWithBalances.reduce((accum, earning) => {
const earningNumber = new BigNumber(earning.balance)
if (earningNumber.eq(0)) {
return accum
}
return accum + earningNumber.div(DEFAULT_TOKEN_DECIMAL).toNumber()
}, 0)
// const farmsWithBalances = []; // XXX debug hard code
// const totalEarned = 0; // XXX debug hard code
setFarmsWithStakedBalance(farmsWithBalances)
setEarningsSum(totalEarned)
}
if (account) {
fetchBalances()
}
}, [account, fastRefresh])
return { farmsWithStakedBalance, earningsSum }
}
Example #4
Source File: helpers.tsx From vvs-ui with GNU General Public License v3.0 | 6 votes |
processAuctionData = async (auctionId: number, auctionResponse: AuctionsResponse): Promise<Auction> => {
const processedAuctionData = {
...auctionResponse,
topLeaderboard: auctionResponse.leaderboard.toNumber(),
initialBidAmount: ethersToBigNumber(auctionResponse.initialBidAmount).div(DEFAULT_TOKEN_DECIMAL).toNumber(),
leaderboardThreshold: ethersToBigNumber(auctionResponse.leaderboardThreshold),
startBlock: auctionResponse.startBlock.toNumber(),
endBlock: auctionResponse.endBlock.toNumber(),
}
// Get all required data and blocks
const currentBlock = await simpleRpcProvider.getBlockNumber()
const startDate = await getDateForBlock(currentBlock, processedAuctionData.startBlock)
const endDate = await getDateForBlock(currentBlock, processedAuctionData.endBlock)
const auctionStatus = getAuctionStatus(
currentBlock,
processedAuctionData.startBlock,
processedAuctionData.endBlock,
processedAuctionData.status,
)
return {
id: auctionId,
startDate,
endDate,
auctionDuration: differenceInHours(endDate, startDate),
...processedAuctionData,
status: auctionStatus,
}
}
Example #5
Source File: farms.ts From vvs-ui with GNU General Public License v3.0 | 6 votes |
unstakeFarm = async (masterChefContract, pid, amount) => {
const gasPrice = getGasPrice()
const value = new BigNumber(amount).times(DEFAULT_TOKEN_DECIMAL).toString()
if (pid === 0) {
const tx = await masterChefContract.leaveStaking(value, { ...options, gasPrice })
const receipt = await tx.wait()
return receipt.status
}
const tx = await masterChefContract.withdraw(pid, value, { ...options, gasPrice })
const receipt = await tx.wait()
return receipt.status
}
Example #6
Source File: farms.ts From vvs-ui with GNU General Public License v3.0 | 6 votes |
stakeFarm = async (masterChefContract, pid, amount) => {
const gasPrice = getGasPrice()
const value = new BigNumber(amount).times(DEFAULT_TOKEN_DECIMAL).toString()
if (pid === 0) {
const tx = await masterChefContract.enterStaking(value, { ...options, gasPrice })
const receipt = await tx.wait()
return receipt.status
}
const tx = await masterChefContract.deposit(pid, value, { ...options, gasPrice })
const receipt = await tx.wait()
return receipt.status
}
Example #7
Source File: ProfileCreationProvider.tsx From glide-frontend with GNU General Public License v3.0 | 6 votes |
initialState: State = {
isInitialized: false,
currentStep: 0,
teamId: null,
selectedNft: {
nftAddress: null,
tokenId: null,
},
userName: '',
minimumCakeRequired: new BigNumber(totalCost).multipliedBy(DEFAULT_TOKEN_DECIMAL),
allowance: new BigNumber(allowance).multipliedBy(DEFAULT_TOKEN_DECIMAL),
}
Example #8
Source File: useFarmsWithBalance.tsx From glide-frontend with GNU General Public License v3.0 | 6 votes |
useFarmsWithBalance = () => {
const [farmsWithStakedBalance, setFarmsWithStakedBalance] = useState<FarmWithBalance[]>([])
const [earningsSum, setEarningsSum] = useState<number>(null)
const { account } = useWeb3React()
const { fastRefresh } = useRefresh()
useEffect(() => {
const fetchBalances = async () => {
const calls = farmsConfig.map((farm) => ({
address: getMasterChefAddress(),
name: 'pendingGlide',
params: [farm.pid, account],
}))
const rawResults = await multicall(masterChefABI, calls)
const results = farmsConfig.map((farm, index) => ({ ...farm, balance: new BigNumber(rawResults[index]) }))
const farmsWithBalances = results.filter((balanceType) => balanceType.balance.gt(0))
const totalEarned = farmsWithBalances.reduce((accum, earning) => {
const earningNumber = new BigNumber(earning.balance)
if (earningNumber.eq(0)) {
return accum
}
return accum + earningNumber.div(DEFAULT_TOKEN_DECIMAL).toNumber()
}, 0)
setFarmsWithStakedBalance(farmsWithBalances)
setEarningsSum(totalEarned)
}
if (account) {
fetchBalances()
}
}, [account, fastRefresh])
return { farmsWithStakedBalance, earningsSum }
}
Example #9
Source File: farms.ts From glide-frontend with GNU General Public License v3.0 | 6 votes |
stakeFarm = async (masterChefContract, pid, amount) => {
const value = new BigNumber(amount).times(DEFAULT_TOKEN_DECIMAL).toString()
if (pid === 0) {
const tx = await masterChefContract.enterStaking(value, options)
const receipt = await tx.wait()
return receipt.status
}
const tx = await masterChefContract.deposit(pid, value, options)
const receipt = await tx.wait()
return receipt.status
}
Example #10
Source File: useStakePool.ts From glide-frontend with GNU General Public License v3.0 | 5 votes |
sousStakeBnb = async (sousChefContract, amount) => {
const tx = await sousChefContract.deposit(new BigNumber(amount).times(DEFAULT_TOKEN_DECIMAL).toString(), options)
const receipt = await tx.wait()
return receipt.status
}
Example #11
Source File: Mint.tsx From glide-frontend with GNU General Public License v3.0 | 5 votes |
minimumCakeBalanceToMint = new BigNumber(MINT_COST).multipliedBy(DEFAULT_TOKEN_DECIMAL)
Example #12
Source File: UserName.tsx From glide-frontend with GNU General Public License v3.0 | 5 votes |
minimumCakeToRegister = new BigNumber(REGISTER_COST).multipliedBy(DEFAULT_TOKEN_DECIMAL)
Example #13
Source File: helpers.tsx From glide-frontend with GNU General Public License v3.0 | 5 votes |
processAuctionData = async (auctionId: number, auctionResponse: AuctionsResponse): Promise<Auction> => {
const processedAuctionData = {
...auctionResponse,
topLeaderboard: auctionResponse.leaderboard.toNumber(),
initialBidAmount: ethersToBigNumber(auctionResponse.initialBidAmount).div(DEFAULT_TOKEN_DECIMAL).toNumber(),
leaderboardThreshold: ethersToBigNumber(auctionResponse.leaderboardThreshold),
startBlock: auctionResponse.startBlock.toNumber(),
endBlock: auctionResponse.endBlock.toNumber(),
}
// Get all required datas and blocks
const currentBlock = await simpleRpcProvider.getBlockNumber()
const startDate = await getDateForBlock(currentBlock, processedAuctionData.startBlock)
const endDate = await getDateForBlock(currentBlock, processedAuctionData.endBlock)
const farmStartDate = add(endDate, { hours: 12 })
const blocksToFarmStartDate = hoursToSeconds(12) / ESC_BLOCK_TIME
const farmStartBlock = processedAuctionData.endBlock + blocksToFarmStartDate
const farmDurationInBlocks = hoursToSeconds(7 * 24) / ESC_BLOCK_TIME
const farmEndBlock = farmStartBlock + farmDurationInBlocks
const farmEndDate = add(farmStartDate, { weeks: 1 })
const auctionStatus = getAuctionStatus(
currentBlock,
processedAuctionData.startBlock,
processedAuctionData.endBlock,
processedAuctionData.status,
)
return {
id: auctionId,
startDate,
endDate,
auctionDuration: differenceInHours(endDate, startDate),
farmStartBlock,
farmStartDate,
farmEndBlock,
farmEndDate,
...processedAuctionData,
status: auctionStatus,
}
}
Example #14
Source File: useStakePool.ts From glide-frontend with GNU General Public License v3.0 | 5 votes |
sousStakeBnb = async (sousChefContract, amount) => {
const tx = await sousChefContract.deposit(new BigNumber(amount).times(DEFAULT_TOKEN_DECIMAL).toString(), options)
const receipt = await tx.wait()
return receipt.status
}
Example #15
Source File: ContributeModal.tsx From glide-frontend with GNU General Public License v3.0 | 4 votes |
ContributeModal: React.FC<Props> = ({
poolId,
ifo,
publicIfoData,
walletIfoData,
userCurrencyBalance,
onDismiss,
onSuccess,
}) => {
const publicPoolCharacteristics = publicIfoData[poolId]
const userPoolCharacteristics = walletIfoData[poolId]
const { currency } = ifo
const { limitPerUserInLP } = publicPoolCharacteristics
const { amountTokenCommittedInLP } = userPoolCharacteristics
const { contract } = walletIfoData
const [value, setValue] = useState('')
const { account } = useWeb3React()
const raisingTokenContract = useERC20(getAddress(currency.address))
const { t } = useTranslation()
const valueWithTokenDecimals = new BigNumber(value).times(DEFAULT_TOKEN_DECIMAL)
const { isApproving, isApproved, isConfirmed, isConfirming, handleApprove, handleConfirm } =
useApproveConfirmTransaction({
onRequiresApproval: async () => {
try {
const response = await raisingTokenContract.allowance(account, contract.address)
const currentAllowance = new BigNumber(response.toString())
return currentAllowance.gt(0)
} catch (error) {
return false
}
},
onApprove: () => {
return raisingTokenContract.approve(contract.address, ethers.constants.MaxUint256, { gasPrice })
},
onConfirm: () => {
return contract.depositPool(valueWithTokenDecimals.toString(), poolId === PoolIds.poolBasic ? 0 : 1, {
gasPrice,
})
},
onSuccess: async () => {
await onSuccess(valueWithTokenDecimals)
onDismiss()
},
})
const maximumLpCommitable = (() => {
if (limitPerUserInLP.isGreaterThan(0)) {
return limitPerUserInLP.minus(amountTokenCommittedInLP).isLessThanOrEqualTo(userCurrencyBalance)
? limitPerUserInLP
: userCurrencyBalance
}
return userCurrencyBalance
})()
return (
<Modal title={t('Contribute %symbol%', { symbol: currency.symbol })} onDismiss={onDismiss}>
<ModalBody maxWidth="320px">
{limitPerUserInLP.isGreaterThan(0) && (
<Flex justifyContent="space-between" mb="16px">
<Text>{t('Max. LP token entry')}</Text>
<Text>{getBalanceAmount(limitPerUserInLP, currency.decimals).toString()}</Text>
</Flex>
)}
<Flex justifyContent="space-between" mb="8px">
<Text>{t('Commit')}:</Text>
<Flex flexGrow={1} justifyContent="flex-end">
<Image
src={`/images/farms/${currency.symbol.split(' ')[0].toLocaleLowerCase()}.svg`}
width={24}
height={24}
/>
<Text>{currency.symbol}</Text>
</Flex>
</Flex>
<BalanceInput
value={value}
currencyValue={publicIfoData.currencyPriceInUSD.times(value || 0).toFixed(2)}
onUserInput={setValue}
isWarning={valueWithTokenDecimals.isGreaterThan(maximumLpCommitable)}
decimals={currency.decimals}
mb="8px"
/>
<Text color="textSubtle" textAlign="right" fontSize="12px" mb="16px">
{t('Balance: %balance%', {
balance: getBalanceAmount(userCurrencyBalance, currency.decimals).toString(),
})}
</Text>
<Flex justifyContent="space-between" mb="16px">
{multiplierValues.map((multiplierValue, index) => (
<Button
key={multiplierValue}
scale="xs"
variant="tertiary"
onClick={() => setValue(getBalanceAmount(maximumLpCommitable.times(multiplierValue)).toString())}
mr={index < multiplierValues.length - 1 ? '8px' : 0}
>
{multiplierValue * 100}%
</Button>
))}
</Flex>
<Text color="textSubtle" fontSize="12px" mb="24px">
{t(
'If you don’t commit enough LP tokens, you may not receive any IFO tokens at all and will only receive a full refund of your LP tokens.',
)}
</Text>
<ApproveConfirmButtons
isApproveDisabled={isConfirmed || isConfirming || isApproved}
isApproving={isApproving}
isConfirmDisabled={
!isApproved || isConfirmed || valueWithTokenDecimals.isNaN() || valueWithTokenDecimals.eq(0)
}
isConfirming={isConfirming}
onApprove={handleApprove}
onConfirm={handleConfirm}
/>
</ModalBody>
</Modal>
)
}
Example #16
Source File: PlaceBidModal.tsx From vvs-ui with GNU General Public License v3.0 | 4 votes |
PlaceBidModal: React.FC<PlaceBidModalProps> = ({
onDismiss,
initialBidAmount,
connectedBidder,
refreshBidders,
}) => {
const { account } = useWeb3React()
const { t } = useTranslation()
const { theme } = useTheme()
const { callWithGasPrice } = useCallWithGasPrice()
const [bid, setBid] = useState('')
const [isMultipleOfTen, setIsMultipleOfTen] = useState(false)
const [isMoreThanInitialBidAmount, setIsMoreThanInitialBidAmount] = useState(false)
const [userNotEnoughCake, setUserNotEnoughCake] = useState(false)
const [errorText, setErrorText] = useState(null)
const { balance: userCake, fetchStatus } = useTokenBalance(tokens.cake.address)
const userCakeBalance = getBalanceAmount(userCake)
const vvsPriceUsdc = usePriceVvsUsdc()
const farmAuctionContract = useFarmAuctionContract()
const cakeContract = useVvs()
const { toastSuccess } = useToast()
const { bidderData } = connectedBidder
const { amount, position } = bidderData
const isFirstBid = amount.isZero()
const isInvalidFirstBid = isFirstBid && !isMoreThanInitialBidAmount
useEffect(() => {
setIsMoreThanInitialBidAmount(parseFloat(bid) >= initialBidAmount)
setIsMultipleOfTen(parseFloat(bid) % 10 === 0 && parseFloat(bid) !== 0)
if (fetchStatus === FetchStatus.SUCCESS && userCakeBalance.lt(bid)) {
setUserNotEnoughCake(true)
} else {
setUserNotEnoughCake(false)
}
}, [bid, initialBidAmount, fetchStatus, userCakeBalance])
useEffect(() => {
if (userNotEnoughCake) {
setErrorText(t('Insufficient VVS balance'))
} else if (!isMoreThanInitialBidAmount && isFirstBid) {
setErrorText(t('First bid must be %initialBidAmount% VVS or more.', { initialBidAmount }))
} else if (!isMultipleOfTen) {
setErrorText(t('Bid must be a multiple of 10'))
} else {
setErrorText(null)
}
}, [isMultipleOfTen, isMoreThanInitialBidAmount, userNotEnoughCake, initialBidAmount, t, isFirstBid])
const { isApproving, isApproved, isConfirmed, isConfirming, handleApprove, handleConfirm } =
useApproveConfirmTransaction({
onRequiresApproval: async () => {
try {
const response = await cakeContract.allowance(account, farmAuctionContract.address)
const currentAllowance = ethersToBigNumber(response)
return currentAllowance.gt(0)
} catch (error) {
return false
}
},
onApprove: () => {
return callWithGasPrice(cakeContract, 'approve', [farmAuctionContract.address, ethers.constants.MaxUint256])
},
onApproveSuccess: async ({ receipt }) => {
toastSuccess(
t('Contract approved - you can now place your bid!'),
<ToastDescriptionWithTx txHash={receipt.transactionHash} />,
)
},
onConfirm: () => {
const bidAmount = new BigNumber(bid).times(DEFAULT_TOKEN_DECIMAL).toString()
return callWithGasPrice(farmAuctionContract, 'bid', [bidAmount])
},
onSuccess: async ({ receipt }) => {
refreshBidders()
onDismiss()
toastSuccess(t('Bid placed!'), <ToastDescriptionWithTx txHash={receipt.transactionHash} />)
},
})
const handleInputChange = (input: string) => {
setBid(input)
}
const setPercentageValue = (percentage: number) => {
const rounding = percentage === 1 ? BigNumber.ROUND_FLOOR : BigNumber.ROUND_CEIL
const valueToSet = getBalanceAmount(userCake.times(percentage)).div(10).integerValue(rounding).times(10)
setBid(valueToSet.toString())
}
return (
<StyledModal title={t('Place a Bid')} onDismiss={onDismiss} headerBackground={theme.colors.gradients.cardHeader}>
<ExistingInfo>
<Flex justifyContent="space-between">
<Text>{t('Your existing bid')}</Text>
<Text>{t('%num% CAKE', { num: getBalanceNumber(amount).toLocaleString() })}</Text>
</Flex>
<Flex justifyContent="space-between">
<Text>{t('Your position')}</Text>
<Text>{position ? `#${position}` : '-'}</Text>
</Flex>
</ExistingInfo>
<InnerContent>
<Flex justifyContent="space-between" alignItems="center" pb="8px">
<Text>{t('Bid a multiple of 10')}</Text>
<Flex>
<PancakeRoundIcon width="24px" height="24px" mr="4px" />
<Text bold>CAKE</Text>
</Flex>
</Flex>
{isFirstBid && (
<Text pb="8px" small>
{t('First bid must be %initialBidAmount% CAKE or more.', { initialBidAmount })}
</Text>
)}
<BalanceInput
isWarning={!isMultipleOfTen || isInvalidFirstBid}
placeholder="0"
value={bid}
onUserInput={handleInputChange}
currencyValue={
vvsPriceUsdc.gt(0) &&
`~${bid ? vvsPriceUsdc.times(new BigNumber(bid)).toNumber().toLocaleString() : '0.00'} USD`
}
/>
<Flex justifyContent="flex-end" mt="8px">
<Text fontSize="12px" color="textSubtle" mr="8px">
{t('Balance')}:
</Text>
<Text fontSize="12px" color="textSubtle">
{formatNumber(userCakeBalance.toNumber(), 3, 3)}
</Text>
</Flex>
{errorText && (
<Text color="failure" textAlign="right" fontSize="12px">
{errorText}
</Text>
)}
<Flex justifyContent="space-between" mt="8px" mb="24px">
<Button
disabled={fetchStatus !== FetchStatus.SUCCESS}
scale="xs"
mx="2px"
p="4px 16px"
variant="tertiary"
onClick={() => setPercentageValue(0.25)}
>
25%
</Button>
<Button
disabled={fetchStatus !== FetchStatus.SUCCESS}
scale="xs"
mx="2px"
p="4px 16px"
variant="tertiary"
onClick={() => setPercentageValue(0.5)}
>
50%
</Button>
<Button
disabled={fetchStatus !== FetchStatus.SUCCESS}
scale="xs"
mx="2px"
p="4px 16px"
variant="tertiary"
onClick={() => setPercentageValue(0.75)}
>
75%
</Button>
<Button
disabled={fetchStatus !== FetchStatus.SUCCESS}
scale="xs"
mx="2px"
p="4px 16px"
variant="tertiary"
onClick={() => setPercentageValue(1)}
>
MAX
</Button>
</Flex>
<Flex flexDirection="column">
{account ? (
<ApproveConfirmButtons
isApproveDisabled={isApproved}
isApproving={isApproving}
isConfirmDisabled={
!isMultipleOfTen ||
getBalanceAmount(userCake).lt(bid) ||
isConfirmed ||
isInvalidFirstBid ||
userNotEnoughCake
}
isConfirming={isConfirming}
onApprove={handleApprove}
onConfirm={handleConfirm}
buttonArrangement={ButtonArrangement.SEQUENTIAL}
/>
) : (
<ConnectWalletButton />
)}
</Flex>
<Text color="textSubtle" small mt="24px">
{t('If your bid is unsuccessful, you’ll be able to reclaim your CAKE after the auction.')}
</Text>
</InnerContent>
</StyledModal>
)
}
Example #17
Source File: PlaceBidModal.tsx From glide-frontend with GNU General Public License v3.0 | 4 votes |
PlaceBidModal: React.FC<PlaceBidModalProps> = ({
onDismiss,
initialBidAmount,
conncetedBidder,
refreshBidders,
}) => {
const { account } = useWeb3React()
const { t } = useTranslation()
const { theme } = useTheme()
const [bid, setBid] = useState('')
const [isMultipleOfTen, setIsMultipleOfTen] = useState(false)
const [isMoreThanInitialBidAmount, setIsMoreThanInitialBidAmount] = useState(false)
const [userNotEnoughCake, setUserNotEnoughCake] = useState(false)
const [errorText, setErrorText] = useState(null)
const { balance: userCake, fetchStatus } = useTokenBalance(getCakeAddress())
const userCakeBalance = getBalanceAmount(userCake)
const cakePriceUsdc = usePriceCakeUsdc()
const farmAuctionContract = useFarmAuctionContract()
const cakeContract = useCake()
const { toastSuccess } = useToast()
const { bidderData } = conncetedBidder
const { amount, position } = bidderData
const isFirstBid = amount.isZero()
const isInvalidFirstBid = isFirstBid && !isMoreThanInitialBidAmount
useEffect(() => {
setIsMoreThanInitialBidAmount(parseFloat(bid) >= initialBidAmount)
setIsMultipleOfTen(parseFloat(bid) % 10 === 0 && parseFloat(bid) !== 0)
if (fetchStatus === FetchStatus.SUCCESS && userCakeBalance.lt(bid)) {
setUserNotEnoughCake(true)
} else {
setUserNotEnoughCake(false)
}
}, [bid, initialBidAmount, fetchStatus, userCakeBalance])
useEffect(() => {
if (userNotEnoughCake) {
setErrorText(t('Insufficient CAKE balance'))
} else if (!isMoreThanInitialBidAmount && isFirstBid) {
setErrorText(t('First bid must be %initialBidAmount% CAKE or more.', { initialBidAmount }))
} else if (!isMultipleOfTen) {
setErrorText(t('Bid must be a multiple of 10'))
} else {
setErrorText(null)
}
}, [isMultipleOfTen, isMoreThanInitialBidAmount, userNotEnoughCake, initialBidAmount, t, isFirstBid])
const { isApproving, isApproved, isConfirmed, isConfirming, handleApprove, handleConfirm } =
useApproveConfirmTransaction({
onRequiresApproval: async () => {
try {
const response = await cakeContract.allowance(account, farmAuctionContract.address)
const currentAllowance = ethersToBigNumber(response)
return currentAllowance.gt(0)
} catch (error) {
return false
}
},
onApprove: () => {
return cakeContract.approve(farmAuctionContract.address, ethers.constants.MaxUint256)
},
onApproveSuccess: async () => {
toastSuccess(t('Contract approved - you can now place your bid!'))
},
onConfirm: () => {
const bidAmount = new BigNumber(bid).times(DEFAULT_TOKEN_DECIMAL).toString()
return farmAuctionContract.bid(bidAmount)
},
onSuccess: async () => {
refreshBidders()
onDismiss()
toastSuccess(t('Bid placed!'))
},
})
const handleInputChange = (input: string) => {
setBid(input)
}
const setPercetageValue = (percentage: number) => {
const rounding = percentage === 1 ? BigNumber.ROUND_FLOOR : BigNumber.ROUND_CEIL
const valueToSet = getBalanceAmount(userCake.times(percentage)).div(10).integerValue(rounding).times(10)
setBid(valueToSet.toString())
}
return (
<StyledModal title={t('Place a Bid')} onDismiss={onDismiss} headerBackground={theme.colors.gradients.cardHeader}>
<ExistingInfo>
<Flex justifyContent="space-between">
<Text>{t('Your existing bid')}</Text>
<Text>{t('%num% CAKE', { num: getBalanceNumber(amount).toLocaleString() })}</Text>
</Flex>
<Flex justifyContent="space-between">
<Text>{t('Your position')}</Text>
<Text>{position ? `#${position}` : '-'}</Text>
</Flex>
</ExistingInfo>
<InnerContent>
<Flex justifyContent="space-between" alignItems="center" pb="8px">
<Text>{t('Bid a multiple of 10')}</Text>
<Flex>
{/* <PancakeRoundIcon width="24px" height="24px" mr="4px" /> */}
<Text bold>CAKE</Text>
</Flex>
</Flex>
{isFirstBid && (
<Text pb="8px" small>
{t('First bid must be %initialBidAmount% CAKE or more.', { initialBidAmount })}
</Text>
)}
<BalanceInput
isWarning={!isMultipleOfTen || isInvalidFirstBid}
placeholder="0"
value={bid}
onUserInput={handleInputChange}
currencyValue={
cakePriceUsdc.gt(0) &&
`~${bid ? cakePriceUsdc.times(new BigNumber(bid)).toNumber().toLocaleString() : '0.00'} USD`
}
/>
<Flex justifyContent="flex-end" mt="8px">
<Text fontSize="12px" color="textSubtle" mr="8px">
{t('Balance')}:
</Text>
<Text fontSize="12px" color="textSubtle">
{formatNumber(userCakeBalance.toNumber(), 3, 3)}
</Text>
</Flex>
{errorText && (
<Text color="failure" textAlign="right" fontSize="12px">
{errorText}
</Text>
)}
<Flex justifyContent="space-between" mt="8px" mb="24px">
<Button
disabled={fetchStatus !== FetchStatus.SUCCESS}
scale="xs"
mx="2px"
p="4px 16px"
variant="tertiary"
onClick={() => setPercetageValue(0.25)}
>
25%
</Button>
<Button
disabled={fetchStatus !== FetchStatus.SUCCESS}
scale="xs"
mx="2px"
p="4px 16px"
variant="tertiary"
onClick={() => setPercetageValue(0.5)}
>
50%
</Button>
<Button
disabled={fetchStatus !== FetchStatus.SUCCESS}
scale="xs"
mx="2px"
p="4px 16px"
variant="tertiary"
onClick={() => setPercetageValue(0.75)}
>
75%
</Button>
<Button
disabled={fetchStatus !== FetchStatus.SUCCESS}
scale="xs"
mx="2px"
p="4px 16px"
variant="tertiary"
onClick={() => setPercetageValue(1)}
>
MAX
</Button>
</Flex>
<Flex flexDirection="column">
{account ? (
<ApproveConfirmButtons
isApproveDisabled={isApproved}
isApproving={isApproving}
isConfirmDisabled={
!isMultipleOfTen ||
getBalanceAmount(userCake).lt(bid) ||
isConfirmed ||
isInvalidFirstBid ||
userNotEnoughCake
}
isConfirming={isConfirming}
onApprove={handleApprove}
onConfirm={handleConfirm}
buttonArrangement={ButtonArrangement.SEQUENTIAL}
/>
) : (
<ConnectWalletButton />
)}
</Flex>
<Text color="textSubtle" small mt="24px">
{t('If your bid is unsuccessful, you’ll be able to reclaim your CAKE after the auction.')}
</Text>
</InnerContent>
</StyledModal>
)
}
Example #18
Source File: ContributeModal.tsx From vvs-ui with GNU General Public License v3.0 | 4 votes |
ContributeModal: React.FC<Props> = ({
poolId,
ifo,
publicIfoData,
walletIfoData,
userCurrencyBalance,
onDismiss,
onSuccess,
}) => {
const publicPoolCharacteristics = publicIfoData[poolId]
const userPoolCharacteristics = walletIfoData[poolId]
const { currency } = ifo
const { limitPerUserInLP } = publicPoolCharacteristics
const { amountTokenCommittedInLP } = userPoolCharacteristics
const { contract } = walletIfoData
const [value, setValue] = useState('')
const { account } = useWeb3React()
const { callWithGasPrice } = useCallWithGasPrice()
const raisingTokenContract = useERC20(currency.address)
const { t } = useTranslation()
const valueWithTokenDecimals = new BigNumber(value).times(DEFAULT_TOKEN_DECIMAL)
const { isApproving, isApproved, isConfirmed, isConfirming, handleApprove, handleConfirm } =
useApproveConfirmTransaction({
onRequiresApproval: async () => {
try {
const response = await raisingTokenContract.allowance(account, contract.address)
const currentAllowance = new BigNumber(response.toString())
return currentAllowance.gt(0)
} catch (error) {
return false
}
},
onApprove: () => {
return callWithGasPrice(raisingTokenContract, 'approve', [contract.address, ethers.constants.MaxUint256], {
gasPrice,
})
},
onConfirm: () => {
return callWithGasPrice(
contract,
'depositPool',
[valueWithTokenDecimals.toString(), poolId === PoolIds.poolBasic ? 0 : 1],
{
gasPrice,
},
)
},
onSuccess: async ({ receipt }) => {
await onSuccess(valueWithTokenDecimals, receipt.transactionHash)
onDismiss()
},
})
const maximumLpCommitable = (() => {
if (limitPerUserInLP.isGreaterThan(0)) {
return limitPerUserInLP.minus(amountTokenCommittedInLP).isLessThanOrEqualTo(userCurrencyBalance)
? limitPerUserInLP
: userCurrencyBalance
}
return userCurrencyBalance
})()
return (
<Modal title={t('Contribute %symbol%', { symbol: currency.symbol })} onDismiss={onDismiss}>
<ModalBody maxWidth="320px">
{limitPerUserInLP.isGreaterThan(0) && (
<Flex justifyContent="space-between" mb="16px">
<Text>{t('Max. LP token entry')}</Text>
<Text>{getBalanceAmount(limitPerUserInLP, currency.decimals).toString()}</Text>
</Flex>
)}
<Flex justifyContent="space-between" mb="8px">
<Text>{t('Commit')}:</Text>
<Flex flexGrow={1} justifyContent="flex-end">
<Image
src={`/images/farms/${currency.symbol.split(' ')[0].toLocaleLowerCase()}.svg`}
width={24}
height={24}
/>
<Text>{currency.symbol}</Text>
</Flex>
</Flex>
<BalanceInput
value={value}
currencyValue={publicIfoData.currencyPriceInUSD.times(value || 0).toFixed(2)}
onUserInput={setValue}
isWarning={valueWithTokenDecimals.isGreaterThan(maximumLpCommitable)}
decimals={currency.decimals}
mb="8px"
/>
<Text color="textSubtle" textAlign="right" fontSize="12px" mb="16px">
{t('Balance: %balance%', {
balance: getBalanceAmount(userCurrencyBalance, currency.decimals).toString(),
})}
</Text>
<Flex justifyContent="space-between" mb="16px">
{multiplierValues.map((multiplierValue, index) => (
<Button
key={multiplierValue}
scale="xs"
variant="tertiary"
onClick={() => setValue(getBalanceAmount(maximumLpCommitable.times(multiplierValue)).toString())}
mr={index < multiplierValues.length - 1 ? '8px' : 0}
>
{multiplierValue * 100}%
</Button>
))}
</Flex>
<Text color="textSubtle" fontSize="12px" mb="24px">
{t(
'If you don’t commit enough LP tokens, you may not receive any IFO tokens at all and will only receive a full refund of your LP tokens.',
)}
</Text>
<ApproveConfirmButtons
isApproveDisabled={isConfirmed || isConfirming || isApproved}
isApproving={isApproving}
isConfirmDisabled={
!isApproved || isConfirmed || valueWithTokenDecimals.isNaN() || valueWithTokenDecimals.eq(0)
}
isConfirming={isConfirming}
onApprove={handleApprove}
onConfirm={handleConfirm}
/>
</ModalBody>
</Modal>
)
}