-
Notifications
You must be signed in to change notification settings - Fork 92
fix: Fix generate transaction when deposit all without balance. #2772
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
yanguoyu
merged 1 commit into
nervosnetwork:develop
from
yanguoyu:fix-deposit-without-left
Jul 24, 2023
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
271 changes: 271 additions & 0 deletions
271
packages/neuron-ui/src/components/DepositDialog/hooks.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,271 @@ | ||
| import { isErrorWithI18n } from 'exceptions' | ||
| import { TFunction } from 'i18next' | ||
| import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useRef, useState } from 'react' | ||
| import { useTranslation } from 'react-i18next' | ||
| import { | ||
| generateDaoDepositAllTx as generateDaoDepositAllTxAPI, | ||
| generateDaoDepositTx as generateDaoDepositTxAPI, | ||
| } from 'services/remote' | ||
| import { AppActions, useDispatch } from 'states' | ||
| import { | ||
| CKBToShannonFormatter, | ||
| ErrorCode, | ||
| ResponseCode, | ||
| isSuccessResponse, | ||
| padFractionDigitsIfDecimal, | ||
| shannonToCKBFormatter, | ||
| useClearGeneratedTx, | ||
| validateAmount, | ||
| } from 'utils' | ||
| import { MAX_DECIMAL_DIGITS, MIN_DEPOSIT_AMOUNT, SHANNON_CKB_RATIO } from 'utils/const' | ||
|
|
||
| const PERCENT_100 = 100 | ||
|
|
||
| function checkDepositValue(depositValue: string, t: TFunction): string | undefined { | ||
| try { | ||
| validateAmount(depositValue) | ||
| } catch (err) { | ||
| if (isErrorWithI18n(err)) { | ||
| return t(`messages.codes.${err.code}`, { | ||
| fieldName: 'deposit', | ||
| fieldValue: depositValue, | ||
| length: MAX_DECIMAL_DIGITS, | ||
| }) | ||
| } | ||
| return undefined | ||
| } | ||
| if (BigInt(CKBToShannonFormatter(depositValue)) < BigInt(MIN_DEPOSIT_AMOUNT * SHANNON_CKB_RATIO)) { | ||
| return t('nervos-dao.minimal-fee-required', { minimal: MIN_DEPOSIT_AMOUNT }) | ||
| } | ||
| return undefined | ||
| } | ||
|
|
||
| function generateDaoDepositTx({ | ||
| walletID, | ||
| capacity, | ||
| suggestFeeRate, | ||
| t, | ||
| }: { | ||
| walletID: string | ||
| capacity: string | ||
| suggestFeeRate: number | ||
| t: TFunction | ||
| }): Promise<State.GeneratedTx | null> { | ||
| return generateDaoDepositTxAPI({ | ||
| feeRate: `${suggestFeeRate}`, | ||
| capacity, | ||
| walletID, | ||
| }).then(res => { | ||
| if (isSuccessResponse(res)) { | ||
| return res.result | ||
| } | ||
| if (res.status === ResponseCode.FAILURE) { | ||
| throw new Error(`${typeof res.message === 'string' ? res.message : res.message.content}`) | ||
| } else if (res.status === ErrorCode.CapacityNotEnoughForChange) { | ||
| throw new Error(t(`messages.codes.106`)) | ||
| } else { | ||
| throw new Error(t(`messages.codes.${res.status}`)) | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| function generateDaoDepositAllTx({ | ||
| suggestFeeRate, | ||
| isBalanceReserved, | ||
| walletID, | ||
| }: { | ||
| suggestFeeRate: number | ||
| isBalanceReserved: boolean | ||
| walletID: string | ||
| }): Promise<State.GeneratedTx | null> { | ||
| return generateDaoDepositAllTxAPI({ | ||
| walletID, | ||
| feeRate: `${suggestFeeRate}`, | ||
| isBalanceReserved, | ||
| }).then(res => { | ||
| if (isSuccessResponse(res)) { | ||
| return res.result | ||
| } | ||
| throw new Error(`${typeof res.message === 'string' ? res.message : res.message.content}`) | ||
| }) | ||
| } | ||
|
|
||
| export const useGenerateDaoDepositTx = ({ | ||
| walletID, | ||
| isBalanceReserved, | ||
| depositValue, | ||
| suggestFeeRate, | ||
| showDepositDialog, | ||
| slidePercent, | ||
| }: { | ||
| walletID: string | ||
| isBalanceReserved: boolean | ||
| depositValue: string | ||
| suggestFeeRate: number | ||
| showDepositDialog: boolean | ||
| slidePercent: number | ||
| }) => { | ||
| const timer = useRef<ReturnType<typeof setTimeout>>() | ||
| const [errorMessage, setErrorMessage] = useState('') | ||
| const [maxDepositValue, setMaxDepositValue] = useState<string | undefined>() | ||
| const [t] = useTranslation() | ||
| const dispatch = useDispatch() | ||
| const clearGeneratedTx = useClearGeneratedTx() | ||
| const isDepositAll = useMemo(() => slidePercent === PERCENT_100, [slidePercent]) | ||
| useEffect(() => { | ||
| clearTimeout(timer.current) | ||
| if (!showDepositDialog) { | ||
| return | ||
| } | ||
| timer.current = setTimeout(() => { | ||
| setErrorMessage('') | ||
| const errorDepositValue = checkDepositValue(depositValue, t) | ||
| if (errorDepositValue) { | ||
| clearGeneratedTx() | ||
| setErrorMessage(errorDepositValue) | ||
| return | ||
| } | ||
|
|
||
| const generateDaoDepositResult: Promise<State.GeneratedTx | null> = isDepositAll | ||
| ? generateDaoDepositAllTx({ walletID, isBalanceReserved, suggestFeeRate }) | ||
| : generateDaoDepositTx({ walletID, capacity: CKBToShannonFormatter(depositValue), suggestFeeRate, t }) | ||
| generateDaoDepositResult | ||
| .then(res => { | ||
| dispatch({ | ||
| type: AppActions.UpdateGeneratedTx, | ||
| payload: res, | ||
| }) | ||
| if (isDepositAll) { | ||
| setMaxDepositValue(shannonToCKBFormatter(res?.outputs[0]?.capacity ?? '0', false, '')) | ||
| if (!isBalanceReserved) { | ||
| setErrorMessage(t('messages.remain-ckb-for-withdraw')) | ||
| } | ||
| } | ||
| }) | ||
| .catch((err: unknown) => { | ||
| clearGeneratedTx() | ||
| setErrorMessage(err instanceof Error ? err.message : '') | ||
| }) | ||
| }) | ||
| }, [ | ||
| clearGeneratedTx, | ||
| dispatch, | ||
| walletID, | ||
| t, | ||
| setErrorMessage, | ||
| isBalanceReserved, | ||
| depositValue, | ||
| suggestFeeRate, | ||
| showDepositDialog, | ||
| isDepositAll, | ||
| ]) | ||
| return { | ||
| errorMessage, | ||
| maxDepositValue: isDepositAll ? maxDepositValue ?? depositValue : null, | ||
| } | ||
| } | ||
|
|
||
| function calculatePercent(amount: string, total: string) { | ||
| if (!total || total === '0') return 0 | ||
| return +((BigInt(PERCENT_100) * BigInt(amount)) / BigInt(total)).toString() | ||
| } | ||
|
|
||
| export const useDepositValue = (balance: string) => { | ||
| const [depositValue, setDepositValue] = useState(`${MIN_DEPOSIT_AMOUNT}`) | ||
| const [slidePercent, setSlidePercent] = useState( | ||
| calculatePercent(CKBToShannonFormatter(`${MIN_DEPOSIT_AMOUNT}`), balance) | ||
| ) | ||
| const onSliderChange = useCallback( | ||
| (percent: number) => { | ||
| setSlidePercent(percent) | ||
| const amount = shannonToCKBFormatter( | ||
| ((BigInt(percent) * BigInt(balance)) / BigInt(PERCENT_100)).toString(), | ||
| false, | ||
| '' | ||
| ) | ||
| setDepositValue(padFractionDigitsIfDecimal(amount, 8)) | ||
| }, | ||
| [balance] | ||
| ) | ||
| const onChangeDepositValue = useCallback( | ||
| (e: React.SyntheticEvent<HTMLInputElement>) => { | ||
| const { value } = e.currentTarget | ||
| const amount = value.replace(/,/g, '') | ||
| if (Number.isNaN(+amount) || /[^\d.]/.test(amount) || +amount < 0) { | ||
| return | ||
| } | ||
| setDepositValue(amount) | ||
| try { | ||
| validateAmount(amount) | ||
| const percent = calculatePercent(CKBToShannonFormatter(amount), balance) | ||
| setSlidePercent(percent >= PERCENT_100 ? 100 : percent) | ||
| } catch (error) { | ||
| // here we can ignore the error, it used to verify amount and set slide percent | ||
| } | ||
| }, | ||
| [setDepositValue, balance] | ||
| ) | ||
| const resetDepositValue = useCallback(() => { | ||
| setDepositValue(`${MIN_DEPOSIT_AMOUNT}`) | ||
| setSlidePercent(calculatePercent(CKBToShannonFormatter(`${MIN_DEPOSIT_AMOUNT}`), balance)) | ||
| }, [balance]) | ||
| return { | ||
| onChangeDepositValue, | ||
| setDepositValue, | ||
| depositValue, | ||
| slidePercent, | ||
| onSliderChange, | ||
| resetDepositValue, | ||
| } | ||
| } | ||
|
|
||
| export const useBalanceReserved = () => { | ||
| const [isBalanceReserved, setIsBalanceReserved] = useState(true) | ||
| const onIsBalanceReservedChange = (e: React.SyntheticEvent<HTMLInputElement>) => { | ||
| setIsBalanceReserved(!e.currentTarget.checked) | ||
| } | ||
| return { | ||
| isBalanceReserved, | ||
| onIsBalanceReservedChange, | ||
| setIsBalanceReserved, | ||
| } | ||
| } | ||
|
|
||
| export const useOnDepositDialogSubmit = ({ | ||
| onCloseDepositDialog, | ||
| walletID, | ||
| }: { | ||
| onCloseDepositDialog: () => void | ||
| walletID: string | ||
| }) => { | ||
| const dispatch = useDispatch() | ||
| return useCallback(() => { | ||
| dispatch({ | ||
| type: AppActions.RequestPassword, | ||
| payload: { | ||
| walletID, | ||
| actionType: 'send', | ||
| }, | ||
| }) | ||
| onCloseDepositDialog() | ||
| }, [dispatch, walletID, onCloseDepositDialog]) | ||
| } | ||
|
|
||
| export const useOnDepositDialogCancel = ({ | ||
| onCloseDepositDialog, | ||
| resetDepositValue, | ||
| setIsBalanceReserved, | ||
| }: { | ||
| onCloseDepositDialog: () => void | ||
| resetDepositValue: () => void | ||
| setIsBalanceReserved: Dispatch<SetStateAction<boolean>> | ||
| }) => { | ||
| const dispatch = useDispatch() | ||
| const clearGeneratedTx = useClearGeneratedTx() | ||
| return useCallback(() => { | ||
| onCloseDepositDialog() | ||
| resetDepositValue() | ||
| setIsBalanceReserved(true) | ||
| clearGeneratedTx() | ||
| }, [dispatch, onCloseDepositDialog, resetDepositValue, clearGeneratedTx]) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.