Skip to content

Commit

Permalink
feat: discriminate chain type by the result of rpc.getBlockchainInfo …
Browse files Browse the repository at this point in the history
…method
  • Loading branch information
Keith-CY committed Sep 26, 2019
1 parent 8113b3f commit 9654662
Show file tree
Hide file tree
Showing 15 changed files with 135 additions and 16 deletions.
3 changes: 2 additions & 1 deletion packages/neuron-ui/src/components/Addresses/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ const Addresses = ({
history,
dispatch,
}: React.PropsWithoutRef<StateWithDispatch & RouteComponentProps>) => {
const isMainnet = (networks.find(n => n.id === networkID) || {}).type === 'mainnet'
const isMainnet =
(networks.find(n => n.id === networkID) || {}).chain === (process.env.REACT_APP_MAINNET_TAG || 'ckb')
const [showMainnetAddress, setShowMainnetAddress] = useState(false)
const [t] = useTranslation()
useEffect(() => {
Expand Down
13 changes: 11 additions & 2 deletions packages/neuron-ui/src/components/NetworkEditor/index.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import React, { useMemo, useRef } from 'react'
import { RouteComponentProps } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { Stack, PrimaryButton, DefaultButton, TextField } from 'office-ui-fabric-react'
import { Stack, PrimaryButton, DefaultButton, TextField, Spinner } from 'office-ui-fabric-react'

import { StateWithDispatch } from 'states/stateProvider/reducer'
import { useGoBack } from 'utils/hooks'
import { useInitialize, useInputs, useNetworkEditor, useIsInputsValid, useHandleSubmit } from './hooks'

const NetworkEditor = ({
app: {
loadings: { network: isUpdating = false },
},
settings: { networks = [] },
match: {
params: { id = '' },
Expand Down Expand Up @@ -42,7 +45,13 @@ const NetworkEditor = ({
</Stack>
<Stack horizontal horizontalAlign="end" tokens={{ childrenGap: 10 }}>
<DefaultButton onClick={goBack} text={t('common.cancel')} />
<PrimaryButton disabled={hasError || notModified} onClick={handleSubmit} text={t('common.save')} />
{isUpdating ? (
<PrimaryButton disabled>
<Spinner />
</PrimaryButton>
) : (
<PrimaryButton disabled={hasError || notModified} onClick={handleSubmit} text={t('common.save')} />
)}
</Stack>
</Stack>
)
Expand Down
15 changes: 15 additions & 0 deletions packages/neuron-ui/src/components/NetworkSetting/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ const onContextMenu = (id: string = '') => () => {
contextMenu({ type: 'networkList', id })
}

const Label = ({ type, t }: { type: 'ckb' | 'ckb_testnet' | 'ckb_dev' | string; t: any }) => {
switch (type) {
case 'ckb': {
return <span className="label primary">{t('settings.network.mainnet')}</span>
}
case 'ckb_testnet': {
return <span className="label secondary">{t('settings.network.testnet')}</span>
}
default: {
return <span className="label third">{t('settings.network.devnet')}</span>
}
}
}

const NetworkSetting = ({
chain = chainState,
settings: { networks = [] },
Expand Down Expand Up @@ -53,6 +67,7 @@ const NetworkSetting = ({
<Text as="span" style={{ color: '#999' }}>
{`(${network.remote})`}
</Text>
<Label type={network.chain} t={t} />
</Stack>
)
},
Expand Down
5 changes: 4 additions & 1 deletion packages/neuron-ui/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,10 @@
"title": "Add or Edit Network",
"rpc-url": "RPC URL",
"name": "Name"
}
},
"mainnet": "Mainnet",
"testnet": "Testnet",
"devnet": "Devnet"
}
},
"password-request": {
Expand Down
5 changes: 4 additions & 1 deletion packages/neuron-ui/src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,10 @@
"title": "添加或编辑网络",
"rpc-url": "RPC地址",
"name": "名称"
}
},
"mainnet": "主网",
"testnet": "测试网",
"devnet": "开发网"
}
},
"password-request": {
Expand Down
1 change: 1 addition & 0 deletions packages/neuron-ui/src/states/initStates/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const appState: State.App = {
sending: false,
addressList: false,
transactionList: false,
network: false,
},
showTopAlert: false,
showAllNotifications: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,29 @@ export const createNetwork = (params: Controller.CreateNetworkParams) => (dispat
}

export const updateNetwork = (params: Controller.UpdateNetworkParams) => (dispatch: StateDispatch, history: any) => {
updateRemoteNetwork(params).then(res => {
if (res.status === 1) {
addPopup('update-network-successfully')(dispatch)
history.push(Routes.SettingsNetworks)
} else {
addNotification(failureResToNotification(res))(dispatch)
}
dispatch({
type: AppActions.UpdateLoadings,
payload: {
network: true,
},
})
updateRemoteNetwork(params)
.then(res => {
if (res.status === 1) {
addPopup('update-network-successfully')(dispatch)
history.push(Routes.SettingsNetworks)
} else {
addNotification(failureResToNotification(res))(dispatch)
}
})
.finally(() => {
dispatch({
type: AppActions.UpdateLoadings,
payload: {
network: false,
},
})
})
}

export default {
Expand Down
8 changes: 8 additions & 0 deletions packages/neuron-ui/src/stories/NetworkSetting.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,23 @@ import initStates from 'states/initStates'
const states: { [title: string]: State.Network[] } = {
'Empty List': [],
'Content List': [
{
id: 'Mainnet',
name: 'Mainnet',
remote: 'http://localhost:8114',
chain: 'ckb',
},
{
id: 'Testnet',
name: 'Testnet',
remote: 'http://localhost:8114',
chain: 'ckb_testnet',
},
{
id: 'Local',
name: 'Local',
remote: 'http://localhost:8114',
chain: 'ckb_devnet',
},
],
}
Expand Down
2 changes: 2 additions & 0 deletions packages/neuron-ui/src/stories/Overview.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const stateTemplate = {
id: 'testnet',
name: 'Testnet',
remote: 'http://testnet.nervos.com',
chain: 'ckb_testnet',
},
],
},
Expand Down Expand Up @@ -111,6 +112,7 @@ stories.addDecorator(withKnobs).add('With knobs', () => {
id: text('Network iD', 'testnet'),
name: text('Network Name', 'Testnet'),
remote: text('Network Address', 'http://testnet.nervos.com'),
chain: text('Chain', 'ckb_testnet'),
},
],
},
Expand Down
23 changes: 23 additions & 0 deletions packages/neuron-ui/src/styles/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,29 @@ navbar {
background-color: white;
}

.label {
padding: 3px 4px;
font-size: 12px;
font-weight: 600;
line-height: 1;
color: #fff;
border-radius: 2px;
box-shadow: inset 0 -1px 0 rgba(27, 31, 35, .12);
text-transform: capitalize;

&.primary {
background-color: #6f42c1;
}

&.secondary {
background-color: #009688;
}

&.third {
background-color: #78909C;
}
}

.form-control,
.btn {
&:focus {
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-ui/src/types/App/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ declare namespace State {
sending: boolean
addressList: boolean
transactionList: boolean
network: boolean
}
showTopAlert: boolean
showAllNotifications: boolean
Expand All @@ -96,7 +97,7 @@ declare namespace State {
interface NetworkProperty {
name: string
remote: string
type?: 'mainnet' | 'testnet'
chain: 'ckb' | 'ckb_testnet' | 'ckb_dev' | string
}

interface Network extends NetworkProperty {
Expand Down
2 changes: 2 additions & 0 deletions packages/neuron-wallet/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,14 @@ const env: ENV = {
name: 'Testnet',
remote: 'http://localhost:8114',
type: 0,
chain: 'ckb_testnet',
},
{
id: 'local',
name: 'Local',
remote: 'http://localhost:8114',
type: 1,
chain: 'ckb_devnet',
},
],
},
Expand Down
34 changes: 33 additions & 1 deletion packages/neuron-wallet/src/services/networks.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Core from '@nervosnetwork/ckb-sdk-core'
import { v4 as uuid } from 'uuid'
import { BehaviorSubject } from 'rxjs'
import { LackOfDefaultNetwork, DefaultNetworkUnremovable } from 'exceptions/network'
Expand Down Expand Up @@ -92,18 +93,28 @@ export default class NetworksService extends Store {
public async create(
@Required name: NetworkName,
@Required remote: NetworkRemote,
type: NetworkType = NetworkType.Normal
type: NetworkType = NetworkType.Normal,
) {
const list = await this.getAll()
if (list.some(item => item.name === name)) {
throw new UsedName('Network')
}

const core = new Core(remote)

const chain = await core.rpc
.getBlockchainInfo()
.then(info => info.chain)
.catch(() => '')

const newOne = {
id: uuid(),
name,
remote,
type,
chain,
}

await this.updateAll([...list, newOne])
return newOne
}
Expand All @@ -115,7 +126,17 @@ export default class NetworksService extends Store {
if (!network) {
throw new NetworkNotFound(id)
}

Object.assign(network, options)
if (!options.chain) {
const core = new Core(network.remote)
const chain = await core.rpc
.getBlockchainInfo()
.then(info => info.chain)
.catch(() => '')
network.chain = chain
}

this.updateAll(list)
const currentID = await this.getCurrentID()
if (currentID === id) {
Expand Down Expand Up @@ -145,6 +166,17 @@ export default class NetworksService extends Store {
throw new NetworkNotFound(id)
}
this.writeSync(NetworksKey.Current, id)

const core = new Core(network.remote)

const chain = await core.rpc
.getBlockchainInfo()
.then(info => info.chain)
.catch(() => '')

if (chain && chain !== network.chain) {
this.update(id, { chain })
}
}

public getCurrentID = async () => {
Expand Down
3 changes: 3 additions & 0 deletions packages/neuron-wallet/src/types/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,17 @@ export enum NetworksKey {
List = 'list',
Current = 'current',
}

export enum NetworkType {
Default,
Normal,
}

export interface Network {
name: NetworkName
remote: NetworkRemote
type: NetworkType
chain: 'ckb' | 'ckb_testnet' | 'ckb_dev' | string // returned by rpc.getBlockchainInfo
}
export interface NetworkWithID extends Network {
id: NetworkID
Expand Down
5 changes: 3 additions & 2 deletions packages/neuron-wallet/tests/services/networks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe(`Unit tests of networks service`, () => {
remote: `http://new-network.localhost.com`,
type: 0,
id: '',
chain: '',
}

const newNetworkWithDefaultTypeOf1 = {
Expand Down Expand Up @@ -166,14 +167,14 @@ describe(`Unit tests of networks service`, () => {

it(`service.create requires name, and remote`, async () => {
expect(service.create(undefined as any, undefined as any)).rejects.toThrowError(
i18n.t(ERROR_MESSAGE.MISSING_ARG)
i18n.t(ERROR_MESSAGE.MISSING_ARG),
)
expect(service.create('network name', undefined as any)).rejects.toThrowError(i18n.t(ERROR_MESSAGE.MISSING_ARG))
})

it(`service.update requires id, options`, () => {
expect(service.update(undefined as any, undefined as any)).rejects.toThrowError(
i18n.t(ERROR_MESSAGE.MISSING_ARG)
i18n.t(ERROR_MESSAGE.MISSING_ARG),
)
expect(service.update('', undefined as any)).rejects.toThrowError(i18n.t(ERROR_MESSAGE.MISSING_ARG))
})
Expand Down

0 comments on commit 9654662

Please sign in to comment.