Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 39 additions & 5 deletions packages/neuron-ui/src/components/CustomRows/DAORecordRow.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React, { useEffect, useState } from 'react'
import React, { useEffect, useState, useMemo } from 'react'
import { DefaultButton } from 'office-ui-fabric-react'
import { useTranslation } from 'react-i18next'
import { ckbCore, getBlockByNumber } from 'services/chain'
import { showMessage } from 'services/remote'
import calculateAPY from 'utils/calculateAPY'
import { shannonToCKBFormatter, uniformTimeFormatter, localNumberFormatter } from 'utils/formatters'
import calculateClaimEpochNumber from 'utils/calculateClaimEpochNumber'
Expand All @@ -21,19 +22,28 @@ const DAORecord = ({
depositOutPoint,
epoch,
withdraw,
connectionStatus,
}: State.NervosDAORecord & {
actionLabel: string
onClick: any
tipBlockNumber: string
epoch: string
withdraw: string | null
connectionStatus: 'online' | 'offline'
}) => {
const [t] = useTranslation()
const [withdrawingEpoch, setWithdrawingEpoch] = useState('')
const [depositEpoch, setDepositEpoch] = useState('')

useEffect(() => {
if (!depositOutPoint) {
getBlockByNumber(BigInt(blockNumber))
.then(b => {
setDepositEpoch(b.header.epoch)
})
.catch((err: Error) => {
console.error(err)
})
return
}
const depositBlockNumber = ckbCore.utils.bytesToHex(ckbCore.utils.hexToBytes(daoData).reverse())
Expand Down Expand Up @@ -81,18 +91,42 @@ const DAORecord = ({
}
}

const onActionClick = useMemo(() => {
const currentEpochInfo = epochParser(epoch)
const thresholdEpoch = withdrawingEpoch || depositEpoch
if (thresholdEpoch) {
const thresholdEpochInfo = epochParser(thresholdEpoch)
if (thresholdEpochInfo.number + BigInt(4) >= currentEpochInfo.number) {
return () =>
showMessage(
{
title: t('nervos-dao.insufficient-period-alert-title'),
message: t('nervos-dao.insufficient-period-alert-title'),
detail: t('nervos-dao.insufficient-period-alert-message'),
},
() => {}
)
}
}
return onClick
}, [onClick, epoch, depositEpoch, withdrawingEpoch, t])

return (
<div className={styles.daoRecord}>
<div className={`${styles.daoRecord} ${depositOutPoint ? styles.isClaim : ''}`}>
<div className={styles.primaryInfo}>
<div>{interest >= BigInt(0) ? `${shannonToCKBFormatter(interest.toString()).toString()} CKB` : ''}</div>
<div>
{interest >= BigInt(0)
? `${depositOutPoint ? '' : '~'}${shannonToCKBFormatter(interest.toString()).toString()} CKB`
: ''}
</div>
<div>{`${shannonToCKBFormatter(capacity)} CKB`}</div>
<div>
<DefaultButton
text={actionLabel}
data-tx-hash={txHash}
data-index={index}
onClick={onClick}
disabled={depositOutPoint && !ready}
onClick={onActionClick}
disabled={connectionStatus === 'offline' || (depositOutPoint && !ready)}
styles={{
flexContainer: {
pointerEvents: 'none',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
display: flex;
flex-direction: column;
border: 1px solid #000;
border-radius: 5px;
border-radius: 2px;
margin: 10px 0;
padding: 5px 15px;
border-left: 5px solid green;

.primaryInfo,
.secondaryInfo {
Expand Down Expand Up @@ -32,4 +33,7 @@
color: #666;
}

&.isClaim {
border-left-color: blue;
}
}
27 changes: 21 additions & 6 deletions packages/neuron-ui/src/components/NervosDAO/WithdrawDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react'
import { Dialog, DialogFooter, DefaultButton, PrimaryButton, DialogType } from 'office-ui-fabric-react'
import { Dialog, DialogFooter, DefaultButton, PrimaryButton, DialogType, Text } from 'office-ui-fabric-react'
import { useTranslation } from 'react-i18next'
import { shannonToCKBFormatter, localNumberFormatter } from 'utils/formatters'
import { ckbCore } from 'services/chain'
Expand Down Expand Up @@ -65,6 +65,16 @@ const WithdrawDialog = ({
blocks: localNumberFormatter(currentEpochInfo.length - currentEpochInfo.index),
days: localNumberFormatter(epochs / BigInt(6)),
})

const alert =
epochs <= BigInt(5)
? t('nervos-dao.withdraw-alert', {
epochs,
nextLeftEpochs: epochs + BigInt(180),
days: (epochs + BigInt(180)) / BigInt(6),
})
: ''

return (
<Dialog
hidden={!record}
Expand All @@ -77,20 +87,25 @@ const WithdrawDialog = ({
>
{record ? (
<>
<div>
<Text as="p" variant="large" block>
<span>{`${t('nervos-dao.deposit')}: `}</span>
<span>{`${shannonToCKBFormatter(record.capacity)} CKB`}</span>
</div>
<div>
</Text>
<Text as="p" variant="large" block>
<span>{`${t('nervos-dao.interest')}: `}</span>
<span>
{withdrawValue
? `${shannonToCKBFormatter((BigInt(withdrawValue) - BigInt(record.capacity)).toString())} CKB`
: ''}
</span>
</div>
</Text>
<div>
<span>{message}</span>
<Text as="p" variant="medium" block>
{message}
</Text>
<Text as="p" variant="xSmall" block styles={{ root: { color: 'red' } }}>
{alert}
</Text>
</div>
</>
) : null}
Expand Down
65 changes: 48 additions & 17 deletions packages/neuron-ui/src/components/NervosDAO/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const NervosDAO = ({
wallet,
dispatch,
nervosDAO: { records },
chain: { connectionStatus },
}: React.PropsWithoutRef<StateWithDispatch & RouteComponentProps>) => {
const [t] = useTranslation()
const [depositValue, setDepositValue] = useState(`${MIN_DEPOSIT_AMOUNT}`)
Expand Down Expand Up @@ -116,19 +117,11 @@ const NervosDAO = ({
const onWithdrawDialogSubmit = () => {
setErrorMessage('')
if (activeRecord) {
;(activeRecord.depositOutPoint
? generateClaimTx({
walletID: wallet.id,
withdrawingOutPoint: activeRecord.outPoint,
depositOutPoint: activeRecord.depositOutPoint,
feeRate: `${MEDIUM_FEE_RATE}`,
})
: generateWithdrawTx({
walletID: wallet.id,
outPoint: activeRecord.outPoint,
feeRate: `${MEDIUM_FEE_RATE}`,
})
)
generateWithdrawTx({
walletID: wallet.id,
outPoint: activeRecord.outPoint,
feeRate: `${MEDIUM_FEE_RATE}`,
})
.then((res: any) => {
if (res.status === 1) {
dispatch({
Expand Down Expand Up @@ -170,10 +163,47 @@ const NervosDAO = ({
}
const record = records.find(r => r.outPoint.txHash === outPoint.txHash && r.outPoint.index === outPoint.index)
if (record) {
setActiveRecord(record)
if (record.depositOutPoint) {
generateClaimTx({
walletID: wallet.id,
withdrawingOutPoint: record.outPoint,
depositOutPoint: record.depositOutPoint,
feeRate: `${MEDIUM_FEE_RATE}`,
})
.then((res: any) => {
if (res.status === 1) {
dispatch({
type: AppActions.UpdateGeneratedTx,
payload: res.result,
})
dispatch({
type: AppActions.RequestPassword,
payload: {
walletID: wallet.id,
actionType: 'send',
},
})
} else {
clearGeneratedTx()
setErrorMessage(`${typeof res.message === 'string' ? res.message : res.message.content}`)
}
})
.catch((err: Error) => {
dispatch({
type: AppActions.AddNotification,
payload: {
type: 'alert',
timestamp: +new Date(),
content: err.message,
},
})
})
} else {
setActiveRecord(record)
}
}
},
[records]
[records, clearGeneratedTx, dispatch, wallet.id]
)

const fee = `${shannonToCKBFormatter(
Expand Down Expand Up @@ -226,13 +256,14 @@ const NervosDAO = ({
onClick={onActionClick}
tipBlockNumber={tipBlockNumber}
epoch={epoch}
connectionStatus={connectionStatus}
/>
)
})}
</Stack>
</>
)
}, [records, withdrawList, t, onActionClick, tipBlockNumber, epoch])
}, [records, withdrawList, t, onActionClick, tipBlockNumber, epoch, connectionStatus])

const free = BigInt(wallet.balance)
const locked = withdrawList.reduce((acc, w) => acc + BigInt(w || 0), BigInt(0))
Expand Down Expand Up @@ -271,7 +302,7 @@ const NervosDAO = ({
<Stack horizontal verticalAlign="center" tokens={{ childrenGap: 15 }}>
<DefaultButton
text={t('nervos-dao.deposit')}
disabled={sending}
disabled={connectionStatus === 'offline' || sending}
onClick={() => setShowDepositDialog(true)}
/>
<TooltipHost
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-ui/src/components/Send/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ const Send = ({
loadings: { sending = false },
},
wallet: { id: walletID = '', balance = '' },
chain: { connectionStatus },
dispatch,
}: React.PropsWithoutRef<StateWithDispatch & RouteComponentProps<{ address: string }>>) => {
const { t } = useTranslation()
Expand Down Expand Up @@ -234,7 +235,7 @@ const Send = ({
<PrimaryButton
type="submit"
onClick={onSubmit(walletID)}
disabled={sending || !!errorMessageUnderTotal || !send.generatedTx}
disabled={connectionStatus === 'offline' || sending || !!errorMessageUnderTotal || !send.generatedTx}
text={t('send.send')}
/>
)}
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-ui/src/components/Transaction/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ const Transaction = () => {
{ label: t('transaction.transaction-hash'), value: transaction.hash || 'none' },
{
label: t('transaction.block-number'),
value: localNumberFormatter(transaction.blockNumber) || 'none',
value: transaction.blockNumber ? localNumberFormatter(transaction.blockNumber) : 'none',
},
{
label: t('transaction.date'),
Expand Down
5 changes: 4 additions & 1 deletion packages/neuron-ui/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,10 @@
"withdrawing-action-label": "Claim",
"minimal-fee-required": "The minimum deposit capacity is {{minimal}} CKB",
"interest-accumulated": "{{blockNumber}} blocks interest accumulated",
"blocks-left": "{{epochs}} epochs {{blocks}} blocks left(~{{days}} days)"
"blocks-left": "{{epochs}} epochs {{blocks}} blocks left(~{{days}} days)",
"withdraw-alert": "Alert: these are only {{epochs}} epochs left before the next start withdrawing epoch number conforming to Nervos DAO, and it is possible that you have to do the withdraw after the next period(~{{days}}) due to the jam on CKB.",
"insufficient-period-alert-title": "Insufficient Period",
"insufficient-period-alert-message": "Nervos DAO needs at least 4 epochs to handle your request."
}
}
}
5 changes: 4 additions & 1 deletion packages/neuron-ui/src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,10 @@
"withdrawing-action-label": "Claim",
"minimal-fee-required": "存入金额应不少于 {{minimal}} CKB",
"interest-accumulated": "已累计 {{blockNumber}} 个块的利息",
"blocks-left": " 还需等待 {{epochs}} epochs {{blocks}} 个块(~{{days}} 天)"
"blocks-left": " 还需等待 {{epochs}} epochs {{blocks}} 个块(~{{days}} 天)",
"withdraw-alert": "风险提示:距离 NervosDAO 规定的最近一个允许提现 epoch 仅剩下 {{epochs}} 个 epoch,存在提现交易拥堵无法上链从而导致只能在下一个提现周期(约 {{days}} 天)的风险",
"insufficient-alert-title": "Insufficient Period",
"insufficient-alert-message": "Nervos DAO 要求您在至少 4 个 epochs 后执行此操作"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,17 @@ export const backupWallet = (params: Controller.BackupWalletParams) => (dispatch
export const updateNervosDaoData = (walletID: Controller.GetNervosDaoDataParams) => (dispatch: StateDispatch) => {
getNervosDaoData(walletID).then(res => {
if (res.status === 1) {
const withdrawList = res.result
.filter((r: State.NervosDAORecord) => !r.depositOutPoint)
.sort((r1: State.NervosDAORecord, r2: State.NervosDAORecord) => +r2.timestamp - +r1.timestamp)

const claimList = res.result
.filter((r: State.NervosDAORecord) => r.depositOutPoint)
.sort((r1: State.NervosDAORecord, r2: State.NervosDAORecord) => +r2.timestamp - +r1.timestamp)

dispatch({
type: NeuronWalletActions.UpdateNervosDaoData,
payload: { records: res.result },
payload: { records: [...claimList, ...withdrawList] },
})
} else {
addNotification(failureResToNotification(res))(dispatch)
Expand Down