Skip to content

Commit

Permalink
fix: Fix deposit dao (#2663)
Browse files Browse the repository at this point in the history
* fix: Fix deposite dao

1. When refreshing in DAO page, the network is not ready, so ignore 404.
2. Reset deposited DAO capacity when opening dialog.
3. Create a common `generateDaoDepositTx` hook to create a deposit tx whether `despositeValue` change or `suggestFeeRate` change

* fix: Fix type error

* fix: Fix typo
  • Loading branch information
yanguoyu authored May 15, 2023
1 parent df6bf91 commit 5950982
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 66 deletions.
67 changes: 41 additions & 26 deletions packages/neuron-ui/src/components/NervosDAO/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useCallback } from 'react'
import { useEffect, useCallback, useRef } from 'react'
import { TFunction } from 'i18next'
import { AppActions, StateAction } from 'states/stateProvider/reducer'
import { updateNervosDaoData, clearNervosDaoData } from 'states/stateProvider/actionCreators'
Expand Down Expand Up @@ -32,7 +32,6 @@ const {
SHANNON_CKB_RATIO,
MAX_DECIMAL_DIGITS,
} = CONSTANTS
let timer: NodeJS.Timeout

const getRecordKey = ({ depositOutPoint, outPoint }: State.NervosDAORecord) => {
return depositOutPoint ? `${depositOutPoint.txHash}-${depositOutPoint.index}` : `${outPoint.txHash}-${outPoint.index}`
Expand Down Expand Up @@ -128,8 +127,8 @@ export const useClearGeneratedTx = (dispatch: React.Dispatch<StateAction>) =>
})
}, [dispatch])

export const useUpdateDepositValue = ({
setDepositValue,

export const useGenerateDaoDepositTx = ({
setErrorMessage,
clearGeneratedTx,
maxDepositAmount,
Expand All @@ -139,9 +138,9 @@ export const useUpdateDepositValue = ({
maxDepositErrorMessage,
isBalanceReserved,
t,
depositValue,
suggestFeeRate,
}: {
setDepositValue: React.Dispatch<React.SetStateAction<string>>
setErrorMessage: React.Dispatch<React.SetStateAction<string>>
clearGeneratedTx: () => void
maxDepositAmount: bigint
Expand All @@ -151,36 +150,34 @@ export const useUpdateDepositValue = ({
maxDepositErrorMessage: string
isBalanceReserved: boolean
t: TFunction
suggestFeeRate: number | string
}) =>
useCallback(
(value: string) => {
const amount = value.replace(/,/g, '')
if (Number.isNaN(+amount) || /[^\d.]/.test(amount) || +amount < 0) {
return
}
clearTimeout(timer)
timer = setTimeout(() => {
depositValue: string
suggestFeeRate: string | number
}) => {
const timer = useRef<ReturnType<typeof setTimeout>>()
useEffect(
() => {
clearTimeout(timer.current)
timer.current = setTimeout(() => {
setErrorMessage('')
clearGeneratedTx()

try {
validateAmount(amount)
validateAmount(depositValue)
} catch (err) {
if (isErrorWithI18n(err)) {
setErrorMessage(
t(`messages.codes.${err.code}`, { fieldName: 'deposit', fieldValue: amount, length: MAX_DECIMAL_DIGITS })
t(`messages.codes.${err.code}`, { fieldName: 'deposit', fieldValue: depositValue, length: MAX_DECIMAL_DIGITS })
)
}
return
}

if (BigInt(CKBToShannonFormatter(amount)) < BigInt(MIN_DEPOSIT_AMOUNT * SHANNON_CKB_RATIO)) {
if (BigInt(CKBToShannonFormatter(depositValue)) < BigInt(MIN_DEPOSIT_AMOUNT * SHANNON_CKB_RATIO)) {
setErrorMessage(t('nervos-dao.minimal-fee-required', { minimal: MIN_DEPOSIT_AMOUNT }))
return
}

const capacity = CKBToShannonFormatter(amount, CapacityUnit.CKB)
const capacity = CKBToShannonFormatter(depositValue, CapacityUnit.CKB)
if (BigInt(capacity) < maxDepositAmount) {
generateDaoDepositTx({
feeRate: `${suggestFeeRate}`,
Expand Down Expand Up @@ -211,8 +208,7 @@ export const useUpdateDepositValue = ({
} else {
setErrorMessage(t(`messages.codes.${ErrorCode.AmountNotEnough}`))
}
}, 500)
setDepositValue(amount)
})
},
[
clearGeneratedTx,
Expand All @@ -222,12 +218,31 @@ export const useUpdateDepositValue = ({
walletID,
maxDepositErrorMessage,
t,
setDepositValue,
setErrorMessage,
isBalanceReserved,
depositValue,
suggestFeeRate,
]
)
}

export const useUpdateDepositValue = ({
setDepositValue,
}: {
setDepositValue: React.Dispatch<React.SetStateAction<string>>
}) =>
useCallback(
(value: string) => {
const amount = value.replace(/,/g, '')
if (Number.isNaN(+amount) || /[^\d.]/.test(amount) || +amount < 0) {
return
}
setDepositValue(amount)
},
[
setDepositValue,
]
)

export const useOnDepositValueChange = ({ updateDepositValue }: { updateDepositValue: (value: string) => void }) =>
useCallback(
Expand Down Expand Up @@ -290,7 +305,6 @@ export const useOnDepositDialogSubmit = ({
}) =>
useCallback(() => {
setShowDepositDialog(false)
setDepositValue(`${MIN_DEPOSIT_AMOUNT}`)
dispatch({
type: AppActions.RequestPassword,
payload: {
Expand Down Expand Up @@ -576,4 +590,5 @@ export default {
useOnSlide,
useUpdateWithdrawList,
useUpdateDepositEpochList,
useGenerateDaoDepositTx,
}
42 changes: 12 additions & 30 deletions packages/neuron-ui/src/components/NervosDAO/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useState, useMemo, useCallback } from 'react'
import { useState as useGlobalState, useDispatch, AppActions } from 'states'
import { useState as useGlobalState, useDispatch } from 'states'
import { useTranslation } from 'react-i18next'
import { ReactComponent as TooltipIcon } from 'widgets/Icons/Tooltip.svg'

Expand All @@ -15,12 +15,9 @@ import {
getCurrentUrl,
getSyncStatus,
CKBToShannonFormatter,
ErrorCode,
CapacityUnit,
isSuccessResponse,
} from 'utils'

import { generateDaoDepositTx, openExternal } from 'services/remote'
import { openExternal } from 'services/remote'

import DepositDialog from 'components/DepositDialog'
import WithdrawDialog from 'components/WithdrawDialog'
Expand Down Expand Up @@ -73,8 +70,7 @@ const NervosDAO = () => {
const [depositEpochList, setDepositEpochList] = useState<Map<string, string | null>>(new Map())
const [isBalanceReserved, setIsBalanceReserved] = useState(true)
const clearGeneratedTx = hooks.useClearGeneratedTx(dispatch)
const updateDepositValue = hooks.useUpdateDepositValue({
setDepositValue,
hooks.useGenerateDaoDepositTx({
setErrorMessage,
clearGeneratedTx,
maxDepositAmount,
Expand All @@ -84,8 +80,10 @@ const NervosDAO = () => {
maxDepositErrorMessage,
isBalanceReserved,
t,
suggestFeeRate,
depositValue,
suggestFeeRate
})
const updateDepositValue = hooks.useUpdateDepositValue({ setDepositValue })

const onDepositValueChange = hooks.useOnDepositValueChange({ updateDepositValue })
const onDepositDialogDismiss = hooks.useOnDepositDialogDismiss({
Expand Down Expand Up @@ -158,6 +156,11 @@ const NervosDAO = () => {
url: getCurrentUrl(networkID, networks),
})

const onOpenDepositDialog = useCallback(() => {
setDepositValue(`${MIN_DEPOSIT_AMOUNT}`)
setShowDepositDialog(true)
}, [])

const MemoizedRecords = useMemo(() => {
const onTabClick = (e: React.SyntheticEvent<HTMLDivElement, MouseEvent>) => {
const {
Expand Down Expand Up @@ -258,27 +261,6 @@ const NervosDAO = () => {
}
}, [maxDepositAmount, depositValue, setDepositValue])

useEffect(() => {
generateDaoDepositTx({
feeRate: `${suggestFeeRate}`,
capacity: CKBToShannonFormatter(depositValue, CapacityUnit.CKB),
walletID: wallet.id,
}).then(res => {
if (isSuccessResponse(res)) {
dispatch({
type: AppActions.UpdateGeneratedTx,
payload: res.result,
})
} else if (res.status === 0) {
setErrorMessage(`${typeof res.message === 'string' ? res.message : res.message.content}`)
} else if (res.status === ErrorCode.CapacityNotEnoughForChange) {
setErrorMessage(t(`messages.codes.106`))
} else {
setErrorMessage(t(`messages.codes.${res.status}`))
}
})
}, [suggestFeeRate, depositValue])

const MemoizedDepositDialog = useMemo(() => {
return (
<DepositDialog
Expand Down Expand Up @@ -407,7 +389,7 @@ const NervosDAO = () => {
<Button
type="primary"
disabled={connectionStatus === 'offline' || sending || !maxDepositTx}
onClick={() => setShowDepositDialog(true)}
onClick={onOpenDepositDialog}
label={t('nervos-dao.deposit')}
/>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,24 @@ const useGetCountDownAndFeeRateStats = ({ seconds = 30, interval = 1000 }: Count
(stateDispatch: StateDispatch) => {
getFeeRateStats()
.then(res => {
const { mean, median } = res
const { mean, median } = res ?? {}
const suggested = mean && median ? Math.max(1000, Number(mean), Number(median)) : MEDIUM_FEE_RATE

setFeeFatestatsData(states => ({ ...states, ...res, suggestFeeRate: suggested }))
})
.catch((err: Error) => {
stateDispatch({
type: AppActions.AddNotification,
payload: {
type: 'alert',
timestamp: +new Date(),
content: err.message,
},
})
.catch((err: Error & { response?: { status: number } }) => {
if (err?.response?.status === 404) {
setFeeFatestatsData(states => ({ ...states, suggestFeeRate: MEDIUM_FEE_RATE }))
} else {
stateDispatch({
type: AppActions.AddNotification,
payload: {
type: 'alert',
timestamp: +new Date(),
content: err.message,
},
})
}
})
},
[getFeeRateStats, setFeeFatestatsData]
Expand Down

1 comment on commit 5950982

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Packaging for test is done in 4981204484

Please sign in to comment.