Skip to content

Commit

Permalink
fix: Use ConnectionStatusSubject to control the network notify.
Browse files Browse the repository at this point in the history
  • Loading branch information
yanguoyu committed Nov 5, 2023
1 parent 7754ab7 commit c539f40
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 83 deletions.
70 changes: 29 additions & 41 deletions packages/neuron-ui/src/containers/Main/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,7 @@ import {
showGlobalAlertDialog,
} from 'states/stateProvider/actionCreators'

import {
getCurrentWallet,
getIsNodeRunExternal,
getWinID,
setCurrentNetwork,
startNodeIgnoreExternal,
} from 'services/remote'
import { getCurrentWallet, getWinID, setCurrentNetwork, startNodeIgnoreExternal } from 'services/remote'
import {
DataUpdate as DataUpdateSubject,
NetworkList as NetworkListSubject,
Expand Down Expand Up @@ -111,13 +105,15 @@ export const useSubscription = ({
navigate,
dispatch,
location,
showSwitchNetwork,
}: {
walletID: string
chain: State.Chain
isAllowedToFetchList: boolean
navigate: NavigateFunction
location: ReturnType<typeof useLocation>
dispatch: StateDispatch
showSwitchNetwork: () => void
}) => {
const { pageNo, pageSize, keywords } = chain.transactions

Expand Down Expand Up @@ -209,6 +205,9 @@ export const useSubscription = ({
type: NeuronWalletActions.UpdateConnectionStatus,
payload: getConnectionStatus({ ...status, isTimeout: Date.now() > CONNECTING_DEADLINE }),
})
if (status.connected && status.isBundledNode && !status.startedBundledNode) {
showSwitchNetwork()
}
}
})

Expand Down Expand Up @@ -314,49 +313,32 @@ export const useSubscription = ({
commandSubscription.unsubscribe()
showGlobalDialogSubject.unsubscribe()
}
}, [walletID, pageNo, pageSize, keywords, isAllowedToFetchList, navigate, dispatch, location.pathname])
}, [
walletID,
pageNo,
pageSize,
keywords,
isAllowedToFetchList,
navigate,
dispatch,
location.pathname,
showSwitchNetwork,
])
}

export const useCheckNode = (networks: State.Network[], network?: State.Network) => {
const [showSwitchNetwork, setShowSwitchNetwork] = useState<boolean>(false)
export const useCheckNode = (networks: State.Network[]) => {
const [isSwitchNetworkShow, setIsSwitchNetworkShow] = useState<boolean>(false)
const [selectNetwork, setSelectNetwork] = useState(networks[0]?.id)
const navigate = useNavigate()
useEffect(() => {
if (!network) return () => {}
let timer: ReturnType<typeof setTimeout>
const checkNode = () => {
return getIsNodeRunExternal().then(res => {
if (isSuccessResponse(res) && res.result !== null) {
if (res.result) {
navigate(RoutePath.Settings)
setShowSwitchNetwork(true)
}
} else {
timer = setTimeout(() => {
checkNode()
}, 2_000)
}
})
}
if (network.readonly) {
checkNode()
} else {
setShowSwitchNetwork(false)
}
return () => {
clearTimeout(timer)
}
}, [network?.readonly, network?.type, navigate])
useEffect(() => {
if (showSwitchNetwork) {
if (isSwitchNetworkShow) {
setSelectNetwork(networks[0]?.id)
}
}, [networks, showSwitchNetwork])
}, [networks, isSwitchNetworkShow])
const [showEditorDialog, setShowEditorDialog] = useState(false)
const onConfirm = useCallback(() => {
if (selectNetwork) {
setCurrentNetwork(selectNetwork)
setShowSwitchNetwork(false)
setIsSwitchNetworkShow(false)
}
}, [selectNetwork])
const onCloseEditorDialog = useCallback(() => {
Expand All @@ -365,12 +347,18 @@ export const useCheckNode = (networks: State.Network[], network?: State.Network)
const onOpenEditorDialog = useCallback(() => {
setShowEditorDialog(true)
}, [])
const navigate = useNavigate()
const showSwitchNetwork = useCallback(() => {
navigate(RoutePath.Settings)
setIsSwitchNetworkShow(true)
}, [])
return {
selectNetwork,
onChangeSelected: setSelectNetwork,
isSwitchNetworkShow,
showSwitchNetwork,
onCancel: useCallback(() => {
setShowSwitchNetwork(false)
setIsSwitchNetworkShow(false)
startNodeIgnoreExternal()
}, []),
onConfirm,
Expand Down
41 changes: 22 additions & 19 deletions packages/neuron-ui/src/containers/Main/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,6 @@ const MainContent = () => {
const { networkID } = chain
const [t, i18n] = useTranslation()

useSubscription({
walletID,
chain,
isAllowedToFetchList,
navigate,
dispatch,
location,
})

const network = useMemo(() => networks.find(n => n.id === networkID), [networks, networkID])

const sameUrlNetworks = useMemo(
Expand All @@ -46,6 +37,27 @@ const MainContent = () => {
dispatch,
})

const {
isSwitchNetworkShow,
showSwitchNetwork,
onCancel: onCloseSwitchNetwork,
onConfirm: onSwitchNetwork,
onChangeSelected,
showEditorDialog,
onCloseEditorDialog,
onOpenEditorDialog,
} = useCheckNode(sameUrlNetworks)

useSubscription({
walletID,
chain,
isAllowedToFetchList,
navigate,
dispatch,
location,
showSwitchNetwork,
})

useOnCurrentWalletChange({
walletID,
chain,
Expand All @@ -58,15 +70,6 @@ const MainContent = () => {
dismissGlobalAlertDialog()(dispatch)
}, [dispatch])
const { isMigrateDialogShow, onCancel, onBackUp, onConfirm } = useMigrate()
const {
showSwitchNetwork,
onCancel: onCloseSwitchNetwork,
onConfirm: onSwitchNetwork,
onChangeSelected,
showEditorDialog,
onCloseEditorDialog,
onOpenEditorDialog,
} = useCheckNode(sameUrlNetworks, network)

return (
<div onContextMenu={onContextMenu}>
Expand All @@ -92,7 +95,7 @@ const MainContent = () => {
</div>
</Dialog>
<Dialog
show={showSwitchNetwork}
show={isSwitchNetworkShow}
onCancel={onCloseSwitchNetwork}
onConfirm={sameUrlNetworks.length ? onSwitchNetwork : onOpenEditorDialog}
confirmText={sameUrlNetworks.length ? undefined : t('main.external-node-detected-dialog.add-network')}
Expand Down
1 change: 0 additions & 1 deletion packages/neuron-ui/src/services/remote/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export const setCkbNodeDataPath = remoteApi<{ dataPath: string; clearCache?: boo
)
export const stopProcessMonitor = remoteApi<'ckb'>('stop-process-monitor')
export const startProcessMonitor = remoteApi<'ckb'>('start-process-monitor')
export const getIsNodeRunExternal = remoteApi<void, boolean>('is-node-run-external')
export const startNodeIgnoreExternal = remoteApi<void, boolean>('start-node-ignore-external')

export type VerifyExternalCkbNodeRes =
Expand Down
1 change: 0 additions & 1 deletion packages/neuron-ui/src/services/remote/remoteApiWrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ type Action =
| 'start-process-monitor'
| 'is-dark'
| 'set-theme'
| 'is-node-run-external'
| 'verify-external-ckb-node'
| 'start-node-ignore-external'
// Wallets
Expand Down
7 changes: 0 additions & 7 deletions packages/neuron-wallet/src/controllers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,13 +289,6 @@ export default class ApiController {
}
})

handle('is-node-run-external', () => {
return {
status: ResponseCode.Success,
result: NodeService.getInstance().isCkbNodeExternal,
}
})

handle('verify-external-ckb-node', async () => {
return {
status: ResponseCode.Success,
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/controllers/networks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ export default class NetworksController {
const id = networksService.getCurrentID()
const network = await networksService.update(id, {})
const genesisHashMatched = await new ChainInfo(network).load()
const isNodeMatched = !network.readonly || NodeService.getInstance().isCkbNodeExternal === false
const isNodeMatched = !network.readonly || (reconnected && NodeService.getInstance().startedBundledNode)

await switchToNetwork(network, reconnected, genesisHashMatched && isNodeMatched)
}
Expand Down
21 changes: 8 additions & 13 deletions packages/neuron-wallet/src/services/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,11 @@ class NodeService {
public connectionStatusSubject = new BehaviorSubject<boolean>(false)

private _tipBlockNumber: string = '0'
private startedBundledNode: boolean = false
private _isCkbNodeExternal?: boolean = undefined
#startedBundledNode: boolean = false

get startedBundledNode() {
return this.#startedBundledNode
}

private constructor() {
this.start()
Expand All @@ -68,13 +71,12 @@ class NodeService {
url: currentNetwork.remote,
connected,
isBundledNode,
startedBundledNode: isBundledNode ? this.startedBundledNode : false,
startedBundledNode: isBundledNode ? this.#startedBundledNode : false,
})
})
}

private whenNetworkUpdate = () => {
this._isCkbNodeExternal = undefined
this.tipNumberSubject.next('0')
this.connectionStatusSubject.next(false)
}
Expand Down Expand Up @@ -130,13 +132,11 @@ class NodeService {
await stopMonitor('ckb')
if (isDefaultCKBNeedStart) {
logger.info('CKB:\texternal RPC on default uri not detected, starting bundled CKB node.')
this._isCkbNodeExternal = false
const redistReady = await redistCheck()
await (redistReady ? this.startNode() : this.showGuideDialog())
await startMonitor()
} else {
logger.info('CKB:\texternal RPC on default uri detected, skip starting bundled CKB node.')
this._isCkbNodeExternal = true
}
}

Expand Down Expand Up @@ -179,9 +179,9 @@ class NodeService {
await CKBLightRunner.getInstance().stop()
await startCkbNode()
}
this.startedBundledNode = true
this.#startedBundledNode = true
} catch (error) {
this.startedBundledNode = false
this.#startedBundledNode = false
logger.info('CKB:\tfail to start bundled CKB with error:')
logger.error(error)
}
Expand All @@ -190,16 +190,11 @@ class NodeService {
public async startNodeIgnoreExternal() {
logger.info('CKB:\tignore running external node, and start node with another port')
await stopMonitor('ckb')
this._isCkbNodeExternal = false
const redistReady = await redistCheck()
await (redistReady ? this.startNode() : this.showGuideDialog())
await startMonitor()
}

get isCkbNodeExternal() {
return this._isCkbNodeExternal
}

private showGuideDialog = () => {
const I18N_PATH = `messageBox.ckb-dependency`
return dialog
Expand Down

1 comment on commit c539f40

@github-actions
Copy link

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 6760251821

Please sign in to comment.