Skip to content

Commit

Permalink
Merge pull request #338 from poanetwork/vb-eip-1193-final
Browse files Browse the repository at this point in the history
Refactoring #2 before EIP - 1193
  • Loading branch information
vbaranov authored Mar 27, 2020
2 parents 9ed5e6d + e48397c commit f9a9162
Show file tree
Hide file tree
Showing 37 changed files with 1,538 additions and 198 deletions.
18 changes: 9 additions & 9 deletions app/scripts/controllers/balance.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const ObservableStore = require('obs-store')
const PendingBalanceCalculator = require('../lib/pending-balance-calculator')
const BN = require('ethereumjs-util').BN
import ObservableStore from 'obs-store'
import PendingBalanceCalculator from '../lib/pending-balance-calculator'
import { BN } from 'ethereumjs-util'

class BalanceController {

/**
* Controller responsible for storing and updating an account's balance.
*
* @typedef {Object} BalanceController
* @param {Object} opts Initialize various properties of the class.
* @param {Object} opts - Initialize various properties of the class.
* @property {string} address A base 16 hex string. The account address which has the balance managed by this
* BalanceController.
* @property {AccountTracker} accountTracker Stores and updates the users accounts
Expand Down Expand Up @@ -47,7 +47,7 @@ class BalanceController {
/**
* Updates the ethBalance property to the current pending balance
*
* @returns {Promise<void>} Promises undefined
* @returns {Promise<void>} - Promises undefined
*/
async updateBalance () {
const balance = await this.balanceCalc.getBalance()
Expand All @@ -68,7 +68,7 @@ class BalanceController {
_registerUpdates () {
const update = this.updateBalance.bind(this)

this.txController.on('tx:status-update', (txId, status) => {
this.txController.on('tx:status-update', (_, status) => {
switch (status) {
case 'submitted':
case 'confirmed':
Expand All @@ -87,7 +87,7 @@ class BalanceController {
* Gets the balance, as a base 16 hex string, of the account at this BalanceController's current address.
* If the current account has no balance, returns undefined.
*
* @returns {Promise<BN|void>} Promises a BN with a value equal to the balance of the current account, or undefined
* @returns {Promise<BN|void>} - Promises a BN with a value equal to the balance of the current account, or undefined
* if the current account has no balance
*
*/
Expand All @@ -103,7 +103,7 @@ class BalanceController {
* TransactionController passed to this BalanceController during construction.
*
* @private
* @returns {Promise<array>} Promises an array of transaction objects.
* @returns {Promise<array>} - Promises an array of transaction objects.
*
*/
async _getPendingTransactions () {
Expand All @@ -118,7 +118,7 @@ class BalanceController {
/**
* Validates that the passed options have all required properties.
*
* @param {Object} opts The options object to validate
* @param {Object} opts - The options object to validate
* @throws {string} Throw a custom error indicating that address, accountTracker, txController and blockTracker are
* missing and at least one is required
*
Expand Down
59 changes: 48 additions & 11 deletions app/scripts/controllers/network/createInfuraClient.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
const mergeMiddleware = require('json-rpc-engine/src/mergeMiddleware')
const createBlockReRefMiddleware = require('eth-json-rpc-middleware/block-ref')
const createRetryOnEmptyMiddleware = require('eth-json-rpc-middleware/retryOnEmpty')
const createBlockCacheMiddleware = require('eth-json-rpc-middleware/block-cache')
const createInflightMiddleware = require('eth-json-rpc-middleware/inflight-cache')
const createBlockTrackerInspectorMiddleware = require('eth-json-rpc-middleware/block-tracker-inspector')
const providerFromMiddleware = require('eth-json-rpc-middleware/providerFromMiddleware')
const createInfuraMiddleware = require('eth-json-rpc-infura')
const BlockTracker = require('eth-block-tracker')
import mergeMiddleware from 'json-rpc-engine/src/mergeMiddleware'
import createScaffoldMiddleware from 'json-rpc-engine/src/createScaffoldMiddleware'
import createBlockReRefMiddleware from 'eth-json-rpc-middleware/block-ref'
import createRetryOnEmptyMiddleware from 'eth-json-rpc-middleware/retryOnEmpty'
import createBlockCacheMiddleware from 'eth-json-rpc-middleware/block-cache'
import createInflightMiddleware from 'eth-json-rpc-middleware/inflight-cache'
import createBlockTrackerInspectorMiddleware from 'eth-json-rpc-middleware/block-tracker-inspector'
import providerFromMiddleware from 'eth-json-rpc-middleware/providerFromMiddleware'
import createInfuraMiddleware from 'eth-json-rpc-infura'
import BlockTracker from 'eth-block-tracker'

module.exports = createInfuraClient
export default createInfuraClient

function createInfuraClient ({ network }) {
const infuraMiddleware = createInfuraMiddleware({ network })
const infuraMiddleware = createInfuraMiddleware({ network, maxAttempts: 5, source: 'metamask' })
const infuraProvider = providerFromMiddleware(infuraMiddleware)
const blockTracker = new BlockTracker({ provider: infuraProvider })

const networkMiddleware = mergeMiddleware([
createNetworkAndChainIdMiddleware({ network }),
createBlockCacheMiddleware({ blockTracker }),
createInflightMiddleware(),
createBlockReRefMiddleware({ blockTracker, provider: infuraProvider }),
Expand All @@ -25,3 +27,38 @@ function createInfuraClient ({ network }) {
])
return { networkMiddleware, blockTracker }
}

function createNetworkAndChainIdMiddleware ({ network }) {
let chainId
let netId

switch (network) {
case 'mainnet':
netId = '1'
chainId = '0x01'
break
case 'ropsten':
netId = '3'
chainId = '0x03'
break
case 'rinkeby':
netId = '4'
chainId = '0x04'
break
case 'kovan':
netId = '42'
chainId = '0x2a'
break
case 'goerli':
netId = '5'
chainId = '0x05'
break
default:
throw new Error(`createInfuraClient - unknown network "${network}"`)
}

return createScaffoldMiddleware({
eth_chainId: chainId,
net_version: netId,
})
}
18 changes: 9 additions & 9 deletions app/scripts/controllers/network/createJsonRpcClient.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
const mergeMiddleware = require('json-rpc-engine/src/mergeMiddleware')
const createFetchMiddleware = require('eth-json-rpc-middleware/fetch')
const createBlockRefRewriteMiddleware = require('eth-json-rpc-middleware/block-ref-rewrite')
const createBlockCacheMiddleware = require('eth-json-rpc-middleware/block-cache')
const createInflightMiddleware = require('eth-json-rpc-middleware/inflight-cache')
const createBlockTrackerInspectorMiddleware = require('eth-json-rpc-middleware/block-tracker-inspector')
const providerFromMiddleware = require('eth-json-rpc-middleware/providerFromMiddleware')
const BlockTracker = require('eth-block-tracker')
import mergeMiddleware from 'json-rpc-engine/src/mergeMiddleware'
import createFetchMiddleware from 'eth-json-rpc-middleware/fetch'
import createBlockRefRewriteMiddleware from 'eth-json-rpc-middleware/block-ref-rewrite'
import createBlockCacheMiddleware from 'eth-json-rpc-middleware/block-cache'
import createInflightMiddleware from 'eth-json-rpc-middleware/inflight-cache'
import createBlockTrackerInspectorMiddleware from 'eth-json-rpc-middleware/block-tracker-inspector'
import providerFromMiddleware from 'eth-json-rpc-middleware/providerFromMiddleware'
import BlockTracker from 'eth-block-tracker'

module.exports = createJsonRpcClient
export default createJsonRpcClient

function createJsonRpcClient ({ rpcUrl }) {
const fetchMiddleware = createFetchMiddleware({ rpcUrl })
Expand Down
18 changes: 9 additions & 9 deletions app/scripts/controllers/network/createLocalhostClient.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const mergeMiddleware = require('json-rpc-engine/src/mergeMiddleware')
const createFetchMiddleware = require('eth-json-rpc-middleware/fetch')
const createBlockRefRewriteMiddleware = require('eth-json-rpc-middleware/block-ref-rewrite')
const createBlockTrackerInspectorMiddleware = require('eth-json-rpc-middleware/block-tracker-inspector')
const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware')
const providerFromMiddleware = require('eth-json-rpc-middleware/providerFromMiddleware')
const BlockTracker = require('eth-block-tracker')
import mergeMiddleware from 'json-rpc-engine/src/mergeMiddleware'
import createFetchMiddleware from 'eth-json-rpc-middleware/fetch'
import createBlockRefRewriteMiddleware from 'eth-json-rpc-middleware/block-ref-rewrite'
import createBlockTrackerInspectorMiddleware from 'eth-json-rpc-middleware/block-tracker-inspector'
import createAsyncMiddleware from 'json-rpc-engine/src/createAsyncMiddleware'
import providerFromMiddleware from 'eth-json-rpc-middleware/providerFromMiddleware'
import BlockTracker from 'eth-block-tracker'

const inTest = process.env.IN_TEST === 'true'

module.exports = createLocalhostClient
export default createLocalhostClient

function createLocalhostClient () {
const fetchMiddleware = createFetchMiddleware({ rpcUrl: 'http://localhost:8545/' })
Expand All @@ -25,7 +25,7 @@ function createLocalhostClient () {
}

function delay (time) {
return new Promise(resolve => setTimeout(resolve, time))
return new Promise((resolve) => setTimeout(resolve, time))
}


Expand Down
28 changes: 13 additions & 15 deletions app/scripts/controllers/network/createMetamaskMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
const mergeMiddleware = require('json-rpc-engine/src/mergeMiddleware')
const createScaffoldMiddleware = require('json-rpc-engine/src/createScaffoldMiddleware')
const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware')
const createWalletSubprovider = require('eth-json-rpc-middleware/wallet')
import mergeMiddleware from 'json-rpc-engine/src/mergeMiddleware'
import createScaffoldMiddleware from 'json-rpc-engine/src/createScaffoldMiddleware'
import createWalletSubprovider from 'eth-json-rpc-middleware/wallet'
import { createPendingNonceMiddleware } from './middleware/pending'

module.exports = createMetamaskMiddleware
export default createMetamaskMiddleware

function createMetamaskMiddleware ({
version,
getAccounts,
processTransaction,
processEthSignMessage,
processTypedMessage,
processTypedMessageV3,
processTypedMessageV4,
processPersonalMessage,
processDecryptMessage,
processEncryptionPublicKey,
getPendingNonce,
}) {
const metamaskMiddleware = mergeMiddleware([
Expand All @@ -25,19 +29,13 @@ function createMetamaskMiddleware ({
processTransaction,
processEthSignMessage,
processTypedMessage,
processTypedMessageV3,
processTypedMessageV4,
processPersonalMessage,
processDecryptMessage,
processEncryptionPublicKey,
}),
createPendingNonceMiddleware({ getPendingNonce }),
])
return metamaskMiddleware
}

function createPendingNonceMiddleware ({ getPendingNonce }) {
return createAsyncMiddleware(async (req, res, next) => {
if (req.method !== 'eth_getTransactionCount') return next()
const address = req.params[0]
const blockRef = req.params[1]
if (blockRef !== 'pending') return next()
res.result = await getPendingNonce(address)
})
}
31 changes: 31 additions & 0 deletions app/scripts/controllers/network/middleware/pending.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const { formatTxMetaForRpcResult } = require('../util')
import createAsyncMiddleware from 'json-rpc-engine/src/createAsyncMiddleware'

export function createPendingNonceMiddleware ({ getPendingNonce }) {
return createAsyncMiddleware(async (req, res, next) => {
const { method, params } = req
if (method !== 'eth_getTransactionCount') {
return next()
}
const [param, blockRef] = params
if (blockRef !== 'pending') {
return next()
}
res.result = await getPendingNonce(param)
})
}

export function createPendingTxMiddleware ({ getPendingTransactionByHash }) {
return createAsyncMiddleware(async (req, res, next) => {
const { method, params } = req
if (method !== 'eth_getTransactionByHash') {
return next()
}
const [hash] = params
const txMeta = getPendingTransactionByHash(hash)
if (!txMeta) {
return next()
}
res.result = formatTxMetaForRpcResult(txMeta)
})
}
48 changes: 23 additions & 25 deletions app/scripts/controllers/network/network.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
const assert = require('assert')
const EventEmitter = require('events')
const ObservableStore = require('obs-store')
const ComposedStore = require('obs-store/lib/composed')
const EthQuery = require('eth-query')
const JsonRpcEngine = require('json-rpc-engine')
const providerFromEngine = require('eth-json-rpc-middleware/providerFromEngine')
const log = require('loglevel')
const createMetamaskMiddleware = require('./createMetamaskMiddleware')
const createInfuraClient = require('./createInfuraClient')
const createJsonRpcClient = require('./createJsonRpcClient')
const createLocalhostClient = require('./createLocalhostClient')
import assert from 'assert'
import EventEmitter from 'events'
import ObservableStore from 'obs-store'
import ComposedStore from 'obs-store/lib/composed'
import EthQuery from 'eth-query'
import JsonRpcEngine from 'json-rpc-engine'
import providerFromEngine from 'eth-json-rpc-middleware/providerFromEngine'
import log from 'loglevel'
import createMetamaskMiddleware from './createMetamaskMiddleware'
import createInfuraClient from './createInfuraClient'
import createJsonRpcClient from './createJsonRpcClient'
import createLocalhostClient from './createLocalhostClient'
const createPocketClient = require('./createPocketClient')
const { createSwappableProxy, createEventEmitterProxy } = require('swappable-obj-proxy')
const ethNetProps = require('eth-net-props')
const parse = require('url-parse')
const extend = require('extend')
import parse from 'url-parse'
const networks = { networkList: {} }
const { isKnownProvider, getDPath } = require('../../../../old-ui/app/util')

Expand Down Expand Up @@ -75,7 +74,7 @@ module.exports = class NetworkController extends EventEmitter {
this.networkStore = new ObservableStore('loading')
this.dProviderStore = new ObservableStore({dProvider: false})
this.networkConfig = new ObservableStore(defaultNetworkConfig)
this.store = new ComposedStore({ provider: this.providerStore, network: this.networkStore, dProviderStore: this.dProviderStore })
this.store = new ComposedStore({ provider: this.providerStore, network: this.networkStore, settings: this.networkConfig, dProviderStore: this.dProviderStore })
this.on('networkDidChange', this.lookupNetwork)
// provider and block tracker
this._provider = null
Expand All @@ -101,7 +100,9 @@ module.exports = class NetworkController extends EventEmitter {

verifyNetwork () {
// Check network when restoring connectivity:
if (this.isNetworkLoading()) this.lookupNetwork()
if (this.isNetworkLoading()) {
this.lookupNetwork()
}
}

getNetworkState () {
Expand Down Expand Up @@ -253,10 +254,12 @@ module.exports = class NetworkController extends EventEmitter {

_configureInfuraProvider ({ type }) {
log.info('NetworkController - configureInfuraProvider', type)
const networkClient = createInfuraClient({ network: type })
const networkClient = createInfuraClient({
network: type,
})
this._setNetworkClient(networkClient)
// setup networkConfig
var settings = {
const settings = {
ticker: 'ETH',
}
this.networkConfig.putState(settings)
Expand Down Expand Up @@ -285,10 +288,10 @@ module.exports = class NetworkController extends EventEmitter {
nickname,
}
// setup networkConfig
var settings = {
let settings = {
network: chainId,
}
settings = extend(settings, networks.networkList['rpc'])
settings = Object.assign(settings, networks.networkList['rpc'])
this.networkConfig.putState(settings)
this._setNetworkClient(networkClient)
}
Expand Down Expand Up @@ -318,9 +321,4 @@ module.exports = class NetworkController extends EventEmitter {
this._provider = provider
this._blockTracker = blockTracker
}

_logBlock (block) {
log.info(`BLOCK CHANGED: #${block.number.toString('hex')} 0x${block.hash.toString('hex')}`)
this.verifyNetwork()
}
}
20 changes: 20 additions & 0 deletions app/scripts/controllers/network/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,27 @@ networks[RSK_TESTNET] = RSK_TESTNET_OBJ

const getNetworkDisplayName = key => networks[key].displayName

function formatTxMetaForRpcResult (txMeta) {
return {
'blockHash': txMeta.txReceipt ? txMeta.txReceipt.blockHash : null,
'blockNumber': txMeta.txReceipt ? txMeta.txReceipt.blockNumber : null,
'from': txMeta.txParams.from,
'gas': txMeta.txParams.gas,
'gasPrice': txMeta.txParams.gasPrice,
'hash': txMeta.hash,
'input': txMeta.txParams.data || '0x',
'nonce': txMeta.txParams.nonce,
'to': txMeta.txParams.to,
'transactionIndex': txMeta.txReceipt ? txMeta.txReceipt.transactionIndex : null,
'value': txMeta.txParams.value || '0x0',
'v': txMeta.v,
'r': txMeta.r,
's': txMeta.s,
}
}

module.exports = {
networks,
getNetworkDisplayName,
formatTxMetaForRpcResult,
}
Loading

0 comments on commit f9a9162

Please sign in to comment.