Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ export default {
payload: { networks: i18n.t(`messages.${Message.URLIsRequired}`) },
}
}
if (!remote.startsWith('http')) {
return {
type: MainActions.ErrorMessage,
payload: { networks: i18n.t(`messages.${Message.ProtocolIsRequired}`) },
}
}
// verification, for now, only name is unique
if (id === 'new') {
if (networks.some(network => network.name === name)) {
Expand Down
3 changes: 2 additions & 1 deletion packages/neuron-ui/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@
"no-wallet": "No Wallet",
"wallet-imported-successfully": "{{name}} imported successfully",
"wallet-created-successfully": "{{name}} created successfully",
"wallet-updated-successfully": "{{name}} updated successfully"
"wallet-updated-successfully": "{{name}} updated successfully",
"protocol-is-required": "Protocol is required"
}
}
}
3 changes: 2 additions & 1 deletion packages/neuron-ui/src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@
"no-wallet": "没有钱包",
"wallet-imported-successfully": "{{name}} 导入成功",
"wallet-created-successfully": "{{name}} 创建成功",
"wallet-updated-successfully": "{{name}} 更新成功"
"wallet-updated-successfully": "{{name}} 更新成功",
"protocol-is-required": "请指定 URL 协议"
}
}
}
1 change: 1 addition & 0 deletions packages/neuron-ui/src/utils/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export enum Message {
InvalidCapacity = 'invalid-capacity',
CapacityNotEnough = 'capacity-is-not-enough',
IsUnremovable = 'is-unremovable',
ProtocolIsRequired = 'protocol-is-required',
}

export enum TransactionType {
Expand Down
13 changes: 0 additions & 13 deletions packages/neuron-wallet/src/core.ts

This file was deleted.

4 changes: 2 additions & 2 deletions packages/neuron-wallet/src/services/addresses.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import TransactionsService from './transactions'
import ckbCore from '../core'
import HD from '../keys/hd'
import { KeysData } from '../keys/keystore'
// TODO: Should use service
import WalletStore from '../store/walletStore'
import nodeService from '../startup/nodeService'

const {
utils: { AddressPrefix, AddressType: Type, AddressBinIdx, pubkeyToAddress },
} = ckbCore
} = nodeService.core

export const MAX_ADDRESS_COUNT = 30
export const SEARCH_RANGE = 20
Expand Down
5 changes: 5 additions & 0 deletions packages/neuron-wallet/src/services/networks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import windowManage from '../utils/windowManage'
import { ResponseCode } from '../controllers'
import { NetworksMethod } from '../controllers/networks'
import { Channel } from '../utils/const'
import nodeService from '../startup/nodeService'

export type NetworkID = string
export type NetworkName = string
Expand Down Expand Up @@ -50,6 +51,10 @@ export default class NetworksService extends Store {
})

this.on(NetworksKey.Active, async (_, newActiveId) => {
const network = await this.get(newActiveId)
if (network) {
nodeService.setNetwork(network.remote)
}
windowManage.broadcast(Channel.Networks, NetworksMethod.ActiveId, {
status: ResponseCode.Success,
result: newActiveId,
Expand Down
29 changes: 21 additions & 8 deletions packages/neuron-wallet/src/services/node.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import Core from '@nervosnetwork/ckb-sdk-core'
import { interval, Subject } from 'rxjs'
import { distinctUntilChanged, flatMap, retry, filter } from 'rxjs/operators'
import ckbCore from '../core'

class NodeService {
tick = interval(1000)

tipNumberSubject = new Subject()

core: Core = new Core('')

setNetwork = (url: string) => {
if (typeof url !== 'string') {
throw new Error('url should be type of string')
}
if (!url.startsWith('http')) {
throw new Error('Protocol of url should be specified')
}
this.core = new Core(url)
return this.core
}

start = () => {
const { unsubscribe } = this.tipNumber()
return unsubscribe
Expand All @@ -15,7 +28,9 @@ class NodeService {
tipNumber = () =>
this.tick
.pipe(
flatMap(() => ckbCore.rpc.getTipBlockNumber()),
flatMap(() => {
return this.core.rpc.getTipBlockNumber()
}),
// TODO: to determine retry or not
retry(3),
distinctUntilChanged(),
Expand All @@ -33,18 +48,16 @@ class NodeService {
tipHeader = () =>
this.tipNumberSubject.pipe(
filter(tipNumber => typeof tipNumber !== 'undefined'),
flatMap(ckbCore.rpc.getTipHeader),
flatMap(this.core.rpc.getTipHeader),
)

tipBlock = () =>
this.tipNumberSubject
.pipe(
filter(tipNumber => typeof tipNumber !== 'undefined'),
flatMap(ckbCore.rpc.getBlockHash),
flatMap(this.core.rpc.getBlockHash),
)
.pipe(flatMap(ckbCore.rpc.getBlock))
.pipe(flatMap(this.core.rpc.getBlock))
}

const nodeService = new NodeService()

export default nodeService
export default NodeService
12 changes: 7 additions & 5 deletions packages/neuron-wallet/src/services/syncBlocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import { Subject } from 'rxjs'
import { Script, OutPoint, Cell } from './cells'
import TransactionsService, { Input, Transaction } from './transactions'
import OutputEntity from '../entities/Output'
import ckbCore from '../core'
import SyncInfoEntity from '../entities/SyncInfo'
import nodeService from '../startup/nodeService'

const { core } = nodeService

export interface BlockHeader {
version: number
Expand Down Expand Up @@ -91,7 +93,7 @@ export default class SyncBlocksService {

async tryGetTipBlockNumber(): Promise<number> {
try {
const tipBlockNumber = await ckbCore.rpc.getTipBlockNumber()
const tipBlockNumber = await core.rpc.getTipBlockNumber()
return parseInt(tipBlockNumber, 10)
} catch {
return this.tryGetTipBlockNumber()
Expand Down Expand Up @@ -150,7 +152,7 @@ export default class SyncBlocksService {
const blockNumbers = Array.from({ length: size }).map((_a, i) => i + startBlockNumber)
const blockHashes: string[] = await Promise.all(
blockNumbers.map(async num => {
const hash: string = await ckbCore.rpc.getBlockHash(num.toString())
const hash: string = await core.rpc.getBlockHash(num.toString())
return hash
}),
)
Expand All @@ -160,7 +162,7 @@ export default class SyncBlocksService {
static async getBlocks(blockHashes: string[]): Promise<Block[]> {
const blocks = await Promise.all(
blockHashes.map(async hash => {
const block = await ckbCore.rpc.getBlock(hash)
const block = await core.rpc.getBlock(hash)
return SyncBlocksService.convertBlock(block)
}),
)
Expand Down Expand Up @@ -337,7 +339,7 @@ export default class SyncBlocksService {
static convertInput(input: any): Input {
return {
previousOutput: input.previous_output,
args: input.args.map((arg: Uint8Array) => ckbCore.utils.bytesToHex(arg)),
args: input.args.map((arg: Uint8Array) => core.utils.bytesToHex(arg)),
}
}

Expand Down
34 changes: 18 additions & 16 deletions packages/neuron-wallet/src/services/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import InputEntity from '../entities/Input'
import OutputEntity from '../entities/Output'
import TransactionEntity from '../entities/Transaction'
import { getHistoryTransactions } from '../mock_rpc'
import ckbCore from '../core'
import nodeService from '../startup/nodeService'

const { core } = nodeService

export interface Input {
previousOutput: OutPoint
Expand Down Expand Up @@ -147,7 +149,7 @@ export default class TransactionsService {
): Promise<PaginationResult<Transaction>> => {
const lockHashes: string[] = await Promise.all(
params.pubkeys.map(async pubkey => {
const addr = ckbCore.utils.pubkeyToAddress(pubkey)
const addr = core.utils.pubkeyToAddress(pubkey)
const lockHash = await TransactionsService.addressToLockHash(addr)
return lockHash
}),
Expand Down Expand Up @@ -190,7 +192,7 @@ export default class TransactionsService {

// check whether the address has history transactions
public static hasTransactions = async (address: string): Promise<boolean> => {
const blake160 = ckbCore.utils.parseAddress(address, ckbCore.utils.AddressPrefix.Testnet, 'hex') as string
const blake160 = core.utils.parseAddress(address, core.utils.AddressPrefix.Testnet, 'hex') as string
const contractInfo = await TransactionsService.contractInfo()

const lock: Script = {
Expand Down Expand Up @@ -426,14 +428,14 @@ export default class TransactionsService {

// system contract info
public static contractInfo = async () => {
const genesisHash: string = await ckbCore.rpc.getBlockHash('0')
const genesisBlock = await ckbCore.rpc.getBlock(genesisHash)
const genesisHash: string = await core.rpc.getBlockHash('0')
const genesisBlock = await core.rpc.getBlock(genesisHash)
const systemScriptTx = genesisBlock.transactions[0]
const blake2b = ckbCore.utils.blake2b(32)
const blake2b = core.utils.blake2b(32)
const systemScriptCell = systemScriptTx.outputs[0]
const { data } = systemScriptCell
if (typeof data === 'string') {
blake2b.update(ckbCore.utils.hexToBytes(data))
blake2b.update(core.utils.hexToBytes(data))
} else {
// if Uint8Array
blake2b.update(data)
Expand Down Expand Up @@ -462,7 +464,7 @@ export default class TransactionsService {
const outputs: Cell[] = targetOutputs.map(o => {
const { capacity, address } = o

const blake160: string = ckbCore.utils.parseAddress(address, ckbCore.utils.AddressPrefix.Testnet, 'hex') as string
const blake160: string = core.utils.parseAddress(address, core.utils.AddressPrefix.Testnet, 'hex') as string

const output: Cell = {
capacity,
Expand All @@ -478,9 +480,9 @@ export default class TransactionsService {

// change
if (BigInt(capacities) > needCapacities) {
const changeBlake160: string = ckbCore.utils.parseAddress(
const changeBlake160: string = core.utils.parseAddress(
changeAddress,
ckbCore.utils.AddressPrefix.Testnet,
core.utils.AddressPrefix.Testnet,
'hex',
) as string

Expand Down Expand Up @@ -509,7 +511,7 @@ export default class TransactionsService {
public static lockScriptToHash = (lock: Script) => {
const binaryHash: string = lock!.binaryHash!
const args: string[] = lock.args!
const lockHash: string = ckbCore.utils.lockScriptToHash({
const lockHash: string = core.utils.lockScriptToHash({
binaryHash,
args,
})
Expand All @@ -522,7 +524,7 @@ export default class TransactionsService {
}

public static addressToLockScript = async (address: string): Promise<Script> => {
const blake160: string = ckbCore.utils.parseAddress(address, ckbCore.utils.AddressPrefix.Testnet, 'hex') as string
const blake160: string = core.utils.parseAddress(address, core.utils.AddressPrefix.Testnet, 'hex') as string
const contractInfo = await TransactionsService.contractInfo()

const lock: Script = {
Expand All @@ -545,10 +547,10 @@ export default class TransactionsService {
}

public static blake160ToAddress = (blake160: string): string => {
return ckbCore.utils.bech32Address(blake160, {
prefix: ckbCore.utils.AddressPrefix.Testnet,
type: ckbCore.utils.AddressType.BinIdx,
binIdx: ckbCore.utils.AddressBinIdx.P2PH,
return core.utils.bech32Address(blake160, {
prefix: core.utils.AddressPrefix.Testnet,
type: core.utils.AddressType.BinIdx,
binIdx: core.utils.AddressBinIdx.P2PH,
})
}
}
10 changes: 6 additions & 4 deletions packages/neuron-wallet/src/services/wallets.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { v4 } from 'uuid'

import ckbCore from '../core'
import TransactionsService from './transactions'
import WalletStore, { WalletData } from '../store/walletStore'
import Key, { Addresses } from '../keys/key'
import { Keystore } from '../keys/keystore'
import nodeService from '../startup/nodeService'

const { core } = nodeService

const walletStore = new WalletStore()

Expand Down Expand Up @@ -85,10 +87,10 @@ export default class WalletService {
const codeHash = '0x0000000000000000000000000000000000000000000000000000000000000001'

const lockhashes = items.map(({ address }) =>
ckbCore.utils.lockScriptToHash({
core.utils.lockScriptToHash({
// TODO: binaryHash has be updated to codeHash with sdk@0.11.0
binaryHash: codeHash,
args: [ckbCore.utils.blake160(address)],
args: [core.utils.blake160(address)],
}),
)
const targetOutputs = items.map(item => ({
Expand All @@ -101,6 +103,6 @@ export default class WalletService {
targetOutputs,
changeAddress,
)) as CKBComponents.RawTransaction
return ckbCore.rpc.sendTransaction(transaction)
return core.rpc.sendTransaction(transaction)
}
}
14 changes: 12 additions & 2 deletions packages/neuron-wallet/src/startup/initApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { distinctUntilChanged } from 'rxjs/operators'
import NetworksController, { NetworksMethod } from '../controllers/networks'
import windowManage from '../utils/windowManage'
import WalletChannel from '../channel/wallet'
import nodeService from '../services/node'
import nodeService from './nodeService'
import { Channel } from '../utils/const'

const syncConnectStatus = () => {
Expand All @@ -21,14 +21,24 @@ const syncConnectStatus = () => {
}

const initApp = async () => {
nodeService.start()
// TODO: this function should be moved to somewhere syncing data
syncConnectStatus()
WalletChannel.start()
const activeId = await NetworksController.service.activeId()
if (!activeId) {
await NetworksController.service.init()
}
if (!nodeService.core.node.url) {
const id = await NetworksController.service.activeId()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use service instead of controller

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I means use service directly, not use controller.service

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I means use service directly, not use controller.service

The service was instantiated in the Controller, you mean instantiating one more here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or just create one somewhere, and controller also use that one

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's better to remove controller in logic level, but we can do this later

@Keith-CY Keith-CY May 12, 2019

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make sense. I'm going to use dependency inject in the future.

const network = await NetworksController.service.get(id || '')
if (network) {
nodeService.setNetwork(network.remote)
} else {
throw new Error('Network not set')
}
}

nodeService.start()
}

export default initApp
3 changes: 3 additions & 0 deletions packages/neuron-wallet/src/startup/nodeService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import NodeService from '../services/node'

export default new NodeService()
5 changes: 3 additions & 2 deletions packages/neuron-wallet/tests/address.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import Addresses from '../src/services/addresses'
import ckbCore from '../src/core'
import nodeService from '../src/startup/nodeService'

const { utils } = nodeService.core

describe('Key tests', () => {
const { utils } = ckbCore
const { AddressPrefix } = utils

it('Generate testnet address from public key', async () => {
Expand Down