Skip to content

Commit

Permalink
Cache most recent account balances in the account-tracker
Browse files Browse the repository at this point in the history
  • Loading branch information
danjm committed Nov 28, 2018
1 parent 18531fe commit 929bd56
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 3 deletions.
20 changes: 17 additions & 3 deletions app/scripts/lib/account-tracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class AccountTracker {
constructor (opts = {}) {
const initState = {
accounts: {},
cachedAccountBalances: {},
currentBlockGasLimit: '',
}
this.store = new ObservableStore(initState)
Expand Down Expand Up @@ -184,12 +185,25 @@ class AccountTracker {
// query balance
const balance = await this._query.getBalance(address)
const result = { address, balance }
// update accounts state
const { accounts } = this.store.getState()
// update accounts and cachedAccountBalances state
const { accounts, cachedAccountBalances } = this.store.getState()
// only populate if the entry is still present
if (!accounts[address]) return
accounts[address] = result
this.store.updateState({ accounts })
this.store.updateState({
accounts,
cachedAccountBalances: this._generateAccountBalancesToCache(result, cachedAccountBalances),
})
}

_generateAccountBalancesToCache ({ address, balance }, cachedAccountBalances) {
const accountBalancesToCache = { ...cachedAccountBalances }

if (balance !== null && balance !== undefined) {
accountBalancesToCache[address] = balance
}

return accountBalancesToCache
}

}
Expand Down
42 changes: 42 additions & 0 deletions app/scripts/migrations/030.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// next version number
const version = 30

/*
Adds cachedAccountBalances to the account tracker.
*/

const clone = require('clone')

module.exports = {
version,

migrate: async function (originalVersionedData) {
const versionedData = clone(originalVersionedData)
versionedData.meta.version = version
const state = versionedData.data
const newState = transformState(state)
versionedData.data = newState
return versionedData
},
}

function transformState (state) {
if (!state.AccountTracker) {
return state
}

const cachedAccountBalances = {}
const accounts = state.AccountTracker.accounts

let balance
for (const accountId in state.AccountTracker.accounts) {
balance = accounts[accountId].balance
if (balance !== null && balance !== undefined) {
cachedAccountBalances[accountId] = balance
}
}
state.AccountTracker.cachedAccountBalances = cachedAccountBalances
return state
}
1 change: 1 addition & 0 deletions app/scripts/migrations/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,5 @@ module.exports = [
require('./027'),
require('./028'),
require('./029'),
require('./030'),
]

0 comments on commit 929bd56

Please sign in to comment.