aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts
diff options
context:
space:
mode:
authorDan Finlay <dan@danfinlay.com>2017-09-23 05:30:31 +0800
committerDan Finlay <dan@danfinlay.com>2017-09-23 05:30:31 +0800
commitaa2abc00eb86c1cb746a59a6e307a6bc255e6466 (patch)
treec6056fb31ac0c79bfebc5e36d7dd56e8cabfd543 /app/scripts
parent08b36b9b582853b411a19e48b407c70596381f61 (diff)
parentf128240e7f877280fa59bf22f2ea8285bb467022 (diff)
downloadtangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.gz
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.bz2
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.lz
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.xz
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.tar.zst
tangerine-wallet-browser-aa2abc00eb86c1cb746a59a6e307a6bc255e6466.zip
Merge branch 'AddBalanceController' into BreakOutKeyringController
Diffstat (limited to 'app/scripts')
-rw-r--r--app/scripts/controllers/balance.js60
-rw-r--r--app/scripts/controllers/computed-balances.js64
-rw-r--r--app/scripts/controllers/transactions.js7
-rw-r--r--app/scripts/keyring-controller.js9
-rw-r--r--app/scripts/lib/account-tracker.js (renamed from app/scripts/lib/eth-store.js)46
-rw-r--r--app/scripts/lib/pending-balance-calculator.js53
-rw-r--r--app/scripts/metamask-controller.js36
7 files changed, 217 insertions, 58 deletions
diff --git a/app/scripts/controllers/balance.js b/app/scripts/controllers/balance.js
new file mode 100644
index 000000000..ddeb06cf9
--- /dev/null
+++ b/app/scripts/controllers/balance.js
@@ -0,0 +1,60 @@
+const ObservableStore = require('obs-store')
+const PendingBalanceCalculator = require('../lib/pending-balance-calculator')
+const BN = require('ethereumjs-util').BN
+
+class BalanceController {
+
+ constructor (opts = {}) {
+ const { address, accountTracker, txController } = opts
+ this.address = address
+ this.accountTracker = accountTracker
+ this.txController = txController
+
+ const initState = {
+ ethBalance: undefined,
+ }
+ this.store = new ObservableStore(initState)
+
+ this.balanceCalc = new PendingBalanceCalculator({
+ getBalance: () => Promise.resolve(this._getBalance()),
+ getPendingTransactions: this._getPendingTransactions.bind(this),
+ })
+
+ this.registerUpdates()
+ }
+
+ async updateBalance () {
+ const balance = await this.balanceCalc.getBalance()
+ this.store.updateState({
+ ethBalance: balance,
+ })
+ }
+
+ registerUpdates () {
+ const update = this.updateBalance.bind(this)
+ this.txController.on('submitted', update)
+ this.txController.on('confirmed', update)
+ this.txController.on('failed', update)
+ this.txController.blockTracker.on('block', update)
+ }
+
+ _getBalance () {
+ const store = this.accountTracker.getState()
+ const balances = store.accounts
+ const entry = balances[this.address]
+ const balance = entry.balance
+ return balance ? new BN(balance.substring(2), 16) : undefined
+ }
+
+ _getPendingTransactions () {
+ const pending = this.txController.getFilteredTxList({
+ from: this.address,
+ status: 'submitted',
+ err: undefined,
+ })
+ return Promise.resolve(pending)
+ }
+
+}
+
+module.exports = BalanceController
diff --git a/app/scripts/controllers/computed-balances.js b/app/scripts/controllers/computed-balances.js
new file mode 100644
index 000000000..576746164
--- /dev/null
+++ b/app/scripts/controllers/computed-balances.js
@@ -0,0 +1,64 @@
+const ObservableStore = require('obs-store')
+const extend = require('xtend')
+const BalanceController = require('./balance')
+
+class ComputedbalancesController {
+
+ constructor (opts = {}) {
+ const { accountTracker, txController } = opts
+ this.accountTracker = accountTracker
+ this.txController = txController
+
+ const initState = extend({
+ computedBalances: {},
+ }, opts.initState)
+ this.store = new ObservableStore(initState)
+ this.balances = {}
+
+ this._initBalanceUpdating()
+ }
+
+ updateAllBalances () {
+ for (let address in this.balances) {
+ this.balances[address].updateBalance()
+ }
+ }
+
+ _initBalanceUpdating () {
+ const store = this.accountTracker.getState()
+ this.addAnyAccountsFromStore(store)
+ this.accountTracker.subscribe(this.addAnyAccountsFromStore.bind(this))
+ }
+
+ addAnyAccountsFromStore(store) {
+ const balances = store.accounts
+
+ for (let address in balances) {
+ this.trackAddressIfNotAlready(address)
+ }
+ }
+
+ trackAddressIfNotAlready (address) {
+ const state = this.store.getState()
+ if (!(address in state.computedBalances)) {
+ this.trackAddress(address)
+ }
+ }
+
+ trackAddress (address) {
+ let updater = new BalanceController({
+ address,
+ accountTracker: this.accountTracker,
+ txController: this.txController,
+ })
+ updater.store.subscribe((accountBalance) => {
+ let newState = this.store.getState()
+ newState.computedBalances[address] = accountBalance
+ this.store.updateState(newState)
+ })
+ this.balances[address] = updater
+ updater.updateBalance()
+ }
+}
+
+module.exports = ComputedbalancesController
diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js
index fb3be6073..2aff4e5ff 100644
--- a/app/scripts/controllers/transactions.js
+++ b/app/scripts/controllers/transactions.js
@@ -22,7 +22,7 @@ module.exports = class TransactionController extends EventEmitter {
this.provider = opts.provider
this.blockTracker = opts.blockTracker
this.signEthTx = opts.signTransaction
- this.ethStore = opts.ethStore
+ this.accountTracker = opts.accountTracker
this.nonceTracker = new NonceTracker({
provider: this.provider,
@@ -52,7 +52,7 @@ module.exports = class TransactionController extends EventEmitter {
provider: this.provider,
nonceTracker: this.nonceTracker,
getBalance: (address) => {
- const account = this.ethStore.getState().accounts[address]
+ const account = this.accountTracker.getState().accounts[address]
if (!account) return
return account.balance
},
@@ -73,7 +73,7 @@ module.exports = class TransactionController extends EventEmitter {
this.blockTracker.on('rawBlock', this.pendingTxTracker.checkForTxInBlock.bind(this.pendingTxTracker))
// this is a little messy but until ethstore has been either
// removed or redone this is to guard against the race condition
- // where ethStore hasent been populated by the results yet
+ // where accountTracker hasent been populated by the results yet
this.blockTracker.once('latest', () => {
this.blockTracker.on('latest', this.pendingTxTracker.resubmitPendingTxs.bind(this.pendingTxTracker))
})
@@ -434,6 +434,7 @@ module.exports = class TransactionController extends EventEmitter {
const txMeta = this.getTx(txId)
txMeta.status = status
this.emit(`${txMeta.id}:${status}`, txId)
+ this.emit(`${status}`, txId)
if (status === 'submitted' || status === 'rejected') {
this.emit(`${txMeta.id}:finished`, txMeta)
}
diff --git a/app/scripts/keyring-controller.js b/app/scripts/keyring-controller.js
index 4454f0b63..fb60a5b3e 100644
--- a/app/scripts/keyring-controller.js
+++ b/app/scripts/keyring-controller.js
@@ -35,7 +35,6 @@ class KeyringController extends EventEmitter {
keyrings: [],
identities: {},
})
- this.ethStore = opts.ethStore
this.encryptor = opts.encryptor || encryptor
this.keyrings = []
this.getNetwork = opts.getNetwork
@@ -338,7 +337,7 @@ class KeyringController extends EventEmitter {
//
// Initializes the provided account array
// Gives them numerically incremented nicknames,
- // and adds them to the ethStore for regular balance checking.
+ // and adds them to the accountTracker for regular balance checking.
setupAccounts (accounts) {
return this.getAccounts()
.then((loadedAccounts) => {
@@ -361,7 +360,7 @@ class KeyringController extends EventEmitter {
throw new Error('Problem loading account.')
}
const address = normalizeAddress(account)
- this.ethStore.addAccount(address)
+ this.accountTracker.addAccount(address)
return this.createNickname(address)
}
@@ -567,12 +566,12 @@ class KeyringController extends EventEmitter {
clearKeyrings () {
let accounts
try {
- accounts = Object.keys(this.ethStore.getState())
+ accounts = Object.keys(this.accountTracker.getState())
} catch (e) {
accounts = []
}
accounts.forEach((address) => {
- this.ethStore.removeAccount(address)
+ this.accountTracker.removeAccount(address)
})
// clear keyrings from memory
diff --git a/app/scripts/lib/eth-store.js b/app/scripts/lib/account-tracker.js
index ebba98f5c..bf949597b 100644
--- a/app/scripts/lib/eth-store.js
+++ b/app/scripts/lib/account-tracker.js
@@ -1,4 +1,4 @@
-/* Ethereum Store
+/* Account Tracker
*
* This module is responsible for tracking any number of accounts
* and caching their current balances & transaction counts.
@@ -18,10 +18,6 @@ class EthereumStore extends ObservableStore {
constructor (opts = {}) {
super({
accounts: {},
- transactions: {},
- currentBlockNumber: '0',
- currentBlockHash: '',
- currentBlockGasLimit: '',
})
this._provider = opts.provider
this._query = new EthQuery(this._provider)
@@ -50,21 +46,6 @@ class EthereumStore extends ObservableStore {
this.updateState({ accounts })
}
- addTransaction (txHash) {
- const transactions = this.getState().transactions
- transactions[txHash] = {}
- this.updateState({ transactions })
- if (!this._currentBlockNumber) return
- this._updateTransaction(this._currentBlockNumber, txHash, noop)
- }
-
- removeTransaction (txHash) {
- const transactions = this.getState().transactions
- delete transactions[txHash]
- this.updateState({ transactions })
- }
-
-
//
// private
//
@@ -72,12 +53,9 @@ class EthereumStore extends ObservableStore {
_updateForBlock (block) {
const blockNumber = '0x' + block.number.toString('hex')
this._currentBlockNumber = blockNumber
- this.updateState({ currentBlockNumber: parseInt(blockNumber) })
- this.updateState({ currentBlockHash: `0x${block.hash.toString('hex')}`})
- this.updateState({ currentBlockGasLimit: `0x${block.gasLimit.toString('hex')}` })
+
async.parallel([
this._updateAccounts.bind(this),
- this._updateTransactions.bind(this, blockNumber),
], (err) => {
if (err) return console.error(err)
this.emit('block', this.getState())
@@ -104,26 +82,6 @@ class EthereumStore extends ObservableStore {
})
}
- _updateTransactions (block, cb = noop) {
- const transactions = this.getState().transactions
- const txHashes = Object.keys(transactions)
- async.each(txHashes, this._updateTransaction.bind(this, block), cb)
- }
-
- _updateTransaction (block, txHash, cb = noop) {
- // would use the block here to determine how many confirmations the tx has
- const transactions = this.getState().transactions
- this._query.getTransaction(txHash, (err, result) => {
- if (err) return cb(err)
- // only populate if the entry is still present
- if (transactions[txHash]) {
- transactions[txHash] = result
- this.updateState({ transactions })
- }
- cb(null, result)
- })
- }
-
_getAccount (address, cb = noop) {
const query = this._query
async.parallel({
diff --git a/app/scripts/lib/pending-balance-calculator.js b/app/scripts/lib/pending-balance-calculator.js
new file mode 100644
index 000000000..c66bffbbb
--- /dev/null
+++ b/app/scripts/lib/pending-balance-calculator.js
@@ -0,0 +1,53 @@
+const BN = require('ethereumjs-util').BN
+const normalize = require('eth-sig-util').normalize
+
+class PendingBalanceCalculator {
+
+ // Must be initialized with two functions:
+ // getBalance => Returns a promise of a BN of the current balance in Wei
+ // getPendingTransactions => Returns an array of TxMeta Objects,
+ // which have txParams properties, which include value, gasPrice, and gas,
+ // all in a base=16 hex format.
+ constructor ({ getBalance, getPendingTransactions }) {
+ this.getPendingTransactions = getPendingTransactions
+ this.getNetworkBalance = getBalance
+ }
+
+ async getBalance() {
+ const results = await Promise.all([
+ this.getNetworkBalance(),
+ this.getPendingTransactions(),
+ ])
+
+ const balance = results[0]
+ const pending = results[1]
+
+ if (!balance) return undefined
+
+ const pendingValue = pending.reduce((total, tx) => {
+ return total.add(this.valueFor(tx))
+ }, new BN(0))
+
+ return `0x${balance.sub(pendingValue).toString(16)}`
+ }
+
+ valueFor (tx) {
+ const txValue = tx.txParams.value
+ const value = this.hexToBn(txValue)
+ const gasPrice = this.hexToBn(tx.txParams.gasPrice)
+
+ const gas = tx.txParams.gas
+ const gasLimit = tx.txParams.gasLimit
+ const gasLimitBn = this.hexToBn(gas || gasLimit)
+
+ const gasCost = gasPrice.mul(gasLimitBn)
+ return value.add(gasCost)
+ }
+
+ hexToBn (hex) {
+ return new BN(normalize(hex).substring(2), 16)
+ }
+
+}
+
+module.exports = PendingBalanceCalculator
diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 42248827f..30e511e19 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -4,7 +4,7 @@ const promiseToCallback = require('promise-to-callback')
const pump = require('pump')
const Dnode = require('dnode')
const ObservableStore = require('obs-store')
-const EthStore = require('./lib/eth-store')
+const AccountTracker = require('./lib/account-tracker')
const EthQuery = require('eth-query')
const RpcEngine = require('json-rpc-engine')
const debounce = require('debounce')
@@ -26,6 +26,7 @@ const BlacklistController = require('./controllers/blacklist')
const MessageManager = require('./lib/message-manager')
const PersonalMessageManager = require('./lib/personal-message-manager')
const TransactionController = require('./controllers/transactions')
+const BalancesController = require('./controllers/computed-balances')
const ConfigManager = require('./lib/config-manager')
const nodeify = require('./lib/nodeify')
const accountImporter = require('./account-import-strategies')
@@ -85,7 +86,7 @@ module.exports = class MetamaskController extends EventEmitter {
// eth data query tools
this.ethQuery = new EthQuery(this.provider)
- this.ethStore = new EthStore({
+ this.accountTracker = new AccountTracker({
provider: this.provider,
blockTracker: this.blockTracker,
})
@@ -93,12 +94,22 @@ module.exports = class MetamaskController extends EventEmitter {
// key mgmt
this.keyringController = new KeyringController({
initState: initState.KeyringController,
- ethStore: this.ethStore,
+ accountTracker: this.accountTracker,
getNetwork: this.networkController.getNetworkState.bind(this.networkController),
encryptor: opts.encryptor || undefined,
})
+
+ // account tracker watches balances, nonces, and any code at their address.
+ this.accountTracker = new AccountTracker({
+ provider: this.provider,
+ blockTracker: this.provider,
+ })
this.keyringController.on('newAccount', (address) => {
this.preferencesController.setSelectedAddress(address)
+ this.accountTracker.addAccount(address)
+ })
+ this.keyringController.on('removedAccount', (address) => {
+ this.accountTracker.removeAccount(address)
})
// address book controller
@@ -117,10 +128,20 @@ module.exports = class MetamaskController extends EventEmitter {
provider: this.provider,
blockTracker: this.blockTracker,
ethQuery: this.ethQuery,
- ethStore: this.ethStore,
+ accountTracker: this.accountTracker,
})
this.txController.on('newUnaprovedTx', opts.showUnapprovedTx.bind(opts))
+ // computed balances (accounting for pending transactions)
+ this.balancesController = new BalancesController({
+ accountTracker: this.accountTracker,
+ txController: this.txController,
+ })
+ this.networkController.on('networkDidChange', () => {
+ this.balancesController.updateAllBalances()
+ })
+ this.balancesController.updateAllBalances()
+
// notices
this.noticeController = new NoticeController({
initState: initState.NoticeController,
@@ -172,8 +193,9 @@ module.exports = class MetamaskController extends EventEmitter {
// manual mem state subscriptions
this.networkController.store.subscribe(this.sendUpdate.bind(this))
- this.ethStore.subscribe(this.sendUpdate.bind(this))
+ this.accountTracker.subscribe(this.sendUpdate.bind(this))
this.txController.memStore.subscribe(this.sendUpdate.bind(this))
+ this.balancesController.store.subscribe(this.sendUpdate.bind(this))
this.messageManager.memStore.subscribe(this.sendUpdate.bind(this))
this.personalMessageManager.memStore.subscribe(this.sendUpdate.bind(this))
this.keyringController.memStore.subscribe(this.sendUpdate.bind(this))
@@ -248,16 +270,18 @@ module.exports = class MetamaskController extends EventEmitter {
const wallet = this.configManager.getWallet()
const vault = this.keyringController.store.getState().vault
const isInitialized = (!!wallet || !!vault)
+
return extend(
{
isInitialized,
},
this.networkController.store.getState(),
- this.ethStore.getState(),
+ this.accountTracker.getState(),
this.txController.memStore.getState(),
this.messageManager.memStore.getState(),
this.personalMessageManager.memStore.getState(),
this.keyringController.memStore.getState(),
+ this.balancesController.store.getState(),
this.preferencesController.store.getState(),
this.addressBookController.store.getState(),
this.currencyController.store.getState(),