Skip to content

Commit

Permalink
feat: ChainInfo delegates Networks Service to get current chain
Browse files Browse the repository at this point in the history
  • Loading branch information
ashchan committed Nov 15, 2019
1 parent a078e76 commit 0673343
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 74 deletions.
14 changes: 8 additions & 6 deletions packages/neuron-wallet/src/controllers/app/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { UpdateController } from 'controllers'
import { showWindow } from './show-window'
import NetworksService from 'services/networks'
import WalletsService from 'services/wallets'
import ChainInfo from 'models/chain-info'
import ChainInfo from 'services/chain-info'
import CommandSubject from 'models/subjects/command'

enum URL {
Expand Down Expand Up @@ -295,10 +295,8 @@ const contextMenuTemplate: {
},
networkList: async (id: string) => {
const networksService = NetworksService.getInstance()
const [network, currentNetworkID] = await Promise.all([
networksService.get(id).catch(() => null),
networksService.getCurrentID().catch(() => null),
])
const network = networksService.get(id)
const currentNetworkID = networksService.getCurrentID()

if (!network) {
showMessageBox({
Expand Down Expand Up @@ -401,7 +399,11 @@ const contextMenuTemplate: {
return []
}

const address = bech32Address(identifier)
const address = bech32Address(identifier, {
prefix: ChainInfo.getInstance().isMainnet() ? AddressPrefix.Mainnet : AddressPrefix.Testnet,
type: AddressType.HashIdx,
codeHashOrCodeHashIndex: '0x00',
})
return [
{
label: i18n.t('contextMenu.copy-address'),
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/controllers/wallets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { dialog, SaveDialogReturnValue, BrowserWindow } from 'electron'
import WalletsService, { Wallet, WalletProperties, FileKeystoreWallet } from 'services/wallets'
import Keystore from 'models/keys/keystore'
import Keychain from 'models/keys/keychain'
import ChainInfo from 'models/chain-info'
import ChainInfo from 'services/chain-info'
import { validateMnemonic, mnemonicToSeedSync } from 'models/keys/mnemonic'
import { AccountExtendedPublicKey, ExtendedPrivateKey } from 'models/keys/key'
import { ResponseCode } from 'utils/const'
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/models/lock-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { OutPoint, Script, ScriptHashType } from 'types/cell-types'
import ConvertTo from 'types/convert-to'
import { SystemScriptSubject } from 'models/subjects/system-script'
import Core from '@nervosnetwork/ckb-sdk-core'
import ChainInfo from './chain-info'
import ChainInfo from '../services/chain-info'

export interface SystemScript {
codeHash: string
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/services/addresses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import LockUtils from 'models/lock-utils'
import AddressDao, { Address as AddressInterface, AddressVersion } from 'database/address/address-dao'
import AddressCreatedSubject from 'models/subjects/address-created-subject'
import NodeService from './node'
import ChainInfo from 'models/chain-info'
import ChainInfo from 'services/chain-info'

const MAX_ADDRESS_COUNT = 30

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import NetworksService from './networks'

export default class ChainInfo {
private static instance: ChainInfo

Expand All @@ -9,18 +11,15 @@ export default class ChainInfo {
return ChainInfo.instance
}

private chain: string = ''

public setChain = (chain: string) => {
this.chain = chain
public setChain = (_chain: string) => {
}

public getChain = (): string => {
return this.chain
return NetworksService.getInstance().getCurrent().chain
}

public isMainnet = (): boolean => {
return this.chain === 'ckb'
return this.getChain() === 'ckb'
}

public explorerUrl = (): string => {
Expand Down
104 changes: 49 additions & 55 deletions packages/neuron-wallet/src/services/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,61 +40,52 @@ export default class NetworksService extends Store {
constructor() {
super('networks', 'index.json', JSON.stringify(presetNetworks))

this.getAll().then(currentNetworkList => {
if (currentNetworkList) {
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 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)
})

this.getCurrentID().then(currentNetworkID => {
if (currentNetworkID) {
CurrentNetworkIDSubject.next({ currentNetworkID })
this.get(currentNetworkID).then(network => {
if (network) {
networkSwitchSubject.next(network)
}
})
}
})
const currentNetwork = this.getCurrent()
if (currentNetwork) {
CurrentNetworkIDSubject.next({ currentNetworkID: currentNetwork.id })
networkSwitchSubject.next(currentNetwork)
}

this.on(NetworksKey.List, async (_, currentNetworkList: NetworkWithID[] = []) => {
NetworkListSubject.next({ currentNetworkList })

const currentID = await this.getCurrentID()
const currentID = this.getCurrentID()
if (currentNetworkList.find(network => network.id === currentID)) {
return
}

const defaultNetwork = await this.defaultOne()
const defaultNetwork = this.defaultOne()
if (!defaultNetwork) {
throw new LackOfDefaultNetwork()
}
this.activate(defaultNetwork.id)
})

this.on(NetworksKey.Current, async (_, currentNetworkID: NetworkID) => {
const currentNetwork = await this.get(currentNetworkID)
const currentNetwork = this.get(currentNetworkID)
if (!currentNetwork) {
throw new NetworkNotFound(currentNetworkID)
}
Expand All @@ -103,19 +94,22 @@ export default class NetworksService extends Store {
})
}

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

@Validate
public async get(@Required id: NetworkID) {
const list = await this.getAll()
public getCurrent(): NetworkWithID {
const currentID = this.getCurrentID()
return this.get(currentID!)! // Should always have at least one network
}

public get(@Required id: NetworkID) {
const list = this.getAll()
return list.find(item => item.id === id) || null
}

@Validate
public async updateAll(@Required networks: NetworkWithID[]) {
public updateAll(@Required networks: NetworkWithID[]) {
if (!Array.isArray(networks)) {
throw new InvalidFormat('Networks')
}
Expand All @@ -124,7 +118,7 @@ export default class NetworksService extends Store {

@Validate
public async create(@Required name: NetworkName, @Required remote: NetworkRemote, type: NetworkType = NetworkType.Normal) {
const list = await this.getAll()
const list = this.getAll()
if (list.some(item => item.name === name)) {
throw new UsedName('Network')
}
Expand All @@ -148,13 +142,13 @@ export default class NetworksService extends Store {
chain,
}

await this.updateAll([...list, newOne])
this.updateAll([...list, newOne])
return newOne
}

@Validate
public async update(@Required id: NetworkID, @Required options: Partial<Network>) {
const list = await this.getAll()
const list = this.getAll()
const network = list.find(item => item.id === id)
if (!network) {
throw new NetworkNotFound(id)
Expand All @@ -177,30 +171,30 @@ export default class NetworksService extends Store {
}

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

@Validate
public async delete(@Required id: NetworkID) {
const networkToDelete = await this.get(id)
const networkToDelete = this.get(id)
if (!networkToDelete) {
throw new NetworkNotFound(id)
}
if (networkToDelete.type === NetworkType.Default) {
throw new DefaultNetworkUnremovable()
}

const prevNetworkList = await this.getAll()
const prevNetworkList = this.getAll()
const currentNetworkList = prevNetworkList.filter(item => item.id !== id)
this.updateAll(currentNetworkList)
}

@Validate
public async activate(@Required id: NetworkID) {
const network = await this.get(id)
const network = this.get(id)
if (!network) {
throw new NetworkNotFound(id)
}
Expand All @@ -227,12 +221,12 @@ export default class NetworksService extends Store {
}
}

public getCurrentID = async () => {
return (await this.read<string>(NetworksKey.Current)) || null
public getCurrentID = () => {
return this.readSync<string>(NetworksKey.Current) || null
}

public defaultOne = async () => {
const list = await this.getAll()
public defaultOne = () => {
const list = this.getAll()
return list.find(item => item.type === NetworkType.Default) || null
}
}
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/services/wallets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import FileService from './file'
import { TransactionsService, TransactionPersistor, TransactionGenerator } from './tx'
import AddressService from './addresses'
import { deindexLockHashes } from './indexer/deindex'
import ChainInfo from 'models/chain-info'
import ChainInfo from 'services/chain-info'
import AddressesService from 'services/addresses'
import { Cell, DepType } from 'types/cell-types'
import TypeConvert from 'types/type-convert'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import IndexerQueue, { LockHashInfo } from 'services/indexer/queue'
import { Address } from 'database/address/address-dao'

import initConnection from 'database/chain/ormconfig'
import ChainInfo from 'models/chain-info'
import ChainInfo from 'services/chain-info'

const { nodeService, addressCreatedSubject, walletCreatedSubject } = remote.require('./startup/sync-block-task/params')

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { updateMetaInfo, getMetaInfo } from 'database/chain/meta-info'
import LockUtils from 'models/lock-utils'
import logger from 'utils/logger'
import genesisBlockHash, { getChain } from './genesis'
import ChainInfo from 'models/chain-info'
import ChainInfo from 'services/chain-info'
import DaoUtils from '../../models/dao-utils'
import { NetworkWithID, EMPTY_GENESIS_HASH } from 'types/network'

Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-wallet/src/startup/sync-block-task/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import BlockListener from 'services/sync/block-listener'
import { Address } from 'database/address/address-dao'

import initConnection from 'database/chain/ormconfig'
import ChainInfo from 'models/chain-info'
import ChainInfo from 'services/chain-info'

const { nodeService, addressCreatedSubject, walletCreatedSubject } = remote.require('./startup/sync-block-task/params')

Expand Down

0 comments on commit 0673343

Please sign in to comment.