aboutsummaryrefslogtreecommitdiffstats
path: root/app/scripts/controllers
diff options
context:
space:
mode:
Diffstat (limited to 'app/scripts/controllers')
-rw-r--r--app/scripts/controllers/detect-tokens.js130
-rw-r--r--app/scripts/controllers/network/enums.js3
-rw-r--r--app/scripts/controllers/preferences.js24
-rw-r--r--app/scripts/controllers/transactions/nonce-tracker.js13
-rw-r--r--app/scripts/controllers/transactions/tx-state-manager.js6
5 files changed, 162 insertions, 14 deletions
diff --git a/app/scripts/controllers/detect-tokens.js b/app/scripts/controllers/detect-tokens.js
new file mode 100644
index 000000000..195ec918a
--- /dev/null
+++ b/app/scripts/controllers/detect-tokens.js
@@ -0,0 +1,130 @@
+const Web3 = require('web3')
+const contracts = require('eth-contract-metadata')
+const { warn } = require('loglevel')
+const { MAINNET } = require('./network/enums')
+// By default, poll every 3 minutes
+const DEFAULT_INTERVAL = 180 * 1000
+const ERC20_ABI = [{'constant': true, 'inputs': [{'name': '_owner', 'type': 'address'}], 'name': 'balanceOf', 'outputs': [{'name': 'balance', 'type': 'uint256'}], 'payable': false, 'type': 'function'}]
+
+/**
+ * A controller that polls for token exchange
+ * rates based on a user's current token list
+ */
+class DetectTokensController {
+ /**
+ * Creates a DetectTokensController
+ *
+ * @param {Object} [config] - Options to configure controller
+ */
+ constructor ({ interval = DEFAULT_INTERVAL, preferences, network, keyringMemStore } = {}) {
+ this.preferences = preferences
+ this.interval = interval
+ this.network = network
+ this.keyringMemStore = keyringMemStore
+ }
+
+ /**
+ * For each token in eth-contract-metada, find check selectedAddress balance.
+ *
+ */
+ async detectNewTokens () {
+ if (!this.isActive) { return }
+ if (this._network.store.getState().provider.type !== MAINNET) { return }
+ this.web3.setProvider(this._network._provider)
+ for (const contractAddress in contracts) {
+ if (contracts[contractAddress].erc20 && !(this.tokenAddresses.includes(contractAddress.toLowerCase()))) {
+ this.detectTokenBalance(contractAddress)
+ }
+ }
+ }
+
+ /**
+ * Find if selectedAddress has tokens with contract in contractAddress.
+ *
+ * @param {string} contractAddress Hex address of the token contract to explore.
+ * @returns {boolean} If balance is detected, token is added.
+ *
+ */
+ async detectTokenBalance (contractAddress) {
+ const ethContract = this.web3.eth.contract(ERC20_ABI).at(contractAddress)
+ ethContract.balanceOf(this.selectedAddress, (error, result) => {
+ if (!error) {
+ if (!result.isZero()) {
+ this._preferences.addToken(contractAddress, contracts[contractAddress].symbol, contracts[contractAddress].decimals)
+ }
+ } else {
+ warn(`MetaMask - DetectTokensController balance fetch failed for ${contractAddress}.`, error)
+ }
+ })
+ }
+
+ /**
+ * Restart token detection polling period and call detectNewTokens
+ * in case of address change or user session initialization.
+ *
+ */
+ restartTokenDetection () {
+ if (!(this.isActive && this.selectedAddress)) { return }
+ this.detectNewTokens()
+ this.interval = DEFAULT_INTERVAL
+ }
+
+ /**
+ * @type {Number}
+ */
+ set interval (interval) {
+ this._handle && clearInterval(this._handle)
+ if (!interval) { return }
+ this._handle = setInterval(() => { this.detectNewTokens() }, interval)
+ }
+
+ /**
+ * In setter when selectedAddress is changed, detectNewTokens and restart polling
+ * @type {Object}
+ */
+ set preferences (preferences) {
+ if (!preferences) { return }
+ this._preferences = preferences
+ preferences.store.subscribe(({ tokens }) => { this.tokenAddresses = tokens.map((obj) => { return obj.address }) })
+ preferences.store.subscribe(({ selectedAddress }) => {
+ if (this.selectedAddress !== selectedAddress) {
+ this.selectedAddress = selectedAddress
+ this.restartTokenDetection()
+ }
+ })
+ }
+
+ /**
+ * @type {Object}
+ */
+ set network (network) {
+ if (!network) { return }
+ this._network = network
+ this.web3 = new Web3(network._provider)
+ }
+
+ /**
+ * In setter when isUnlocked is updated to true, detectNewTokens and restart polling
+ * @type {Object}
+ */
+ set keyringMemStore (keyringMemStore) {
+ if (!keyringMemStore) { return }
+ this._keyringMemStore = keyringMemStore
+ this._keyringMemStore.subscribe(({ isUnlocked }) => {
+ if (this.isUnlocked !== isUnlocked) {
+ this.isUnlocked = isUnlocked
+ if (isUnlocked) { this.restartTokenDetection() }
+ }
+ })
+ }
+
+ /**
+ * Internal isActive state
+ * @type {Object}
+ */
+ get isActive () {
+ return this.isOpen && this.isUnlocked
+ }
+}
+
+module.exports = DetectTokensController
diff --git a/app/scripts/controllers/network/enums.js b/app/scripts/controllers/network/enums.js
index 9da7f309c..3190eb37c 100644
--- a/app/scripts/controllers/network/enums.js
+++ b/app/scripts/controllers/network/enums.js
@@ -4,6 +4,7 @@ const KOVAN = 'kovan'
const MAINNET = 'mainnet'
const LOCALHOST = 'localhost'
+const MAINNET_CODE = 1
const ROPSTEN_CODE = 3
const RINKEYBY_CODE = 4
const KOVAN_CODE = 42
@@ -13,13 +14,13 @@ const RINKEBY_DISPLAY_NAME = 'Rinkeby'
const KOVAN_DISPLAY_NAME = 'Kovan'
const MAINNET_DISPLAY_NAME = 'Main Ethereum Network'
-
module.exports = {
ROPSTEN,
RINKEBY,
KOVAN,
MAINNET,
LOCALHOST,
+ MAINNET_CODE,
ROPSTEN_CODE,
RINKEYBY_CODE,
KOVAN_CODE,
diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js
index b314745f5..f6250dc16 100644
--- a/app/scripts/controllers/preferences.js
+++ b/app/scripts/controllers/preferences.js
@@ -86,6 +86,30 @@ class PreferencesController {
}
/**
+ * Removes an address from state
+ *
+ * @param {string} address A hex address
+ * @returns {string} the address that was removed
+ */
+ removeAddress (address) {
+ const identities = this.store.getState().identities
+ if (!identities[address]) {
+ throw new Error(`${address} can't be deleted cause it was not found`)
+ }
+ delete identities[address]
+ this.store.updateState({ identities })
+
+ // If the selected account is no longer valid,
+ // select an arbitrary other account:
+ if (address === this.getSelectedAddress()) {
+ const selected = Object.keys(identities)[0]
+ this.setSelectedAddress(selected)
+ }
+ return address
+ }
+
+
+ /**
* Adds addresses to the identities object without removing identities
*
* @param {string[]} addresses An array of hex addresses
diff --git a/app/scripts/controllers/transactions/nonce-tracker.js b/app/scripts/controllers/transactions/nonce-tracker.js
index a27568843..421036368 100644
--- a/app/scripts/controllers/transactions/nonce-tracker.js
+++ b/app/scripts/controllers/transactions/nonce-tracker.js
@@ -120,19 +120,6 @@ class NonceTracker {
return Number.isInteger(highest) ? highest + 1 : 0
}
- _reduceTxListToUniqueNonces (txList) {
- const reducedTxList = txList.reduce((reducedList, txMeta, index) => {
- if (!index) return [txMeta]
- const nonceMatches = txList.filter((txData) => {
- return txMeta.txParams.nonce === txData.txParams.nonce
- })
- if (nonceMatches.length > 1) return reducedList
- reducedList.push(txMeta)
- return reducedList
- }, [])
- return reducedTxList
- }
-
_getHighestNonce (txList) {
const nonces = txList.map((txMeta) => {
const nonce = txMeta.txParams.nonce
diff --git a/app/scripts/controllers/transactions/tx-state-manager.js b/app/scripts/controllers/transactions/tx-state-manager.js
index 0aae4774b..28a18ca2e 100644
--- a/app/scripts/controllers/transactions/tx-state-manager.js
+++ b/app/scripts/controllers/transactions/tx-state-manager.js
@@ -288,6 +288,7 @@ class TransactionStateManager extends EventEmitter {
*/
setTxStatusRejected (txId) {
this._setTxStatus(txId, 'rejected')
+ this._removeTx(txId)
}
/**
@@ -422,6 +423,11 @@ class TransactionStateManager extends EventEmitter {
_saveTxList (transactions) {
this.store.updateState({ transactions })
}
+
+ _removeTx (txId) {
+ const transactionList = this.getFullTxList()
+ this._saveTxList(transactionList.filter((txMeta) => txMeta.id !== txId))
+ }
}
module.exports = TransactionStateManager