Skip to content

Commit

Permalink
Merge branch 'develop' of https://github.com/nervosnetwork/neuron int…
Browse files Browse the repository at this point in the history
…o merge-develop-into-support-light-client
  • Loading branch information
Keith-CY committed May 15, 2023
2 parents 1b3d647 + 5950982 commit f527c0f
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 79 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 @@ -132,8 +131,8 @@ export const useClearGeneratedTx = (dispatch: React.Dispatch<StateAction>) =>
})
}, [dispatch])

export const useUpdateDepositValue = ({
setDepositValue,

export const useGenerateDaoDepositTx = ({
setErrorMessage,
clearGeneratedTx,
maxDepositAmount,
Expand All @@ -143,9 +142,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 @@ -155,36 +154,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 @@ -215,8 +212,7 @@ export const useUpdateDepositValue = ({
} else {
setErrorMessage(t(`messages.codes.${ErrorCode.AmountNotEnough}`))
}
}, 500)
setDepositValue(amount)
})
},
[
clearGeneratedTx,
Expand All @@ -226,12 +222,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 @@ -294,7 +309,6 @@ export const useOnDepositDialogSubmit = ({
}) =>
useCallback(() => {
setShowDepositDialog(false)
setDepositValue(`${MIN_DEPOSIT_AMOUNT}`)
dispatch({
type: AppActions.RequestPassword,
payload: {
Expand Down Expand Up @@ -602,4 +616,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 @@ -166,6 +164,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 @@ -267,27 +270,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 @@ -416,7 +398,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
@@ -1,7 +1,7 @@
import { useState, useEffect, useCallback } from 'react'
import { getFeeRateStats } from 'services/chain'
import { AppActions, StateDispatch, useDispatch } from 'states'
import { MEDIUM_FEE_RATE, METHOD_NOT_FOUND } from 'utils/const'
import { MEDIUM_FEE_RATE } from 'utils/const'

type CountdownOptions = {
seconds?: number
Expand All @@ -21,30 +21,24 @@ const useGetCountDownAndFeeRateStats = ({ seconds = 30, interval = 1000 }: Count
(stateDispatch: StateDispatch) => {
getFeeRateStats()
.then(res => {
if (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 }))
}
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) => {
try {
const errMsg = JSON.parse(err.message)
if (errMsg?.code === METHOD_NOT_FOUND) {
return
}
} catch (error) {
//ignore, show error default
.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,
},
})
}
stateDispatch({
type: AppActions.AddNotification,
payload: {
type: 'alert',
timestamp: +new Date(),
content: err.message,
},
})
})
},
[getFeeRateStats, setFeeFatestatsData]
Expand Down

1 comment on commit f527c0f

@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 4982217247

Please sign in to comment.