Skip to content

Commit

Permalink
Merge pull request #1137 from nervosnetwork/lazy-update-network
Browse files Browse the repository at this point in the history
feat: Do not update network info too often
  • Loading branch information
ashchan authored Nov 16, 2019
2 parents 82a0c8d + 507131b commit 54eda3a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 60 deletions.
73 changes: 22 additions & 51 deletions packages/neuron-wallet/src/services/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { Validate, Required } from 'decorators'
import { UsedName, NetworkNotFound, InvalidFormat } from 'exceptions'
import { NetworkListSubject, CurrentNetworkIDSubject } from 'models/subjects/networks'
import { MAINNET_GENESIS_HASH, EMPTY_GENESIS_HASH, NetworkID, NetworkName, NetworkRemote, NetworksKey, NetworkType, Network, NetworkWithID } from 'types/network'
import logger from 'utils/logger'

export const networkSwitchSubject = new BehaviorSubject<undefined | NetworkWithID>(undefined)

Expand Down Expand Up @@ -43,28 +42,12 @@ export default class NetworksService extends Store {
const currentNetworkList = this.getAll()
NetworkListSubject.next({ currentNetworkList })

Promise.all(currentNetworkList.map(n => {
if (n.type == NetworkType.Default) {
return n
} else {
const core = new Core(n.remote)
return Promise.all([
core.rpc.getBlockchainInfo(),
core.rpc.getBlockHash('0x0')
]).then(([info, genesisHash]) => ({
...n,
chain: info.chain,
genesisHash
}))
}
})).then(networkList => {
this.updateAll(networkList)
}).catch((err: Error) => {
logger.error(err)
})

const currentNetwork = this.getCurrent()
if (currentNetwork) {
if (currentNetwork.type !== NetworkType.Default) {
this.update(currentNetwork.id, {}) // Update to trigger chain/genesis hash refresh
}

CurrentNetworkIDSubject.next({ currentNetworkID: currentNetwork.id })
networkSwitchSubject.next(currentNetwork)
}
Expand Down Expand Up @@ -95,13 +78,11 @@ export default class NetworksService extends Store {
}

public getAll = () => {
const list = this.readSync<NetworkWithID[]>(NetworksKey.List)
return list || presetNetworks.networks
return this.readSync<NetworkWithID[]>(NetworksKey.List) || presetNetworks.networks
}

public getCurrent(): NetworkWithID {
const currentID = this.getCurrentID()
return this.get(currentID) || this.defaultOne()! // Should always have at least one network
return this.get(this.getCurrentID()) || this.defaultOne()! // Should always have at least one network
}

public get(@Required id: NetworkID) {
Expand Down Expand Up @@ -161,19 +142,24 @@ export default class NetworksService extends Store {
const chain = await core.rpc
.getBlockchainInfo()
.then(info => info.chain)
.catch(() => 'ckb_dev')
network.chain = chain
.catch(() => '')
if (chain !== '') {
network.chain = chain
}

const genesisHash = await core.rpc
.getBlockHash('0x0')
.catch(() => EMPTY_GENESIS_HASH)
network.genesisHash = genesisHash
if (genesisHash !== EMPTY_GENESIS_HASH) {
network.genesisHash = genesisHash
}
}

this.updateAll(list)
const currentID = this.getCurrentID()
if (currentID === id) {
await this.activate(id)

if (this.getCurrentID() === id) {
CurrentNetworkIDSubject.next({ currentNetworkID: id })
networkSwitchSubject.next(network)
}
}

Expand All @@ -198,36 +184,21 @@ export default class NetworksService extends Store {
if (!network) {
throw new NetworkNotFound(id)
}
this.writeSync(NetworksKey.Current, id)

// No need to update the default mainnet
if (network.type === NetworkType.Default) {
return
// No need to update the default mainnet's genesis hash
if (network.type !== NetworkType.Default) {
this.update(id, {})
}

const core = new Core(network.remote)

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

const genesisHash = await core.rpc
.getBlockHash('0x0')
.catch(() => EMPTY_GENESIS_HASH)

if (chain && chain !== network.chain && genesisHash && genesisHash !== network.genesisHash) {
this.update(id, { chain, genesisHash })
}
this.writeSync(NetworksKey.Current, id)
}

public getCurrentID = () => {
return this.readSync<string>(NetworksKey.Current) || 'mainnet'
}

public defaultOne = () => {
const list = this.getAll()
return list.find(item => item.type === NetworkType.Default) || presetNetworks.networks[0]
return this.getAll().find(item => item.type === NetworkType.Default) || presetNetworks.networks[0]
}

public isMainnet = (): boolean => {
Expand Down
12 changes: 3 additions & 9 deletions packages/neuron-wallet/tests/services/networks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,11 @@ describe(`Unit tests of networks service`, () => {

let service: NetworksService = new NetworksService()

beforeEach(done => {
beforeEach(() => {
service = new NetworksService()
setTimeout(() => {
done()
}, 1000)
})
afterEach(done => {
afterEach(() => {
service.clear()
setTimeout(() => {
done()
}, 1000)
})

describe(`success cases`, () => {
Expand Down Expand Up @@ -132,7 +126,7 @@ describe(`Unit tests of networks service`, () => {
expect(currentID).toBe('mainnet')
})

it(`reset the netowrks`, async () => {
it(`reset the networks`, async () => {
await service.create(newNetwork.name, newNetwork.remote)
const newNetworkList = service.getAll()
expect(newNetworkList.length).toBe(2)
Expand Down

0 comments on commit 54eda3a

Please sign in to comment.