增加ido兑换

This commit is contained in:
myf 2022-05-20 11:17:20 +08:00
parent 666ee04c6d
commit 3a4c81deb7
22 changed files with 575 additions and 108 deletions

View File

@ -1153,5 +1153,11 @@
"gross": "总量", "gross": "总量",
"remaining quantity": "剩余数量", "remaining quantity": "剩余数量",
"Immediately change": "立即兑换", "Immediately change": "立即兑换",
"IDO Exchange": "IDO 兑换" "IDO Exchange": "IDO 兑换",
"Get": "领取",
"IDO Get": "IDO 领取",
"Estimated time of collection": "预计领取时间",
"amount": "金额",
"Change the end": "兑换结束",
"After purchase, it is expected to be available for collection in %time% time. Do you confirm the purchase": "购买后,预计%time%时间后可进行领取,是否确认购买"
} }

View File

@ -57,9 +57,14 @@ const Menu = (props) => {
sign() sign()
} }
}, [unActiveAccount, hasWalletLogin, library]) }, [unActiveAccount, hasWalletLogin, library])
const [price, setPrice] = useState(0)
useEffect(() => { useEffect(() => {
getDetails() getDetails()
if (hccPriceUsdt.toString() === 'Infinity') {
setPrice(0)
} else {
setPrice(hccPriceUsdt.toNumber())
}
}, []) }, [])
return ( return (
<UikitMenu <UikitMenu
@ -72,7 +77,7 @@ const Menu = (props) => {
currentLang={currentLanguage.code} currentLang={currentLanguage.code}
langs={languageList} langs={languageList}
setLang={setLanguage} setLang={setLanguage}
cakePriceUsd={hccPriceUsdt.toNumber()} cakePriceUsd={price}
links={config(t)} links={config(t)}
socialLink={socialLink} socialLink={socialLink}
{...props} {...props}

View File

@ -17,6 +17,15 @@
"name": "AddRound", "name": "AddRound",
"type": "event" "type": "event"
}, },
{
"anonymous": false,
"inputs": [
{ "indexed": true, "internalType": "address", "name": "user", "type": "address" },
{ "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" }
],
"name": "Harvest",
"type": "event"
},
{ {
"anonymous": false, "anonymous": false,
"inputs": [ "inputs": [
@ -26,6 +35,12 @@
"name": "OwnershipTransferred", "name": "OwnershipTransferred",
"type": "event" "type": "event"
}, },
{
"anonymous": false,
"inputs": [{ "indexed": false, "internalType": "uint256", "name": "newLockTime", "type": "uint256" }],
"name": "SetLockTimeEvent",
"type": "event"
},
{ {
"anonymous": false, "anonymous": false,
"inputs": [ "inputs": [
@ -74,6 +89,14 @@
"stateMutability": "view", "stateMutability": "view",
"type": "function" "type": "function"
}, },
{ "inputs": [], "name": "harvest", "outputs": [], "stateMutability": "nonpayable", "type": "function" },
{
"inputs": [],
"name": "lockTime",
"outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
"stateMutability": "view",
"type": "function"
},
{ {
"inputs": [], "inputs": [],
"name": "owner", "name": "owner",
@ -105,7 +128,24 @@
"stateMutability": "view", "stateMutability": "view",
"type": "function" "type": "function"
}, },
{
"inputs": [
{ "internalType": "uint256", "name": "round", "type": "uint256" },
{ "internalType": "uint256", "name": "amount", "type": "uint256" }
],
"name": "purchaseWithLock",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{ "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" },
{
"inputs": [{ "internalType": "uint256", "name": "_lockTime", "type": "uint256" }],
"name": "setLockTime",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{ "inputs": [], "name": "setPause", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "setPause", "outputs": [], "stateMutability": "nonpayable", "type": "function" },
{ {
"inputs": [ "inputs": [
@ -127,5 +167,12 @@
"outputs": [], "outputs": [],
"stateMutability": "nonpayable", "stateMutability": "nonpayable",
"type": "function" "type": "function"
},
{
"inputs": [{ "internalType": "address", "name": "", "type": "address" }],
"name": "userInfo",
"outputs": [{ "internalType": "uint256", "name": "purchasedAmount", "type": "uint256" }],
"stateMutability": "view",
"type": "function"
} }
] ]

View File

@ -8,7 +8,7 @@ export default {
56: '0x6ab8463a4185b80905e05a9ff80a2d6b714b9e95', 56: '0x6ab8463a4185b80905e05a9ff80a2d6b714b9e95',
}, },
boardChef: { boardChef: {
97: '0x126935cae1988efbf8e310abe6be1f9046eaf0ac', 97: '0x2D807e54A07e3B404823359eeD854Aa54AC4F237',
56: '0xD34871F12ace1BB8034E18009104b9dA60B84250', // NEED CHANGE 节点董事会合约 56: '0xD34871F12ace1BB8034E18009104b9dA60B84250', // NEED CHANGE 节点董事会合约
}, },
boardRewardChef: { boardRewardChef: {
@ -24,7 +24,7 @@ export default {
56: '0x46271393dd6f2c8798a44f857888aa6a85af3527', // NEED CHANGE 持币人分红 56: '0x46271393dd6f2c8798a44f857888aa6a85af3527', // NEED CHANGE 持币人分红
}, },
referralChef: { referralChef: {
97: '0x8a5dc1e8262d6a3de664624fdc13a533ba64e60d', 97: '0x16ed5C884a0aA02c2E0FA9064F3EB5A8Da58B659',
56: '0x88F46EF2Ee08494D84942DCA3bd24cDEf7C88Ae2', // NEED CHANGE 邀请或则军团长 56: '0x88F46EF2Ee08494D84942DCA3bd24cDEf7C88Ae2', // NEED CHANGE 邀请或则军团长
}, },
referralRewardChef: { referralRewardChef: {
@ -32,8 +32,8 @@ export default {
56: '0x88F46EF2Ee08494D84942DCA3bd24cDEf7C88Ae2', // NEED CHANGE 邀请或则军团长收益 56: '0x88F46EF2Ee08494D84942DCA3bd24cDEf7C88Ae2', // NEED CHANGE 邀请或则军团长收益
}, },
idoPurchase: { idoPurchase: {
97: '0xc9f05c406876364fd13fbf15a9dc5de4f8cd1eda', 97: '0x7657AF82EA0A59Cdc697d2c7b7b67E376ed36ec2',
56: '0x2bAA17bDeC5cDF2943309B245EF5310FF9c46B01', // NEED CHANGE IDO兑换 56: '0x7657AF82EA0A59Cdc697d2c7b7b67E376ed36ec2', // NEED CHANGE IDO兑换
}, },
lotteryV2: { lotteryV2: {
97: '0x5790c3534F30437641541a0FA04C992799602998', 97: '0x5790c3534F30437641541a0FA04C992799602998',

View File

@ -73,7 +73,7 @@ const tokens = {
symbol: 'HCC', symbol: 'HCC',
address: { address: {
56: '0x20de22029ab63cf9A7Cf5fEB2b737Ca1eE4c82A6', 56: '0x20de22029ab63cf9A7Cf5fEB2b737Ca1eE4c82A6',
97: '0x77f2efa78c1c2798ad3c753330aa4e1babcaeff8', 97: '0x6F9B2c66BbefE35a364280A2E8B51b255eC51678',
}, },
decimals: 18, decimals: 18,
projectLink: 'https://tranchess.com/', projectLink: 'https://tranchess.com/',

View File

@ -1280,5 +1280,11 @@
"gross": "gross", "gross": "gross",
"remaining quantity": "remaining quantity", "remaining quantity": "remaining quantity",
"Immediately change": "Immediately change", "Immediately change": "Immediately change",
"IDO Exchange": "IDO Exchange" "IDO Exchange": "IDO Exchange",
"Get": "Get",
"IDO Get": "IDO Get",
"Estimated time of collection": "Estimated time of collection",
"amount": "amount",
"Change the end": "Change the end",
"After purchase, it is expected to be available for collection in %time% time. Do you confirm the purchase": "After purchase, it is expected to be available for collection in %time% time. Do you confirm the purchase"
} }

View File

@ -2,7 +2,7 @@ import request from 'utils/request'
export const getPurchaseActivity = () => { export const getPurchaseActivity = () => {
return request.request({ return request.request({
url: '/high_city/app/api/purchasr/activity/current', url: '/high_city/app/api/purchase/activity/current',
method: 'get', method: 'get',
}) })
} }

View File

@ -129,6 +129,9 @@ export const getReferralchefContract = (signer?: ethers.Signer | ethers.provider
export const getReferralRewardchefContract = (signer?: ethers.Signer | ethers.providers.Provider) => { export const getReferralRewardchefContract = (signer?: ethers.Signer | ethers.providers.Provider) => {
return getContract(referralRewardChef, getReferralRewardAddress(), signer) return getContract(referralRewardChef, getReferralRewardAddress(), signer)
} }
export const getIdoPurchaseContract = (signer?: ethers.Signer | ethers.providers.Provider) => {
return getContract(idoPurchase, getIdoPurchaseAddress(), signer)
}
export const getClaimRefundContract = (signer?: ethers.Signer | ethers.providers.Provider) => { export const getClaimRefundContract = (signer?: ethers.Signer | ethers.providers.Provider) => {
return getContract(claimRefundAbi, getClaimRefundAddress(), signer) return getContract(claimRefundAbi, getClaimRefundAddress(), signer)
} }
@ -158,6 +161,3 @@ export const getBunnySpecialCakeVaultContract = (signer?: ethers.Signer | ethers
export const getBunnySpecialPredictionContract = (signer?: ethers.Signer | ethers.providers.Provider) => { export const getBunnySpecialPredictionContract = (signer?: ethers.Signer | ethers.providers.Provider) => {
return getContract(bunnySpecialPredictionAbi, getBunnySpecialPredictionAddress(), signer) return getContract(bunnySpecialPredictionAbi, getBunnySpecialPredictionAddress(), signer)
} }
export const getIdoPurchaseContract = (signer?: ethers.Signer | ethers.providers.Provider) => {
return getContract(idoPurchase, getIdoPurchaseAddress(), signer)
}

View File

@ -65,6 +65,6 @@ export const formatFixedNumber = (number: ethers.FixedNumber, displayDecimals =
return formatBigNumber(ethers.BigNumber.from(leftSide), displayDecimals, decimals) return formatBigNumber(ethers.BigNumber.from(leftSide), displayDecimals, decimals)
} }
export const formatDivNumber = (number: number, decimals = 4) => { export const formatDivNumber = (number: BigNumber | number, decimals = 4) => {
return new BigNumber(number).div(BIG_TEN.pow(decimals)).toNumber() return new BigNumber(number).div(BIG_TEN.pow(decimals)).toNumber()
} }

View File

@ -119,7 +119,7 @@ const BoardCard: React.FC<NodeCardProps> = ({ board, account, boardsData }) => {
const date2 = dayjs(date) const date2 = dayjs(date)
const time = date2.diff(date1) const time = date2.diff(date1)
if (time > 0) { if (time > 0) {
const hour = Math.floor((time / (1000 * 60 * 60)) % 24) const hour = Math.floor(time / (1000 * 60 * 60))
const minute = Math.floor((time / (1000 * 60)) % 60) const minute = Math.floor((time / (1000 * 60)) % 60)
const second = Math.round((time / 1000) % 60) const second = Math.round((time / 1000) % 60)
setCountDown(`${hour}:${minute}:${second}`) setCountDown(`${hour}:${minute}:${second}`)

View File

@ -1,4 +1,4 @@
import React, { useState, useCallback, useMemo } from 'react' import React, { useState, useCallback, useMemo, useEffect } from 'react'
import BigNumber from 'bignumber.js' import BigNumber from 'bignumber.js'
import styled from 'styled-components' import styled from 'styled-components'
import { provider as ProviderType } from 'web3-core' import { provider as ProviderType } from 'web3-core'
@ -50,6 +50,15 @@ const CardActions: React.FC<NodeCardActionsProps> = ({ board, account }) => {
const displayBalance = rawEarningsBalance.toFixed(3, BigNumber.ROUND_DOWN) const displayBalance = rawEarningsBalance.toFixed(3, BigNumber.ROUND_DOWN)
const hccPriceUsdt = usePriceHccUsdt() const hccPriceUsdt = usePriceHccUsdt()
const [price, setPrice] = useState(0)
useEffect(() => {
if (hccPriceUsdt.toString() === 'Infinity') {
setPrice(0)
} else {
setPrice(Number(hccPriceUsdt.toNumber().toFixed(3)))
}
}, [])
const handleApprove = useCallback(async () => { const handleApprove = useCallback(async () => {
try { try {
setRequestedApproval(true) setRequestedApproval(true)
@ -76,7 +85,7 @@ const CardActions: React.FC<NodeCardActionsProps> = ({ board, account }) => {
{displayBalance} {displayBalance}
</Text> </Text>
<Text fontSize="12px" color="#9BE5EB"> <Text fontSize="12px" color="#9BE5EB">
{(Number(hccPriceUsdt.toNumber().toFixed(3)) * Number(displayBalance)).toFixed(3)} USDT {price ? (price * Number(displayBalance)).toFixed(3) : 0} USDT
</Text> </Text>
</PriceCoin> </PriceCoin>
</Flex> </Flex>

View File

@ -39,7 +39,6 @@ const StakeAction: React.FC<NodeCardActionsProps> = ({ stakedBalance, tokenBalan
const { t } = useTranslation() const { t } = useTranslation()
const { toastWarning } = useToast() const { toastWarning } = useToast()
const { onStake } = useStakeBoard(pid) const { onStake } = useStakeBoard(pid)
console.log(onStake)
const { onUnstake } = useUnstakeBoard(pid) const { onUnstake } = useUnstakeBoard(pid)
const { onUnstake: onUnstakeForce } = useUnstakeForceBoard(pid) const { onUnstake: onUnstakeForce } = useUnstakeForceBoard(pid)
const { tokenDecimals = 18, minStakeAmount, userData } = useBoardsFromPid(pid) const { tokenDecimals = 18, minStakeAmount, userData } = useBoardsFromPid(pid)

View File

@ -141,6 +141,7 @@ const FristCom: React.FC = () => {
market: 0, market: 0,
}) })
const hccPriceUsdt = usePriceHccUsdt() const hccPriceUsdt = usePriceHccUsdt()
const [price, setPrice] = useState(0)
const [linkList, setLinkList] = useState([]) const [linkList, setLinkList] = useState([])
const getDetail = async () => { const getDetail = async () => {
@ -155,6 +156,11 @@ const FristCom: React.FC = () => {
setDetail(data) setDetail(data)
} }
useEffect(() => { useEffect(() => {
if (hccPriceUsdt.toString() === 'Infinity') {
setPrice(0)
} else {
setPrice(hccPriceUsdt.toNumber())
}
getDetail() getDetail()
}, []) }, [])
const openLink = (link) => { const openLink = (link) => {
@ -201,7 +207,7 @@ const FristCom: React.FC = () => {
<ScoreDiv> <ScoreDiv>
<FlexItemCom name={t('Number of holders')} valueNum={detail?.userCount} /> <FlexItemCom name={t('Number of holders')} valueNum={detail?.userCount} />
<FlexItemCom name={t('Your volume')} valueNum={detail?.volume} /> <FlexItemCom name={t('Your volume')} valueNum={detail?.volume} />
<FlexItemCom name={t('market value')} valueNum={detail?.market * Number(hccPriceUsdt) || 0} /> <FlexItemCom name={t('market value')} valueNum={detail?.market * price || 0} />
{/* {burned.map((item) => { {/* {burned.map((item) => {
return <FlexItemCom key={item.id} name={item.name} value={item.value} /> return <FlexItemCom key={item.id} name={item.name} value={item.value} />
})} */} })} */}

View File

@ -0,0 +1,37 @@
import BigNumber from 'bignumber.js'
import React, { useCallback, useMemo, useState } from 'react'
import { Button, Modal, Text } from '@pancakeswap/uikit'
import { ModalActions, ModalInput } from 'components/Modal'
import { useTranslation } from 'contexts/Localization'
import useToast from 'hooks/useToast'
import { getFullDisplayBalance } from 'utils/formatBalance'
interface AffirmModalProps {
title?: string
content?: string
onDismiss?: () => void
handSubmit?: () => void
}
const BuyModal: React.FC<AffirmModalProps> = ({ title, content, onDismiss, handSubmit }) => {
const { t } = useTranslation()
const submit = async () => {
await handSubmit()
onDismiss()
}
return (
<Modal title={t(`${title}`)} onDismiss={onDismiss}>
<Text>{!content ? t('Whether to cancel') : content}</Text>
<ModalActions>
<Button variant="secondary" onClick={onDismiss} width="100%">
{t('Cancel')}
</Button>
<Button width="100%" onClick={submit}>
{t('Confirm')}
</Button>
</ModalActions>
</Modal>
)
}
export default BuyModal

View File

@ -0,0 +1,79 @@
import React, { useMemo, useState, useEffect, useCallback } from 'react'
import dayjs from 'dayjs'
import styled, { keyframes } from 'styled-components'
import { useTranslation } from 'contexts/Localization'
import { Flex, Text, Button, Input } from '@pancakeswap/uikit'
import { useHarvest } from '../hooks'
interface GetCardProps {
price?: number | string
time?: number | string
}
const FCard = styled.div`
width: 434px;
background: ${(props) => props.theme.card.background};
border-radius: 32px;
box-shadow: 0px 2px 30px 0px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
position: relative;
text-align: left;
padding: 27px 20px;
margin-top: 50px;
`
const ExchangeCard: React.FC<GetCardProps> = ({ price = 0, time = 0 }) => {
const { t } = useTranslation()
// const account = useAccount()
// const lockTime = useLockTime()
// const [time, setTime] = useState(0)
// const userInfo = useUserInfo()
// const [price, setPrice] = useState(0)
// const init = async () => {
// const data = await lockTime()
// console.log(data)
// setTime(data)
// const info = await userInfo(account)
// console.log(info)
// setPrice(info)
// }
// useEffect(() => {
// if (account) {
// init()
// }
// }, [account])
const harvest = useHarvest()
const getPrice = async () => {
const res = await harvest()
console.log(res)
}
return (
<FCard>
{/* 锁仓时间大于当前时间 不可领取 */}
{/* 锁仓时间小于当前时间 可领取 */}
{/* 当前时间大于锁仓时间 不显示 */}
<Flex justifyContent="space-between" alignItems="center">
<div>
<Text>{t('IDO Get')}</Text>
{new Date().getTime() <= time && (
<Text>
{t('Estimated time of collection')}{dayjs(time).format('YYYY-MM-DD HH:mm:ss')}
</Text>
)}
<Flex alignItems="center">
<Text>{t('amount')}</Text>
<Text>{price}HCC</Text>
</Flex>
</div>
<Button disabled={time > new Date().getTime() || !price} onClick={getPrice}>
{t('Get')}
</Button>
</Flex>
</FCard>
)
}
export default ExchangeCard

View File

@ -0,0 +1,40 @@
import React from 'react'
import dayjs from 'dayjs'
import styled from 'styled-components'
import { useTranslation } from 'contexts/Localization'
import { Text } from '@pancakeswap/uikit'
const TimeText = styled(Text)`
color: #7a6eaa;
font-size: 22px;
`
interface RoundDetailProps {
beginTime?: number
endTime?: number
price?: number
remaining?: number
token?: string
total?: number
}
interface Props {
status?: string
roundDetail?: RoundDetailProps
}
const HeaderStatus: React.FC<Props> = ({ status, roundDetail }) => {
const { t } = useTranslation()
return (
<TimeText>
{status === 'none' && t('Change the end')}
{status === 'proceed' &&
`${dayjs(roundDetail?.beginTime).format('YYYY-MM-DD HH:mm:ss')} ~ ${dayjs(roundDetail?.endTime).format(
'YYYY-MM-DD HH:mm:ss',
)}`}
{status === 'end' &&
`${t('Opening time of next exchange period:')}${dayjs(roundDetail?.beginTime).format('YYYY-MM-DD HH:mm:ss')}`}
</TimeText>
)
}
export default HeaderStatus

View File

@ -22,16 +22,23 @@ const CoinText = styled(Text)`
interface InputProps { interface InputProps {
name: string name: string
value?: number | string value?: number | string
isDisabled?: boolean
onChange: (e: React.FormEvent<HTMLInputElement>) => void onChange: (e: React.FormEvent<HTMLInputElement>) => void
} }
const ExchangeInput: React.FC<InputProps> = ({ name, value, onChange }) => { const ExchangeInput: React.FC<InputProps> = ({ name, value, onChange, isDisabled = true }) => {
const { t } = useTranslation() const { t } = useTranslation()
return ( return (
<PriceContent> <PriceContent>
<CoinText>{name}</CoinText> <CoinText>{name}</CoinText>
<Input value={value} placeholder={t('Please enter the amount')} onChange={onChange} type="number" /> <Input
value={value}
placeholder={t('Please enter the amount')}
onChange={onChange}
type="number"
disabled={isDisabled}
/>
</PriceContent> </PriceContent>
) )
} }

View File

@ -1,20 +1,23 @@
import React, { useMemo, useState, useEffect, useCallback } from 'react' import React, { useState, useEffect } from 'react'
import styled, { keyframes } from 'styled-components' import dayjs from 'dayjs'
import styled from 'styled-components'
import { useTranslation } from 'contexts/Localization' import { useTranslation } from 'contexts/Localization'
import { Flex, Text, Button, Input } from '@pancakeswap/uikit' import { Text, Button, useModal } from '@pancakeswap/uikit'
import { getAddress, getIdoPurchaseAddress } from 'utils/addressHelpers' import { getAddress } from 'utils/addressHelpers'
import { getPurchaseActivity } from 'services/idoPurchase' import { getPurchaseActivity } from 'services/idoPurchase'
// import { useIdoPurchase } from 'hooks/useContract'
import { fetchIdoUserAllowances } from 'state/ido' import { fetchIdoUserAllowances } from 'state/ido'
import multicall from 'utils/multicall' import { useERC20 } from 'hooks/useContract'
import { useERC20, useIdoPurchase } from 'hooks/useContract' import useToast from 'hooks/useToast'
import idoPurchaseABI from 'config/abi/idoPurchase.json'
import tokens from 'config/constants/tokens' import tokens from 'config/constants/tokens'
import { useAccount } from 'state/userInfo/hooks' import { useAccount } from 'state/userInfo/hooks'
import UnlockButton from 'components/UnlockButton' import UnlockButton from 'components/UnlockButton'
import ExchangeInput from './IdoInput' import ExchangeInput from './IdoInput'
import { useApproveIdo, useBuyTransaction } from '../hooks' import HeaderStatus from './HeaderStatus'
import RateText from './RateText'
import BuyModal from './BuyModal'
import { useApproveIdo, useBuyTransaction, useCheckTokenBalance } from '../hooks'
const FCard = styled.div` const FCard = styled.div`
width: 650px; width: 650px;
@ -26,24 +29,19 @@ const FCard = styled.div`
position: relative; position: relative;
text-align: center; text-align: center;
padding: 50px 70px; padding: 50px 70px;
${({ theme }) => theme.mediaQueries.xs} {
width: 350px;
padding: 20px 30px;
}
${({ theme }) => theme.mediaQueries.lg} {
width: 650px;
padding: 50px 70px;
}
` `
const HeaderText = styled(Text)` const HeaderText = styled(Text)`
font-size: 48px; font-size: 48px;
color: #280d5f; color: #280d5f;
` `
const TimeText = styled(Text)`
color: #7a6eaa;
font-size: 22px;
`
const RateText = styled(Text)`
font-size: 30px;
color: #280d5f;
`
const RateNumber = styled(Text)`
font-size: 30px;
color: #1fc7d4;
`
const FooterButton = styled.div` const FooterButton = styled.div`
margin-top: 50px; margin-top: 50px;
width: 100%; width: 100%;
@ -51,36 +49,55 @@ const FooterButton = styled.div`
const UnlockButtonDiv = styled(UnlockButton)` const UnlockButtonDiv = styled(UnlockButton)`
width: 100%; width: 100%;
` `
interface DetailProps {
id?: string
name?: string
beginTime?: string
endTime?: string
}
interface RoundDetailProps {
beginTime?: number
endTime?: number
price?: number
remaining?: number
token?: string
total?: number
}
interface Props {
status?: string
roundDetail?: RoundDetailProps
time?: number
}
const ExchangeCard: React.FC = () => { const ExchangeCard: React.FC<Props> = ({ status, roundDetail, time }) => {
const { t } = useTranslation() const { t } = useTranslation()
const { toastSuccess, toastError } = useToast()
const account = useAccount() const account = useAccount()
const [allowanceList, setAllowanceList] = useState({ usdt: 0 }) const [allowanceList, setAllowanceList] = useState({ usdt: 0 })
const [loading, setLoading] = useState(false)
const getAllowances = async () => { const getAllowances = async () => {
const allowances = await fetchIdoUserAllowances(account) const allowances = await fetchIdoUserAllowances(account)
setAllowanceList({ setAllowanceList({
usdt: allowances.usdt, usdt: allowances.usdt,
}) })
} }
const [idoInfo, setIdoInfo] = useState<DetailProps>({})
const getPurchasrInfo = async () => { const getPurchaseInfo = async () => {
const data = await getPurchaseActivity() const data = await getPurchaseActivity()
console.log(data) setIdoInfo(data)
} }
useEffect(() => { useEffect(() => {
if (account) { if (account) {
getAllowances() getAllowances()
getPurchasrInfo() getPurchaseInfo()
} }
}, [account]) }, [account])
const usdtContract = useERC20(getAddress(tokens.usdt.address)) const usdtContract = useERC20(getAddress(tokens.usdt.address))
const { onApprove: onUsdtApprove } = useApproveIdo(usdtContract) const { onApprove: onUsdtApprove } = useApproveIdo(usdtContract)
const [loading, setLoading] = useState(false)
const handleApprove = async (approve) => { const handleApprove = async (approve) => {
try { try {
setLoading(true) setLoading(true)
@ -96,69 +113,59 @@ const ExchangeCard: React.FC = () => {
const [hccPrice, setHccPrice] = useState('') const [hccPrice, setHccPrice] = useState('')
const handleUsdtChange = (e: React.FormEvent<HTMLInputElement>) => { const handleUsdtChange = (e: React.FormEvent<HTMLInputElement>) => {
const price = Number(e.currentTarget.value) * Number(hccPrice) const price = Number(e.currentTarget.value) * roundDetail?.price
console.log(price)
setUsdtPrice(e.currentTarget.value) setUsdtPrice(e.currentTarget.value)
setHccPrice(price.toString()) e.currentTarget.value ? setHccPrice(price.toString()) : setHccPrice('')
} }
const handleHccChange = (e: React.FormEvent<HTMLInputElement>) => { const handleHccChange = (e: React.FormEvent<HTMLInputElement>) => {
const price = Number(e.currentTarget.value) / roundDetail?.price
setHccPrice(e.currentTarget.value) setHccPrice(e.currentTarget.value)
e.currentTarget.value ? setUsdtPrice(price.toString()) : setUsdtPrice('')
} }
const buyTransaction = useBuyTransaction() const buyTransaction = useBuyTransaction()
const [onCheckBalance] = useCheckTokenBalance()
// 立即兑换 // 立即兑换
const immediatelyChange = async () => { const immediatelyChange = async () => {
console.log('立即兑换') try {
// "inputs": [ const enoughBalance = onCheckBalance(hccPrice)
// { "internalType": "uint256", "name": "round", "type": "uint256" }, if (enoughBalance) {
// { "internalType": "uint256", "name": "amount", "type": "uint256" } const res = await buyTransaction(hccPrice)
// ], }
// "name": "purchase", } catch (e: any) {
const params = [ toastError(e?.error?.message || e.message)
'0x8ec8610ef88cdd222d45a22dd98c55a98b979664', }
'50000000000000000000',
'0',
'1652787744',
'1525022104880209921',
'0x18e77720bdfb43fc6b0a9a9050b7001fcd8f859041bdb0986d053366238e41582ceacaaca5e8c9ac815f6cc054c7135638b38acf5cd0aeb8fe6112effe7901d81b',
]
const res = await buyTransaction()
console.log(res)
// setTxId(res.hash)
const params1 = [1, 2]
// const tx = await useIdoPurchase.purchase(...params)
// console.log(idoPurchaseABI)
// const Info = await multicall(idoPurchaseABI, [
// {
// address: getIdoPurchaseAddress(),
// name: 'purchase',
// params: params1,
// },
// ])
// console.log(Info)
} }
const [onPresentAffirm] = useModal(
<BuyModal
title="Trade in"
content={t(
'After purchase, it is expected to be available for collection in %time% time. Do you confirm the purchase',
{ time: dayjs(time).format('YYYY-MM-DD HH:mm:ss') },
)}
handSubmit={immediatelyChange}
/>,
)
return ( return (
<FCard> <FCard>
<HeaderText>{t('IDO exchange in the first phase')}</HeaderText> <HeaderText>{idoInfo?.name}</HeaderText>
<TimeText>{t('Opening time of next exchange period:')}2022.5.16 00:00</TimeText> <HeaderStatus status={status} roundDetail={roundDetail} />
<ExchangeInput name="USDT" value={usdtPrice} onChange={handleUsdtChange} /> <ExchangeInput name="USDT" value={usdtPrice} onChange={handleUsdtChange} isDisabled={status !== 'proceed'} />
<Flex alignItems="center" justifyContent="center" marginTop={20}> <RateText status={status} roundDetail={roundDetail} />
<RateText>{t('Exchange rate')}</RateText> <ExchangeInput name="HCC" value={hccPrice} onChange={handleHccChange} isDisabled={status !== 'proceed'} />
<RateNumber>1USDT=100HCC</RateNumber>
</Flex>
<Flex alignItems="center" justifyContent="center">
<Text color="textSubtle">{t('gross')}100000HCC</Text>
<Text color="textSubtle" marginLeft={20}>
{t('remaining quantity')}100000HCC
</Text>
</Flex>
<ExchangeInput name="HCC" value={hccPrice} onChange={handleHccChange} />
<FooterButton> <FooterButton>
{account ? ( {account ? (
allowanceList.usdt ? ( allowanceList.usdt ? (
<Button width="100%" onClick={immediatelyChange}> time ? (
{t('Immediately change')} <Button width="100%" onClick={onPresentAffirm} disabled={status !== 'proceed' || !hccPrice}>
</Button> {t('Immediately change')}
</Button>
) : (
<Button width="100%" onClick={immediatelyChange} disabled={status !== 'proceed' || !hccPrice}>
{t('Immediately change')}
</Button>
)
) : ( ) : (
<Button <Button
mt="8px" mt="8px"

View File

@ -0,0 +1,75 @@
import React from 'react'
import styled from 'styled-components'
import { useTranslation } from 'contexts/Localization'
import { Flex, Text } from '@pancakeswap/uikit'
const RateText = styled(Text)`
font-size: 30px;
color: #280d5f;
${({ theme }) => theme.mediaQueries.xs} {
font-size: 25px;
}
${({ theme }) => theme.mediaQueries.lg} {
font-size: 30px;
}
`
const RateNumber = styled(Text)`
font-size: 30px;
color: #1fc7d4;
${({ theme }) => theme.mediaQueries.xs} {
font-size: 25px;
}
${({ theme }) => theme.mediaQueries.lg} {
font-size: 30px;
}
`
const FlexRowCenter = styled(Flex)`
justify-content: center;
align-items: center;
`
const FlexCenter = styled(Flex)`
justify-content: center;
align-items: center;
${({ theme }) => theme.mediaQueries.xs} {
flex-direction: column;
}
${({ theme }) => theme.mediaQueries.lg} {
flex-direction: row;
}
`
interface RoundDetailProps {
beginTime?: number
endTime?: number
price?: number
remaining?: number
token?: string
total?: number
}
interface Props {
status?: string
roundDetail?: RoundDetailProps
}
const RateCom: React.FC<Props> = ({ status, roundDetail }) => {
const { t } = useTranslation()
return (
<>
<FlexRowCenter marginTop={20}>
<RateText>{t('Exchange rate')}</RateText>
<RateNumber>{status === 'none' ? '-------' : `1USDT=${roundDetail?.price}HCC`}</RateNumber>
</FlexRowCenter>
<FlexCenter>
<Text color="textSubtle">
{t('gross')}{status === 'none' ? ' -------- ' : roundDetail?.total}HCC
</Text>
<Text color="textSubtle" marginLeft={20}>
{t('remaining quantity')}{status === 'none' ? ' -------- ' : roundDetail?.remaining}HCC
</Text>
</FlexCenter>
</>
)
}
export default RateCom

View File

@ -1,7 +1,7 @@
import { useState, useCallback } from 'react' import { useCallback } from 'react'
import { useIdoPurchase, useReferralchef } from 'hooks/useContract' import { useIdoPurchase, useReferralchef } from 'hooks/useContract'
import useTokenBalance from 'hooks/useTokenBalance' import useTokenBalance from 'hooks/useTokenBalance'
import erc20ABI from 'config/abi/erc20.json' import idoPurchaseABI from 'config/abi/idoPurchase.json'
import { getAddress, getIdoPurchaseAddress } from 'utils/addressHelpers' import { getAddress, getIdoPurchaseAddress } from 'utils/addressHelpers'
import { getPurchaseActivity } from 'services/idoPurchase' import { getPurchaseActivity } from 'services/idoPurchase'
import BigNumber from 'bignumber.js' import BigNumber from 'bignumber.js'
@ -10,10 +10,27 @@ import tokensList from 'config/constants/tokens'
import useToast from 'hooks/useToast' import useToast from 'hooks/useToast'
import { useTranslation } from 'contexts/Localization' import { useTranslation } from 'contexts/Localization'
import { ethers, Contract } from 'ethers' import { ethers, Contract } from 'ethers'
import { getBalanceNumber, getDecimalAmountNumber } from 'utils/formatBalance' import { getBalanceNumber, getDecimalAmount, formatDivNumber, getDecimalAmountNumber } from 'utils/formatBalance'
import { getWithdrawRewardParams, getBuyReferralParams } from 'services/referral' // 判断余额
export const useCheckTokenBalance = () => {
const { balance: usdtTokenBalance } = useTokenBalance(getAddress(tokensList.usdt.address))
const { toastWarning } = useToast()
const { t } = useTranslation()
const onCheck = useCallback(
(usdtAmount) => {
if (getBalanceNumber(usdtTokenBalance) <= usdtAmount) {
toastWarning(t('Insufficient Balance'))
return false
}
return true
},
[usdtTokenBalance],
)
return [onCheck]
}
// 授权usdt
export const useApproveIdo = (tokenContract: Contract) => { export const useApproveIdo = (tokenContract: Contract) => {
const handleApprove = useCallback(async () => { const handleApprove = useCallback(async () => {
try { try {
@ -28,13 +45,91 @@ export const useApproveIdo = (tokenContract: Contract) => {
return { onApprove: handleApprove } return { onApprove: handleApprove }
} }
// 兑换
export const useBuyTransaction = () => { export const useBuyTransaction = () => {
const idoPurchase = useIdoPurchase() const idoPurchase = useIdoPurchase()
const transaction = async () => { const transaction = async (amount) => {
const data = await getPurchaseActivity() const data = await getPurchaseActivity()
const { id } = data const { id } = data
const params = [id, 1110000000000] const params = [id, new BigNumber(amount).times(18).toString()]
const res = await idoPurchase.purchase(...params) const res = await idoPurchase.purchaseWithLock(...params)
console.log(res)
return res
}
return transaction
}
// 获取信息
export const useGetRound = () => {
const transaction = async () => {
const data = await getPurchaseActivity()
if (!data) {
return null
}
const { id } = data
const idoPurchaseAddress = getIdoPurchaseAddress()
const calls = [
{
address: idoPurchaseAddress,
name: 'getRound',
params: [id],
},
]
const res = await multicall(idoPurchaseABI, calls)
const detail = res.map((item) => {
return {
beginTime: new BigNumber(item?.beginTime._hex).toNumber() * 1000,
endTime: new BigNumber(item?.endTime._hex).toNumber() * 1000,
price: 1 / formatDivNumber(item?.price._hex, 18),
remaining: formatDivNumber(item?.remaining._hex, 18),
token: item?.token,
total: formatDivNumber(item?.total._hex, 18),
}
})
return detail[0]
}
return transaction
}
// 获取锁仓时间
export const useLockTime = () => {
const transaction = async () => {
const idoPurchaseAddress = getIdoPurchaseAddress()
const calls = [
{
address: idoPurchaseAddress,
name: 'lockTime',
},
]
const [res] = await multicall(idoPurchaseABI, calls)
return new BigNumber(res[0]._hex).toNumber() * 1000
}
return transaction
}
// 获取领取数量
export const useUserInfo = () => {
const transaction = async (account) => {
const idoPurchaseAddress = getIdoPurchaseAddress()
const calls = [
{
address: idoPurchaseAddress,
name: 'userInfo',
params: [account],
},
]
const [res] = await multicall(idoPurchaseABI, calls)
return formatDivNumber(res.purchasedAmount._hex, 18)
}
return transaction
}
// 领取收益
export const useHarvest = () => {
const idoPurchase = useIdoPurchase()
const transaction = async () => {
const res = await idoPurchase.harvest()
console.log(res)
return res return res
} }
return transaction return transaction

View File

@ -1,6 +1,19 @@
import React, { useState, useEffect } from 'react' import React, { useState, useEffect } from 'react'
import styled from 'styled-components' import styled from 'styled-components'
import ExchangeCard from './components/IdoPurchaseCard' import { useAccount } from 'state/userInfo/hooks'
import useRefresh from 'hooks/useRefresh'
import { useLockTime, useUserInfo, useGetRound } from './hooks'
import IdoPurchaseCard from './components/IdoPurchaseCard'
import GetCard from './components/GetCard'
interface RoundDetailProps {
beginTime?: number
endTime?: number
price?: number
remaining?: number
token?: string
total?: number
}
const PageContent = styled.div` const PageContent = styled.div`
min-height: calc(100vh - 64px); min-height: calc(100vh - 64px);
@ -8,14 +21,51 @@ const PageContent = styled.div`
background-size: cover; background-size: cover;
background-repeat: no-repeat; background-repeat: no-repeat;
display: flex; display: flex;
flex-direction: column;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
` `
const Exchange: React.FC = () => { const Exchange: React.FC = () => {
const account = useAccount()
const lockTime = useLockTime()
const [time, setTime] = useState(0)
const userInfo = useUserInfo()
const [price, setPrice] = useState(0)
const [status, setStatus] = useState('none') // none proceed end
const [roundDetail, setRoundDetail] = useState<RoundDetailProps>({})
const getRound = useGetRound()
const init = async () => {
const detail = await getRound()
if (!detail) {
setStatus('none')
} else if (detail.beginTime < new Date().getTime() && detail.endTime > new Date().getTime()) {
setStatus('proceed')
} else {
setStatus('end')
}
setRoundDetail(detail)
const data = await lockTime()
setTime(data)
const info = await userInfo(account)
setPrice(info)
}
const { fastRefresh } = useRefresh()
useEffect(() => {
if (account) {
init()
}
}, [account, fastRefresh])
return ( return (
<PageContent> <PageContent>
<ExchangeCard /> <IdoPurchaseCard status={status} time={time} roundDetail={roundDetail} />
{price > 0 && <GetCard price={price} time={time} />}
</PageContent> </PageContent>
) )
} }

View File

@ -33,7 +33,6 @@ export const useBuyTransaction = () => {
const data = await getBuyReferralParams() const data = await getBuyReferralParams()
const { to, hccPrice, otherPaymentPrice, timestamp, code, sign } = data const { to, hccPrice, otherPaymentPrice, timestamp, code, sign } = data
const params = [to, hccPrice, otherPaymentPrice, timestamp, code, sign] const params = [to, hccPrice, otherPaymentPrice, timestamp, code, sign]
console.log(referralContract)
const res = await referralContract.mint(...params) const res = await referralContract.mint(...params)
return res return res
} }