Skip to content

Commit

Permalink
feat: Remove ChainInfo moving its feature into NetworksService
Browse files Browse the repository at this point in the history
  • Loading branch information
ashchan committed Nov 15, 2019
1 parent 0673343 commit 81f1eff
Show file tree
Hide file tree
Showing 16 changed files with 94 additions and 152 deletions.
7 changes: 3 additions & 4 deletions packages/neuron-wallet/src/controllers/app/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { UpdateController } from 'controllers'
import { showWindow } from './show-window'
import NetworksService from 'services/networks'
import WalletsService from 'services/wallets'
import ChainInfo from 'services/chain-info'
import CommandSubject from 'models/subjects/command'

enum URL {
Expand Down Expand Up @@ -400,7 +399,7 @@ const contextMenuTemplate: {
}

const address = bech32Address(identifier, {
prefix: ChainInfo.getInstance().isMainnet() ? AddressPrefix.Mainnet : AddressPrefix.Testnet,
prefix: NetworksService.getInstance().isMainnet() ? AddressPrefix.Mainnet : AddressPrefix.Testnet,
type: AddressType.HashIdx,
codeHashOrCodeHashIndex: '0x00',
})
Expand All @@ -415,7 +414,7 @@ const contextMenuTemplate: {
},
{
label: i18n.t('contextMenu.view-on-explorer'),
click: () => { shell.openExternal(`${ChainInfo.getInstance().explorerUrl()}/address/${address}`) }
click: () => { shell.openExternal(`${NetworksService.getInstance().explorerUrl()}/address/${address}`) }
},
]
},
Expand All @@ -433,7 +432,7 @@ const contextMenuTemplate: {
},
{
label: i18n.t('contextMenu.view-on-explorer'),
click: () => { shell.openExternal(`${ChainInfo.getInstance().explorerUrl()}/transaction/${hash}`) }
click: () => { shell.openExternal(`${NetworksService.getInstance().explorerUrl()}/transaction/${hash}`) }
},
]
},
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-wallet/src/controllers/wallets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import fs from 'fs'
import { parseAddress } from '@nervosnetwork/ckb-sdk-utils'
import { dialog, SaveDialogReturnValue, BrowserWindow } from 'electron'
import WalletsService, { Wallet, WalletProperties, FileKeystoreWallet } from 'services/wallets'
import NetworksService from 'services/networks'
import Keystore from 'models/keys/keystore'
import Keychain from 'models/keys/keychain'
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 Expand Up @@ -341,7 +341,7 @@ export default class WalletsController {
feeRate = '1000'
}

const isMainnet = ChainInfo.getInstance().isMainnet()
const isMainnet = NetworksService.getInstance().isMainnet()
params.items.forEach(item => {
if (isMainnet && !item.address.startsWith('ckb')) {
throw new MainnetAddressRequired(item.address)
Expand Down
8 changes: 3 additions & 5 deletions packages/neuron-wallet/src/models/lock-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ 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 '../services/chain-info'

export interface SystemScript {
codeHash: string
Expand Down Expand Up @@ -119,13 +118,12 @@ export default class LockUtils {
return LockUtils.computeScriptHash(lock)
}

static lockScriptToAddress(lock: Script): string {
static lockScriptToAddress(lock: Script, prefix: AddressPrefix = AddressPrefix.Mainnet): string {
const blake160: string = lock.args!
return LockUtils.blake160ToAddress(blake160)
return LockUtils.blake160ToAddress(blake160, prefix)
}

static blake160ToAddress(blake160: string): string {
const prefix = ChainInfo.getInstance().isMainnet() ? AddressPrefix.Mainnet : AddressPrefix.Testnet
static blake160ToAddress(blake160: string, prefix: AddressPrefix = AddressPrefix.Mainnet): string {
return bech32Address(blake160, {
prefix,
type: AddressType.HashIdx,
Expand Down
6 changes: 3 additions & 3 deletions 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 'services/chain-info'
import NetworksService from 'services/networks'

const MAX_ADDRESS_COUNT = 30

Expand Down Expand Up @@ -162,7 +162,7 @@ export default class AddressService {
AddressPrefix.Mainnet
).address

const addressToParse = ChainInfo.getInstance().isMainnet() ? mainnetAddress : testnetAddress
const addressToParse = NetworksService.getInstance().isMainnet() ? mainnetAddress : testnetAddress
const blake160: string = LockUtils.addressToBlake160(addressToParse)

const testnetAddressInfo: AddressInterface = {
Expand Down Expand Up @@ -238,6 +238,6 @@ export default class AddressService {
}

private static getAddressVersion = (): AddressVersion => {
return ChainInfo.getInstance().isMainnet() ? AddressVersion.Mainnet : AddressVersion.Testnet
return NetworksService.getInstance().isMainnet() ? AddressVersion.Mainnet : AddressVersion.Testnet
}
}
31 changes: 0 additions & 31 deletions packages/neuron-wallet/src/services/chain-info.ts

This file was deleted.

17 changes: 14 additions & 3 deletions packages/neuron-wallet/src/services/indexer/queue.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Subject, Subscription } from 'rxjs'
import { AddressPrefix } from '@nervosnetwork/ckb-sdk-utils'
import Utils from 'services/sync/utils'
import logger from 'utils/logger'
import GetBlocks from 'services/sync/get-blocks'
import NetworksService from 'services/networks'
import { Transaction, TransactionWithStatus } from 'types/cell-types'
import TypeConvert from 'types/type-convert'
import BlockNumber from 'services/sync/block-number'
Expand Down Expand Up @@ -211,7 +213,10 @@ export default class IndexerQueue {
blockHash: transactionWithStatus.txStatus.blockHash!
}
if (type === TxPointType.CreatedBy && this.latestCreatedBy.includes(txUniqueFlag)) {
const address = LockUtils.lockScriptToAddress(transaction.outputs![parseInt(txPoint.index, 16)].lock)
const address = LockUtils.lockScriptToAddress(
transaction.outputs![parseInt(txPoint.index, 16)].lock,
NetworksService.getInstance().isMainnet ? AddressPrefix.Mainnet : AddressPrefix.Testnet
)
AddressesUsedSubject.getSubject().next({
addresses: [address],
url: this.url,
Expand Down Expand Up @@ -273,13 +278,19 @@ export default class IndexerQueue {

let address: string | undefined
if (type === TxPointType.CreatedBy) {
address = LockUtils.lockScriptToAddress(transaction.outputs![parseInt(txPoint.index, 16)].lock)
address = LockUtils.lockScriptToAddress(
transaction.outputs![parseInt(txPoint.index, 16)].lock,
NetworksService.getInstance().isMainnet ? AddressPrefix.Mainnet : AddressPrefix.Testnet
)
this.latestCreatedBy.push(txUniqueFlag)
} else if (type === TxPointType.ConsumedBy) {
const input = txEntity.inputs[parseInt(txPoint.index, 16)]
const output = await IndexerTransaction.updateInputLockHash(input.outPointTxHash!, input.outPointIndex!)
if (output) {
address = LockUtils.lockScriptToAddress(output.lock)
address = LockUtils.lockScriptToAddress(
output.lock,
NetworksService.getInstance().isMainnet ? AddressPrefix.Mainnet : AddressPrefix.Testnet
)
}
}
if (address) {
Expand Down
17 changes: 14 additions & 3 deletions packages/neuron-wallet/src/services/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export default class NetworksService extends Store {

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

public get(@Required id: NetworkID) {
Expand Down Expand Up @@ -222,11 +222,22 @@ export default class NetworksService extends Store {
}

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

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

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

public explorerUrl = (): string => {
if (this.isMainnet()) {
return "https://explorer.nervos.org"
}
return "https://explorer.nervos.org/testnet"
}
}
14 changes: 12 additions & 2 deletions packages/neuron-wallet/src/services/sync/check-and-save/tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import LockUtils from 'models/lock-utils'
import CheckOutput from './output'
import { addressesUsedSubject as addressesUsedSubjectParam } from '../renderer-params'
import { AddressesWithURL } from 'models/subjects/addresses-used-subject'
import NetworksService from 'services/networks'
import { AddressPrefix } from 'models/keys/address'

export default class CheckTx {
private tx: Transaction
Expand All @@ -32,7 +34,10 @@ export default class CheckTx {
const inputAddresses = await this.filterInputs(lockHashes)

const outputAddresses: string[] = outputs.map(output => {
return LockUtils.lockScriptToAddress(output.lock)
return LockUtils.lockScriptToAddress(
output.lock,
NetworksService.getInstance().isMainnet ? AddressPrefix.Mainnet : AddressPrefix.Testnet
)
})

const addresses: string[] = inputAddresses.concat(outputAddresses)
Expand Down Expand Up @@ -85,7 +90,12 @@ export default class CheckTx {
outPointIndex: outPoint.index,
})
if (output && lockHashes.includes(output.lockHash)) {
addresses.push(LockUtils.lockScriptToAddress(output.lock))
addresses.push(
LockUtils.lockScriptToAddress(
output.lock,
NetworksService.getInstance().isMainnet ? AddressPrefix.Mainnet : AddressPrefix.Testnet
)
)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions 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 'services/chain-info'
import NetworksService from 'services/networks'
import AddressesService from 'services/addresses'
import { Cell, DepType } from 'types/cell-types'
import TypeConvert from 'types/type-convert'
Expand Down Expand Up @@ -269,7 +269,7 @@ export default class WalletService {
}

private deindexAddresses = async (addresses: string[]) => {
const prefix = ChainInfo.getInstance().isMainnet() ? AddressPrefix.Mainnet : AddressPrefix.Testnet
const prefix = NetworksService.getInstance().isMainnet() ? AddressPrefix.Mainnet : AddressPrefix.Testnet
const addressesWithEnvPrefix: string[] = addresses.filter(addr => addr.startsWith(prefix))

if (addressesWithEnvPrefix.length === 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import IndexerQueue, { LockHashInfo } from 'services/indexer/queue'
import { Address } from 'database/address/address-dao'

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

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

Expand All @@ -19,15 +18,14 @@ export const loadAddressesAndConvert = async (nodeURL: string): Promise<string[]

// call this after network switched
let indexerQueue: IndexerQueue | undefined
export const switchNetwork = async (nodeURL: string, genesisBlockHash: string, chain: string) => {
export const switchNetwork = async (nodeURL: string, genesisBlockHash: string, _chain: string) => {
// stop all blocks service
if (indexerQueue) {
await indexerQueue.stopAndWait()
}

// disconnect old connection and connect to new database
await initConnection(genesisBlockHash)
ChainInfo.getInstance().setChain(chain)
// load lockHashes
const lockHashes: string[] = await loadAddressesAndConvert(nodeURL)
const lockHashInfos: LockHashInfo[] = lockHashes.map(lockHash => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ 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 'services/chain-info'
import DaoUtils from '../../models/dao-utils'
import { NetworkWithID, EMPTY_GENESIS_HASH } from 'types/network'

Expand Down Expand Up @@ -47,7 +46,6 @@ export class InitDatabase {
if (chain === '') {
chain = await getChain(network.remote)
}
ChainInfo.getInstance().setChain(chain)

try {
const systemScriptInfo = await LockUtils.systemScript(network.remote)
Expand All @@ -64,7 +62,6 @@ export class InitDatabase {
const metaInfo = getMetaInfo()
await initConnection(metaInfo.genesisBlockHash)
chain = metaInfo.chain
ChainInfo.getInstance().setChain(chain)
LockUtils.setSystemScript(metaInfo.systemScriptInfo)
DaoUtils.setDaoScript(metaInfo.daoScriptInfo)
hash = metaInfo.genesisBlockHash
Expand Down
5 changes: 1 addition & 4 deletions packages/neuron-wallet/src/startup/sync-block-task/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import AddressService from 'services/addresses'
import LockUtils from 'models/lock-utils'
import BlockListener from 'services/sync/block-listener'
import { Address } from 'database/address/address-dao'

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

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

Expand All @@ -27,15 +25,14 @@ export const loadAddressesAndConvert = async (nodeURL: string): Promise<string[]

// call this after network switched
let blockListener: BlockListener | undefined
export const switchNetwork = async (url: string, genesisBlockHash: string, chain: string) => {
export const switchNetwork = async (url: string, genesisBlockHash: string, _chain: string) => {
// stop all blocks service
if (blockListener) {
await blockListener.stopAndWait()
}

// disconnect old connection and connect to new database
await initConnection(genesisBlockHash)
ChainInfo.getInstance().setChain(chain)
// load lockHashes
const lockHashes: string[] = await loadAddressesAndConvert(url)
// start sync blocks service
Expand Down
45 changes: 0 additions & 45 deletions packages/neuron-wallet/tests/models/chain-info.test.ts

This file was deleted.

Loading

0 comments on commit 81f1eff

Please sign in to comment.