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
90 changes: 58 additions & 32 deletions packages/neuron-ui/src/components/NervosDAO/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
generateDaoDepositTx,
generateDaoClaimTx,
} from 'services/remote'
import { ckbCore, getHeaderByNumber } from 'services/chain'
import { ckbCore, getHeader } from 'services/chain'
import { isErrorWithI18n } from 'exceptions'
import { calculateMaximumWithdraw } from '@nervosnetwork/ckb-sdk-utils'

Expand Down Expand Up @@ -81,12 +81,14 @@ export const useInitData = ({
updateDepositValue,
wallet,
setGenesisBlockTimestamp,
genesisBlockHash,
}: {
clearGeneratedTx: () => void
dispatch: React.Dispatch<StateAction>
updateDepositValue: (value: string) => void
wallet: State.Wallet
setGenesisBlockTimestamp: React.Dispatch<React.SetStateAction<number | undefined>>
genesisBlockHash?: string
}) =>
useEffect(() => {
updateNervosDaoData({ walletID: wallet.id })(dispatch)
Expand All @@ -100,9 +102,11 @@ export const useInitData = ({
: BigInt(0)
}`
)
getHeaderByNumber('0x0')
.then(header => setGenesisBlockTimestamp(+header.timestamp))
.catch(err => console.error(err))
if (genesisBlockHash) {
getHeader(genesisBlockHash)
.then(header => setGenesisBlockTimestamp(+header.timestamp))
.catch(err => console.error(err))
}
return () => {
clearInterval(intervalId)
clearNervosDaoData()(dispatch)
Expand Down Expand Up @@ -429,15 +433,15 @@ export const useOnSlide = ({

export const useUpdateWithdrawList = ({
records,
tipBlockHash,
tipDao,
setWithdrawList,
}: {
records: Readonly<State.NervosDAORecord[]>
tipBlockHash: string
tipDao?: string
setWithdrawList: React.Dispatch<React.SetStateAction<Map<string, string | null>>>
}) =>
useEffect(() => {
if (!tipBlockHash) {
if (!tipDao) {
setWithdrawList(new Map())
return
}
Expand All @@ -452,7 +456,6 @@ export const useUpdateWithdrawList = ({
const blockHashes = [
...(committedTx.map(v => v.txStatus.blockHash).filter(v => !!v) as string[]),
...(records.map(v => (v.depositOutPoint ? v.blockHash : null)).filter(v => !!v) as string[]),
tipBlockHash,
]
return ckbCore.rpc
.createBatchRequest<'getHeader', string[], CKBComponents.BlockHeader[]>(
Expand All @@ -473,7 +476,7 @@ export const useUpdateWithdrawList = ({
const withdrawList = new Map()
records.forEach(record => {
const key = getRecordKey(record)
const withdrawBlockHash = record.depositOutPoint ? record.blockHash : tipBlockHash
const withdrawBlockHash = record.depositOutPoint ? record.blockHash : undefined
const formattedDepositOutPoint = record.depositOutPoint
? {
txHash: record.depositOutPoint.txHash,
Expand All @@ -488,7 +491,7 @@ export const useUpdateWithdrawList = ({
return
}
const depositDAO = hashHeaderMap.get(tx.txStatus.blockHash!)
const withdrawDAO = hashHeaderMap.get(withdrawBlockHash)
const withdrawDAO = withdrawBlockHash ? hashHeaderMap.get(withdrawBlockHash) : tipDao
if (!depositDAO || !withdrawDAO) {
return
}
Expand All @@ -508,7 +511,23 @@ export const useUpdateWithdrawList = ({
.catch(() => {
setWithdrawList(new Map())
})
}, [records, tipBlockHash, setWithdrawList])
}, [records, tipDao, setWithdrawList])

const getBlockHashes = (txHashes: string[]) => {
const batchParams: ['getTransaction', string][] = txHashes.map(v => ['getTransaction', v])
return ckbCore.rpc
.createBatchRequest<'getTransaction', [string], CKBComponents.TransactionWithStatus[]>(batchParams)
.exec()
.then(res => {
return res.map((v, idx) => ({
txHash: txHashes[idx],
blockHash: v.txStatus.blockHash,
}))
})
.catch(() => {
return []
})
}

export const useUpdateDepositEpochList = ({
records,
Expand All @@ -521,28 +540,35 @@ export const useUpdateDepositEpochList = ({
}) =>
useEffect(() => {
if (connectionStatus === 'online') {
const recordKeyIdxMap = new Map<string, number>()
const batchParams: ['getHeaderByNumber', bigint][] = []
records.forEach((record, idx) => {
const depositBlockNumber = record.depositOutPoint
? ckbCore.utils.toUint64Le(record.daoData)
: record.blockNumber
if (depositBlockNumber) {
batchParams.push(['getHeaderByNumber', BigInt(depositBlockNumber)])
recordKeyIdxMap.set(getRecordKey(record), idx)
}
})
ckbCore.rpc
.createBatchRequest<'getHeaderByNumber', any, CKBComponents.BlockHeader[]>(batchParams)
.exec()
.then(res => {
const epochList = new Map()
records.forEach(record => {
const key = getRecordKey(record)
epochList.set(key, recordKeyIdxMap.get(key) ? res[recordKeyIdxMap.get(key)!]?.epoch : null)
getBlockHashes(records.map(v => v.depositOutPoint?.txHash).filter(v => !!v) as string[]).then(
depositBlockHashes => {
const recordKeyIdxMap = new Map<string, number>()
const batchParams: ['getHeader', string][] = []
records.forEach((record, idx) => {
if (!record.depositOutPoint && record.blockHash) {
batchParams.push(['getHeader', record.blockHash])
recordKeyIdxMap.set(record.outPoint.txHash, idx)
}
})
setDepositEpochList(epochList)
})
depositBlockHashes.forEach((v, idx) => {
if (v.blockHash) {
batchParams.push(['getHeader', v.blockHash])
recordKeyIdxMap.set(v.txHash, idx)
}
})
ckbCore.rpc
.createBatchRequest<'getHeader', any, CKBComponents.BlockHeader[]>(batchParams)
.exec()
.then(res => {
const epochList = new Map()
records.forEach(record => {
const key = record.depositOutPoint ? record.depositOutPoint.txHash : record.outPoint.txHash
epochList.set(key, recordKeyIdxMap.has(key) ? res[recordKeyIdxMap.get(key)!]?.epoch : null)
})
setDepositEpochList(epochList)
})
}
)
}
}, [records, setDepositEpochList, connectionStatus])

Expand Down
21 changes: 15 additions & 6 deletions packages/neuron-ui/src/components/NervosDAO/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const NervosDAO = () => {
app: {
send = appState.send,
loadings: { sending = false },
tipBlockHash,
tipDao,
tipBlockTimestamp,
epoch,
},
Expand Down Expand Up @@ -103,7 +103,15 @@ const NervosDAO = () => {
setMaxDepositErrorMessage,
isBalanceReserved,
})
hooks.useInitData({ clearGeneratedTx, dispatch, updateDepositValue, wallet, setGenesisBlockTimestamp })
const genesisBlockHash = useMemo(() => networks.find(v => v.id === networkID)?.genesisHash, [networkID, networks])
hooks.useInitData({
clearGeneratedTx,
dispatch,
updateDepositValue,
wallet,
setGenesisBlockTimestamp,
genesisBlockHash,
})
hooks.useUpdateGlobalAPC({ bestKnownBlockTimestamp, genesisBlockTimestamp, setGlobalAPC })
const onWithdrawDialogSubmit = hooks.useOnWithdrawDialogSubmit({
activeRecord,
Expand Down Expand Up @@ -138,7 +146,7 @@ const NervosDAO = () => {
)} CKB`
hooks.useUpdateWithdrawList({
records,
tipBlockHash,
tipDao,
setWithdrawList,
})

Expand Down Expand Up @@ -190,13 +198,14 @@ const NervosDAO = () => {
const key = record.depositOutPoint
? `${record.depositOutPoint.txHash}-${record.depositOutPoint.index}`
: `${record.outPoint.txHash}-${record.outPoint.index}`
const txHash = record.depositOutPoint ? record.depositOutPoint.txHash : record.outPoint.txHash

const props: DAORecordProps = {
...record,
tipBlockTimestamp,
withdrawCapacity: withdrawList.get(key) || null,
onClick: onActionClick,
depositEpoch: depositEpochList.get(key) || '',
depositEpoch: depositEpochList.get(txHash) || '',
currentEpoch: epoch,
genesisBlockTimestamp,
connectionStatus,
Expand Down Expand Up @@ -286,11 +295,11 @@ const NervosDAO = () => {
record={activeRecord}
onDismiss={onWithdrawDialogDismiss}
onSubmit={onWithdrawDialogSubmit}
tipBlockHash={tipBlockHash}
tipDao={tipDao}
currentEpoch={epoch}
/>
) : null
}, [activeRecord, onWithdrawDialogDismiss, onWithdrawDialogSubmit, tipBlockHash, epoch])
}, [activeRecord, onWithdrawDialogDismiss, onWithdrawDialogSubmit, tipDao, epoch])

const free = BigInt(wallet.balance)
const locked = records
Expand Down
12 changes: 6 additions & 6 deletions packages/neuron-ui/src/components/NervosDAORecord/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { useEffect, useCallback } from 'react'
import { getHeader } from 'services/chain'
import { showTransactionDetails } from 'services/remote'
import { getHeaderByNumber } from 'services/chain'
import { calculateAPC, CONSTANTS } from 'utils'

const { MILLISECONDS_IN_YEAR } = CONSTANTS

export const useUpdateWithdrawEpochs = ({
isWithdrawn,
blockNumber,
blockHash,
setWithdrawEpoch,
setWithdrawTimestamp,
}: {
isWithdrawn: boolean
blockNumber: CKBComponents.BlockNumber | null
blockHash: CKBComponents.BlockHeader['hash'] | null
setWithdrawEpoch: React.Dispatch<string>
setWithdrawTimestamp: React.Dispatch<string>
}) => {
useEffect(() => {
if (isWithdrawn && blockNumber) {
getHeaderByNumber(BigInt(blockNumber))
if (isWithdrawn && blockHash) {
getHeader(blockHash)
.then(header => {
setWithdrawEpoch(header.epoch)
setWithdrawTimestamp(header.timestamp)
Expand All @@ -27,7 +27,7 @@ export const useUpdateWithdrawEpochs = ({
console.error(err)
})
}
}, [isWithdrawn, blockNumber, setWithdrawEpoch, setWithdrawTimestamp])
}, [isWithdrawn, blockHash, setWithdrawEpoch, setWithdrawTimestamp])
}

export const useUpdateApc = ({
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-ui/src/components/NervosDAORecord/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export interface DAORecordProps extends State.NervosDAORecord {
}

export const DAORecord = ({
blockNumber,
blockHash,
tipBlockTimestamp,
capacity,
outPoint: { txHash, index },
Expand Down Expand Up @@ -73,7 +73,7 @@ export const DAORecord = ({
setApc,
})

hooks.useUpdateWithdrawEpochs({ isWithdrawn, blockNumber, setWithdrawEpoch, setWithdrawTimestamp })
hooks.useUpdateWithdrawEpochs({ isWithdrawn, blockHash, setWithdrawEpoch, setWithdrawTimestamp })
const onTxRecordClick = hooks.useOnTxRecordClick()

const currentEpochValue = epochParser(currentEpoch).value
Expand Down
34 changes: 20 additions & 14 deletions packages/neuron-ui/src/components/WithdrawDialog/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { useTranslation } from 'react-i18next'
import Button from 'widgets/Button'

import { CONSTANTS, shannonToCKBFormatter, localNumberFormatter, useCalculateEpochs, useDialog } from 'utils'
import { calculateDaoMaximumWithdraw, getHeader } from 'services/chain'
import { getTransaction, getHeader } from 'services/chain'

import { calculateMaximumWithdraw } from '@nervosnetwork/ckb-sdk-utils'
import styles from './withdrawDialog.module.scss'

const { WITHDRAW_EPOCHS } = CONSTANTS
Expand All @@ -13,13 +14,13 @@ const WithdrawDialog = ({
onDismiss,
onSubmit,
record,
tipBlockHash,
tipDao,
currentEpoch,
}: {
onDismiss: () => void
onSubmit: () => void
record: State.NervosDAORecord
tipBlockHash: string
tipDao?: string
currentEpoch: string
}) => {
const [t] = useTranslation()
Expand All @@ -42,24 +43,29 @@ const WithdrawDialog = ({
}, [record])

useEffect(() => {
if (!record || !tipBlockHash) {
if (!record || !tipDao) {
return
}

calculateDaoMaximumWithdraw(
{
txHash: record.outPoint.txHash,
index: `0x${BigInt(record.outPoint.index).toString(16)}`,
},
tipBlockHash
)
.then((res: string) => {
setWithdrawValue(res)
getTransaction(record.outPoint.txHash)
.then(tx => {
if (tx.txStatus.blockHash) {
getHeader(tx.txStatus.blockHash).then(header => {
setWithdrawValue(
calculateMaximumWithdraw(
tx.transaction.outputs[+record.outPoint.index],
tx.transaction.outputsData[+record.outPoint.index],
header.dao,
tipDao
)
)
})
}
})
.catch((err: Error) => {
console.error(err)
})
}, [record, tipBlockHash])
}, [record, tipDao])

const { currentEpochInfo, targetEpochValue } = useCalculateEpochs({ depositEpoch, currentEpoch })

Expand Down
12 changes: 5 additions & 7 deletions packages/neuron-ui/src/containers/Main/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
SyncState as SyncStateSubject,
Command as CommandSubject,
} from 'services/subjects'
import { ckbCore, getBlockchainInfo, getTipHeader } from 'services/chain'
import { ckbCore, getTipHeader } from 'services/chain'
import { networks as networksCache, currentNetworkID as currentNetworkIDCache } from 'services/localCache'
import { WalletWizardPath } from 'components/WalletWizard'
import { ErrorCode, RoutePath, getConnectionStatus } from 'utils'
Expand All @@ -38,18 +38,16 @@ export const useSyncChainData = ({ chainURL, dispatch }: { chainURL: string; dis
useEffect(() => {
let timer: NodeJS.Timeout
const syncBlockchainInfo = () => {
Promise.all([getTipHeader(), getBlockchainInfo()])
.then(([header, chainInfo]) => {
getTipHeader()
.then(header => {
if (isCurrentUrl(chainURL)) {
dispatch({
type: AppActions.UpdateChainInfo,
payload: {
tipBlockNumber: `${BigInt(header.number)}`,
tipBlockHash: header.hash,
tipDao: header.dao,
tipBlockTimestamp: +header.timestamp,
chain: chainInfo.chain,
difficulty: BigInt(chainInfo.difficulty),
epoch: chainInfo.epoch,
epoch: header.epoch,
},
})

Expand Down
Loading