From 088d7930e0895ef1802823c5fc843dd1c19b9661 Mon Sep 17 00:00:00 2001
From: kumavis <aaron@kumavis.me>
Date: Wed, 16 May 2018 20:46:34 -0700
Subject: network - create provider and block-tracker via json-rpc-engine

---
 app/scripts/metamask-controller.js | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index a6b5d3453..7f4f2fc9b 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -103,8 +103,9 @@ module.exports = class MetamaskController extends EventEmitter {
     this.blacklistController.scheduleUpdates()
 
     // rpc provider
-    this.provider = this.initializeProvider()
-    this.blockTracker = this.provider._blockTracker
+    this.initializeProvider()
+    this.provider = this.networkController.getProviderAndBlockTracker().provider
+    this.blockTracker = this.networkController.getProviderAndBlockTracker().blockTracker
 
     // token exchange rate tracker
     this.tokenRatesController = new TokenRatesController({
@@ -1033,7 +1034,7 @@ module.exports = class MetamaskController extends EventEmitter {
     // create filter polyfill middleware
     const filterMiddleware = createFilterMiddleware({
       provider: this.provider,
-      blockTracker: this.provider._blockTracker,
+      blockTracker: this.blockTracker,
     })
 
     engine.push(createOriginMiddleware({ origin }))
-- 
cgit 


From 66a62dfd0c2efbb9596bdc4b4befe03b25fbd7e9 Mon Sep 17 00:00:00 2001
From: kumavis <aaron@kumavis.me>
Date: Thu, 24 May 2018 13:44:33 -0700
Subject: metamask-controller - fix account lookup hook

---
 app/scripts/metamask-controller.js | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 14eb749e7..152ad13a0 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -241,7 +241,7 @@ module.exports = class MetamaskController extends EventEmitter {
         },
       },
       // account mgmt
-      getAccounts: (cb) => {
+      getAccounts: async () => {
         const isUnlocked = this.keyringController.memStore.getState().isUnlocked
         const result = []
         const selectedAddress = this.preferencesController.getSelectedAddress()
@@ -250,7 +250,7 @@ module.exports = class MetamaskController extends EventEmitter {
         if (isUnlocked && selectedAddress) {
           result.push(selectedAddress)
         }
-        cb(null, result)
+        return result
       },
       // tx signing
       // old style msg signing
-- 
cgit 


From aab9691c42184b81cdf7086d389bb74279e867bf Mon Sep 17 00:00:00 2001
From: kumavis <aaron@kumavis.me>
Date: Thu, 24 May 2018 15:51:46 -0700
Subject: provider - update wallet hooks for new wallet middleware

---
 app/scripts/metamask-controller.js | 77 +++++++++-----------------------------
 1 file changed, 17 insertions(+), 60 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 152ad13a0..8c3c70c5c 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -234,28 +234,22 @@ module.exports = class MetamaskController extends EventEmitter {
       static: {
         eth_syncing: false,
         web3_clientVersion: `MetaMask/v${version}`,
-        eth_sendTransaction: (payload, next, end) => {
-          const origin = payload.origin
-          const txParams = payload.params[0]
-          nodeify(this.txController.newUnapprovedTransaction, this.txController)(txParams, { origin }, end)
-        },
       },
       // account mgmt
       getAccounts: async () => {
         const isUnlocked = this.keyringController.memStore.getState().isUnlocked
-        const result = []
         const selectedAddress = this.preferencesController.getSelectedAddress()
-
         // only show address if account is unlocked
         if (isUnlocked && selectedAddress) {
-          result.push(selectedAddress)
+          return [selectedAddress]
+        } else {
+          return []
         }
-        return result
       },
       // tx signing
-      // old style msg signing
-      processMessage: this.newUnsignedMessage.bind(this),
-      // personal_sign msg signing
+      processTransaction: this.txController.newUnapprovedTransaction.bind(this.txController),
+      // msg signing
+      processEthSignMessage: this.newUnsignedMessage.bind(this),
       processPersonalMessage: this.newUnsignedPersonalMessage.bind(this),
       processTypedMessage: this.newUnsignedTypedMessage.bind(this),
     }
@@ -634,20 +628,11 @@ module.exports = class MetamaskController extends EventEmitter {
    * @param {Object} msgParams - The params passed to eth_sign.
    * @param {Function} cb = The callback function called with the signature.
    */
-  newUnsignedMessage (msgParams, cb) {
-    const msgId = this.messageManager.addUnapprovedMessage(msgParams)
+  newUnsignedMessage (msgParams, req) {
+    const promise = this.messageManager.addUnapprovedMessageAsync(msgParams, req)
     this.sendUpdate()
     this.opts.showUnconfirmedMessage()
-    this.messageManager.once(`${msgId}:finished`, (data) => {
-      switch (data.status) {
-        case 'signed':
-          return cb(null, data.rawSig)
-        case 'rejected':
-          return cb(new Error('MetaMask Message Signature: User denied message signature.'))
-        default:
-          return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))
-      }
-    })
+    return promise
   }
 
   /**
@@ -701,24 +686,11 @@ module.exports = class MetamaskController extends EventEmitter {
    * @param {Function} cb - The callback function called with the signature.
    * Passed back to the requesting Dapp.
    */
-  newUnsignedPersonalMessage (msgParams, cb) {
-    if (!msgParams.from) {
-      return cb(new Error('MetaMask Message Signature: from field is required.'))
-    }
-
-    const msgId = this.personalMessageManager.addUnapprovedMessage(msgParams)
+  async newUnsignedPersonalMessage (msgParams, req) {
+    const promise = this.personalMessageManager.addUnapprovedMessageAsync(msgParams, req)
     this.sendUpdate()
     this.opts.showUnconfirmedMessage()
-    this.personalMessageManager.once(`${msgId}:finished`, (data) => {
-      switch (data.status) {
-        case 'signed':
-          return cb(null, data.rawSig)
-        case 'rejected':
-          return cb(new Error('MetaMask Message Signature: User denied message signature.'))
-        default:
-          return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))
-      }
-    })
+    return promise
   }
 
   /**
@@ -767,26 +739,11 @@ module.exports = class MetamaskController extends EventEmitter {
    * @param {Object} msgParams - The params passed to eth_signTypedData.
    * @param {Function} cb - The callback function, called with the signature.
    */
-  newUnsignedTypedMessage (msgParams, cb) {
-    let msgId
-    try {
-      msgId = this.typedMessageManager.addUnapprovedMessage(msgParams)
-      this.sendUpdate()
-      this.opts.showUnconfirmedMessage()
-    } catch (e) {
-      return cb(e)
-    }
-
-    this.typedMessageManager.once(`${msgId}:finished`, (data) => {
-      switch (data.status) {
-        case 'signed':
-          return cb(null, data.rawSig)
-        case 'rejected':
-          return cb(new Error('MetaMask Message Signature: User denied message signature.'))
-        default:
-          return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`))
-      }
-    })
+  newUnsignedTypedMessage (msgParams, req) {
+    const promise = this.typedMessageManager.addUnapprovedMessageAsync(msgParams, req)
+    this.sendUpdate()
+    this.opts.showUnconfirmedMessage()
+    return promise
   }
 
   /**
-- 
cgit 


From 76cfb10864364d53efcdfa5f646f9947c83b6fb2 Mon Sep 17 00:00:00 2001
From: kumavis <aaron@kumavis.me>
Date: Thu, 24 May 2018 16:05:07 -0700
Subject: metamask-controller - wrap txController.addUnapprovedTx for wallet
 middleware reference before txController is instantiated

---
 app/scripts/metamask-controller.js | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 8c3c70c5c..796c9385a 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -247,7 +247,7 @@ module.exports = class MetamaskController extends EventEmitter {
         }
       },
       // tx signing
-      processTransaction: this.txController.newUnapprovedTransaction.bind(this.txController),
+      processTransaction: this.newUnapprovedTransaction.bind(this),
       // msg signing
       processEthSignMessage: this.newUnsignedMessage.bind(this),
       processPersonalMessage: this.newUnsignedPersonalMessage.bind(this),
@@ -617,6 +617,18 @@ module.exports = class MetamaskController extends EventEmitter {
   // ---------------------------------------------------------------------------
   // Identity Management (signature operations)
 
+  /**
+   * Called when a Dapp suggests a new tx to be signed.
+   * this wrapper needs to exist so we can provide a reference to
+   *  "newUnapprovedTransaction" before "txController" is instantiated
+   *
+   * @param {Object} msgParams - The params passed to eth_sign.
+   * @param {Object} req - (optional) the original request, containing the origin
+   */
+  async newUnapprovedTransaction(txParams, req) {
+    return await this.txController.newUnapprovedTransaction(txParams, req)
+  }
+
   // eth_sign methods:
 
   /**
-- 
cgit 


From fe42de46422c89156e91fb08ee06f50511c8601f Mon Sep 17 00:00:00 2001
From: kumavis <aaron@kumavis.me>
Date: Mon, 28 May 2018 22:58:14 -0700
Subject: metamask-controller - update preferences controller addresses after
 import account

---
 app/scripts/metamask-controller.js | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 796c9385a..ed606d4ab 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -345,7 +345,7 @@ module.exports = class MetamaskController extends EventEmitter {
       verifySeedPhrase: nodeify(this.verifySeedPhrase, this),
       clearSeedWordCache: this.clearSeedWordCache.bind(this),
       resetAccount: nodeify(this.resetAccount, this),
-      importAccountWithStrategy: this.importAccountWithStrategy.bind(this),
+      importAccountWithStrategy: nodeify(this.importAccountWithStrategy, this),
 
       // vault management
       submitPassword: nodeify(keyringController.submitPassword, keyringController),
@@ -603,15 +603,15 @@ module.exports = class MetamaskController extends EventEmitter {
    * @param  {any} args - The data required by that strategy to import an account.
    * @param  {Function} cb - A callback function called with a state update on success.
    */
-  importAccountWithStrategy (strategy, args, cb) {
-    accountImporter.importAccount(strategy, args)
-    .then((privateKey) => {
-      return this.keyringController.addNewKeyring('Simple Key Pair', [ privateKey ])
-    })
-    .then(keyring => keyring.getAccounts())
-    .then((accounts) => this.preferencesController.setSelectedAddress(accounts[0]))
-    .then(() => { cb(null, this.keyringController.fullUpdate()) })
-    .catch((reason) => { cb(reason) })
+  async importAccountWithStrategy (strategy, args) {
+    const privateKey = await accountImporter.importAccount(strategy, args)
+    const keyring = await this.keyringController.addNewKeyring('Simple Key Pair', [ privateKey ])
+    const accounts = await keyring.getAccounts()
+    // update accounts in preferences controller
+    const allAccounts = await keyringController.getAccounts()
+    this.preferencesController.setAddresses(allAccounts)
+    // set new account as selected
+    await this.preferencesController.setSelectedAddress(accounts[0])
   }
 
   // ---------------------------------------------------------------------------
-- 
cgit 


From c9f3404ca5b04df859f765f9f8e90f21737142c1 Mon Sep 17 00:00:00 2001
From: kumavis <kumavis@users.noreply.github.com>
Date: Mon, 28 May 2018 23:14:38 -0700
Subject: metamask-controller - lint fix

---
 app/scripts/metamask-controller.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index ed606d4ab..2e74b3a20 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -608,7 +608,7 @@ module.exports = class MetamaskController extends EventEmitter {
     const keyring = await this.keyringController.addNewKeyring('Simple Key Pair', [ privateKey ])
     const accounts = await keyring.getAccounts()
     // update accounts in preferences controller
-    const allAccounts = await keyringController.getAccounts()
+    const allAccounts = await this.keyringController.getAccounts()
     this.preferencesController.setAddresses(allAccounts)
     // set new account as selected
     await this.preferencesController.setSelectedAddress(accounts[0])
-- 
cgit 


From ffb8fa16497d0c4a48e3bd4b918dde1ac3adcd5d Mon Sep 17 00:00:00 2001
From: kumavis <aaron@kumavis.me>
Date: Wed, 6 Jun 2018 11:17:52 -0700
Subject: lint - remove unused require

---
 app/scripts/metamask-controller.js | 1 -
 1 file changed, 1 deletion(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index b206c6b67..b1d0217fd 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -45,7 +45,6 @@ const BN = require('ethereumjs-util').BN
 const GWEI_BN = new BN('1000000000')
 const percentile = require('percentile')
 const seedPhraseVerifier = require('./lib/seed-phrase-verifier')
-const cleanErrorStack = require('./lib/cleanErrorStack')
 const DiagnosticsReporter = require('./lib/diagnostics-reporter')
 const log = require('loglevel')
 
-- 
cgit 


From 5ef80495cfd47a8f5e4caf4b16842155420de62e Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Fri, 10 Aug 2018 21:54:34 -0400
Subject: refactor to support multiple hw wallets

---
 app/scripts/metamask-controller.js | 130 ++++++++++++++++---------------------
 1 file changed, 55 insertions(+), 75 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index db323e3fe..593b722ff 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -49,6 +49,7 @@ const seedPhraseVerifier = require('./lib/seed-phrase-verifier')
 const cleanErrorStack = require('./lib/cleanErrorStack')
 const log = require('loglevel')
 const TrezorKeyring = require('eth-trezor-keyring')
+const LedgerKeyring = require('./eth-ledger-keyring-listener')
 
 module.exports = class MetamaskController extends EventEmitter {
 
@@ -127,7 +128,7 @@ module.exports = class MetamaskController extends EventEmitter {
     })
 
     // key mgmt
-    const additionalKeyrings = [TrezorKeyring]
+    const additionalKeyrings = [TrezorKeyring, LedgerKeyring]
     this.keyringController = new KeyringController({
       keyringTypes: additionalKeyrings,
       initState: initState.KeyringController,
@@ -377,9 +378,7 @@ module.exports = class MetamaskController extends EventEmitter {
       connectHardware: nodeify(this.connectHardware, this),
       forgetDevice: nodeify(this.forgetDevice, this),
       checkHardwareStatus: nodeify(this.checkHardwareStatus, this),
-
-      // TREZOR
-      unlockTrezorAccount: nodeify(this.unlockTrezorAccount, this),
+      unlockHardwareWalletAccount: nodeify(this.unlockHardwareWalletAccount, this),
 
       // vault management
       submitPassword: nodeify(this.submitPassword, this),
@@ -540,6 +539,28 @@ module.exports = class MetamaskController extends EventEmitter {
   // Hardware
   //
 
+  async getKeyringForDevice (deviceName) {
+    let keyringName = null
+    switch (deviceName) {
+      case 'trezor':
+        keyringName = TrezorKeyring.type
+        break
+      case 'ledger':
+        keyringName = TrezorKeyring.type
+        break
+      default:
+        throw new Error('MetamaskController:connectHardware - Unknown device')
+    }
+
+    let keyring = await this.keyringController.getKeyringsByType(keyringName)[0]
+    if (!keyring) {
+      keyring = await this.keyringController.addNewKeyring(keyringName)
+    }
+
+    return keyring
+
+  }
+
   /**
    * Fetch account list from a trezor device.
    *
@@ -547,38 +568,26 @@ module.exports = class MetamaskController extends EventEmitter {
    */
   async connectHardware (deviceName, page) {
 
-    switch (deviceName) {
-      case 'trezor':
-        const keyringController = this.keyringController
-        const oldAccounts = await keyringController.getAccounts()
-        let keyring = await keyringController.getKeyringsByType(
-          'Trezor Hardware'
-        )[0]
-        if (!keyring) {
-          keyring = await this.keyringController.addNewKeyring('Trezor Hardware')
-        }
-        let accounts = []
-
-        switch (page) {
-            case -1:
-              accounts = await keyring.getPreviousPage()
-              break
-            case 1:
-              accounts = await keyring.getNextPage()
-              break
-            default:
-              accounts = await keyring.getFirstPage()
-        }
-
-        // Merge with existing accounts
-        // and make sure addresses are not repeated
-        const accountsToTrack = [...new Set(oldAccounts.concat(accounts.map(a => a.address.toLowerCase())))]
-        this.accountTracker.syncWithAddresses(accountsToTrack)
-        return accounts
-
-      default:
-        throw new Error('MetamaskController:connectHardware - Unknown device')
+    const oldAccounts = await this.keyringController.getAccounts()
+    const keyring = await this.getKeyringForDevice(deviceName)
+    let accounts = []
+
+    switch (page) {
+        case -1:
+          accounts = await keyring.getPreviousPage()
+          break
+        case 1:
+          accounts = await keyring.getNextPage()
+          break
+        default:
+          accounts = await keyring.getFirstPage()
     }
+
+    // Merge with existing accounts
+    // and make sure addresses are not repeated
+    const accountsToTrack = [...new Set(oldAccounts.concat(accounts.map(a => a.address.toLowerCase())))]
+    this.accountTracker.syncWithAddresses(accountsToTrack)
+    return accounts
   }
 
   /**
@@ -587,20 +596,8 @@ module.exports = class MetamaskController extends EventEmitter {
    * @returns {Promise<boolean>}
    */
   async checkHardwareStatus (deviceName) {
-
-    switch (deviceName) {
-      case 'trezor':
-        const keyringController = this.keyringController
-        const keyring = await keyringController.getKeyringsByType(
-          'Trezor Hardware'
-        )[0]
-        if (!keyring) {
-          return false
-        }
-        return keyring.isUnlocked()
-      default:
-        throw new Error('MetamaskController:checkHardwareStatus - Unknown device')
-    }
+    const keyring = await this.getKeyringForDevice(deviceName)
+    return keyring.isUnlocked()
   }
 
   /**
@@ -610,20 +607,9 @@ module.exports = class MetamaskController extends EventEmitter {
    */
   async forgetDevice (deviceName) {
 
-    switch (deviceName) {
-      case 'trezor':
-        const keyringController = this.keyringController
-        const keyring = await keyringController.getKeyringsByType(
-          'Trezor Hardware'
-        )[0]
-        if (!keyring) {
-          throw new Error('MetamaskController:forgetDevice - Trezor Hardware keyring not found')
-        }
-        keyring.forgetDevice()
-        return true
-      default:
-        throw new Error('MetamaskController:forgetDevice - Unknown device')
-    }
+    const keyring = await this.getKeyringForDevice(deviceName)
+    keyring.forgetDevice()
+    return true
   }
 
   /**
@@ -631,23 +617,17 @@ module.exports = class MetamaskController extends EventEmitter {
    *
    * @returns {} keyState
    */
-  async unlockTrezorAccount (index) {
-    const keyringController = this.keyringController
-    const keyring = await keyringController.getKeyringsByType(
-      'Trezor Hardware'
-    )[0]
-    if (!keyring) {
-      throw new Error('MetamaskController - No Trezor Hardware Keyring found')
-    }
+  async unlockHardwareWalletAccount (deviceName, index) {
+    const keyring = await this.getKeyringForDevice(deviceName)
 
     keyring.setAccountToUnlock(index)
-    const oldAccounts = await keyringController.getAccounts()
-    const keyState = await keyringController.addNewAccount(keyring)
-    const newAccounts = await keyringController.getAccounts()
+    const oldAccounts = await this.keyringController.getAccounts()
+    const keyState = await this.keyringController.addNewAccount(keyring)
+    const newAccounts = await this.keyringController.getAccounts()
     this.preferencesController.setAddresses(newAccounts)
     newAccounts.forEach(address => {
       if (!oldAccounts.includes(address)) {
-        this.preferencesController.setAccountLabel(address, `TREZOR #${parseInt(index, 10) + 1}`)
+        this.preferencesController.setAccountLabel(address, `${deviceName.toUpperCase()} #${parseInt(index, 10) + 1}`)
         this.preferencesController.setSelectedAddress(address)
       }
     })
-- 
cgit 


From 78a1cd3314455d6e4e08839a3eea3ec2868f4f59 Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Sat, 11 Aug 2018 02:35:20 -0400
Subject: iframe communication working

---
 app/scripts/metamask-controller.js | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 593b722ff..58bab9789 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -546,12 +546,11 @@ module.exports = class MetamaskController extends EventEmitter {
         keyringName = TrezorKeyring.type
         break
       case 'ledger':
-        keyringName = TrezorKeyring.type
+        keyringName = LedgerKeyring.type
         break
       default:
         throw new Error('MetamaskController:connectHardware - Unknown device')
     }
-
     let keyring = await this.keyringController.getKeyringsByType(keyringName)[0]
     if (!keyring) {
       keyring = await this.keyringController.addNewKeyring(keyringName)
@@ -568,10 +567,8 @@ module.exports = class MetamaskController extends EventEmitter {
    */
   async connectHardware (deviceName, page) {
 
-    const oldAccounts = await this.keyringController.getAccounts()
     const keyring = await this.getKeyringForDevice(deviceName)
     let accounts = []
-
     switch (page) {
         case -1:
           accounts = await keyring.getPreviousPage()
@@ -585,6 +582,7 @@ module.exports = class MetamaskController extends EventEmitter {
 
     // Merge with existing accounts
     // and make sure addresses are not repeated
+    const oldAccounts = await this.keyringController.getAccounts()
     const accountsToTrack = [...new Set(oldAccounts.concat(accounts.map(a => a.address.toLowerCase())))]
     this.accountTracker.syncWithAddresses(accountsToTrack)
     return accounts
-- 
cgit 


From 8e842a8947997b7ea47cf35d1348788d21f2f467 Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Sat, 11 Aug 2018 05:02:02 -0400
Subject: able to add accounts

---
 app/scripts/metamask-controller.js | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 58bab9789..c79e5141e 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -615,7 +615,7 @@ module.exports = class MetamaskController extends EventEmitter {
    *
    * @returns {} keyState
    */
-  async unlockHardwareWalletAccount (deviceName, index) {
+  async unlockHardwareWalletAccount (index, deviceName) {
     const keyring = await this.getKeyringForDevice(deviceName)
 
     keyring.setAccountToUnlock(index)
-- 
cgit 


From 0b9b892c6b27c55a016378387cb8d227957f8528 Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Sun, 12 Aug 2018 01:34:01 -0400
Subject: this should be ready to go

---
 app/scripts/metamask-controller.js | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index c79e5141e..fed00077e 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -49,7 +49,7 @@ const seedPhraseVerifier = require('./lib/seed-phrase-verifier')
 const cleanErrorStack = require('./lib/cleanErrorStack')
 const log = require('loglevel')
 const TrezorKeyring = require('eth-trezor-keyring')
-const LedgerKeyring = require('./eth-ledger-keyring-listener')
+const LedgerBridgeKeyring = require('eth-ledger-bridge-keyring')
 
 module.exports = class MetamaskController extends EventEmitter {
 
@@ -128,7 +128,7 @@ module.exports = class MetamaskController extends EventEmitter {
     })
 
     // key mgmt
-    const additionalKeyrings = [TrezorKeyring, LedgerKeyring]
+    const additionalKeyrings = [TrezorKeyring, LedgerBridgeKeyring]
     this.keyringController = new KeyringController({
       keyringTypes: additionalKeyrings,
       initState: initState.KeyringController,
@@ -546,7 +546,7 @@ module.exports = class MetamaskController extends EventEmitter {
         keyringName = TrezorKeyring.type
         break
       case 'ledger':
-        keyringName = LedgerKeyring.type
+        keyringName = LedgerBridgeKeyring.type
         break
       default:
         throw new Error('MetamaskController:connectHardware - Unknown device')
-- 
cgit 


From 4e1d8ba19db729f5c282c4e3c6b43433b562a45e Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Mon, 13 Aug 2018 19:29:43 -0400
Subject: good progress adding paths

---
 app/scripts/metamask-controller.js | 19 +++++++++++--------
 1 file changed, 11 insertions(+), 8 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index fed00077e..beaf04c0d 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -539,7 +539,7 @@ module.exports = class MetamaskController extends EventEmitter {
   // Hardware
   //
 
-  async getKeyringForDevice (deviceName) {
+  async getKeyringForDevice (deviceName, hdPath = null) {
     let keyringName = null
     switch (deviceName) {
       case 'trezor':
@@ -555,6 +555,10 @@ module.exports = class MetamaskController extends EventEmitter {
     if (!keyring) {
       keyring = await this.keyringController.addNewKeyring(keyringName)
     }
+    if (hdPath) {
+      console.log('[LEDGER]: HDPATH set', hdPath)
+      keyring.hdPath = hdPath
+    }
 
     return keyring
 
@@ -565,9 +569,8 @@ module.exports = class MetamaskController extends EventEmitter {
    *
    * @returns [] accounts
    */
-  async connectHardware (deviceName, page) {
-
-    const keyring = await this.getKeyringForDevice(deviceName)
+  async connectHardware (deviceName, page, hdPath) {
+    const keyring = await this.getKeyringForDevice(deviceName, hdPath)
     let accounts = []
     switch (page) {
         case -1:
@@ -593,8 +596,8 @@ module.exports = class MetamaskController extends EventEmitter {
    *
    * @returns {Promise<boolean>}
    */
-  async checkHardwareStatus (deviceName) {
-    const keyring = await this.getKeyringForDevice(deviceName)
+  async checkHardwareStatus (deviceName, hdPath) {
+    const keyring = await this.getKeyringForDevice(deviceName, hdPath)
     return keyring.isUnlocked()
   }
 
@@ -615,8 +618,8 @@ module.exports = class MetamaskController extends EventEmitter {
    *
    * @returns {} keyState
    */
-  async unlockHardwareWalletAccount (index, deviceName) {
-    const keyring = await this.getKeyringForDevice(deviceName)
+  async unlockHardwareWalletAccount (index, deviceName, hdPath) {
+    const keyring = await this.getKeyringForDevice(deviceName, hdPath)
 
     keyring.setAccountToUnlock(index)
     const oldAccounts = await this.keyringController.getAccounts()
-- 
cgit 


From 61a279204a804ddf4815d0db6103c19c5640bbb9 Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Tue, 14 Aug 2018 01:26:18 -0400
Subject: legacy and new hd path working

---
 app/scripts/metamask-controller.js | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index beaf04c0d..b1473390b 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -556,10 +556,11 @@ module.exports = class MetamaskController extends EventEmitter {
       keyring = await this.keyringController.addNewKeyring(keyringName)
     }
     if (hdPath) {
-      console.log('[LEDGER]: HDPATH set', hdPath)
       keyring.hdPath = hdPath
     }
 
+    keyring.network = this.networkController.getProviderConfig().type
+
     return keyring
 
   }
-- 
cgit 


From b77cc3d9690304362471fbfe207bdad461c2ca3a Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Tue, 14 Aug 2018 03:42:23 -0400
Subject: fix tx tests

---
 app/scripts/metamask-controller.js | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index b1473390b..c813c58ac 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -549,14 +549,14 @@ module.exports = class MetamaskController extends EventEmitter {
         keyringName = LedgerBridgeKeyring.type
         break
       default:
-        throw new Error('MetamaskController:connectHardware - Unknown device')
+        throw new Error('MetamaskController:getKeyringForDevice - Unknown device')
     }
     let keyring = await this.keyringController.getKeyringsByType(keyringName)[0]
     if (!keyring) {
       keyring = await this.keyringController.addNewKeyring(keyringName)
     }
-    if (hdPath) {
-      keyring.hdPath = hdPath
+    if (hdPath && keyring.setHdPath) {
+      keyring.setHdPath(hdPath)
     }
 
     keyring.network = this.networkController.getProviderConfig().type
-- 
cgit 


From fdf202efb066008f6625ba15cec8bcaef1edfec6 Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Tue, 14 Aug 2018 21:19:01 -0400
Subject: fixed unit tests

---
 app/scripts/metamask-controller.js | 6 ++++++
 1 file changed, 6 insertions(+)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index c813c58ac..ac188c4df 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -551,15 +551,21 @@ module.exports = class MetamaskController extends EventEmitter {
       default:
         throw new Error('MetamaskController:getKeyringForDevice - Unknown device')
     }
+    console.log('getting keyring for device ', deviceName, hdPath)
     let keyring = await this.keyringController.getKeyringsByType(keyringName)[0]
+    console.log('got Keyring', keyring)
     if (!keyring) {
+      console.log('we did not so lets add it', keyringName)
       keyring = await this.keyringController.addNewKeyring(keyringName)
+      console.log('what about now', keyring)
     }
+    console.log('setting hdPath', hdPath)
     if (hdPath && keyring.setHdPath) {
       keyring.setHdPath(hdPath)
     }
 
     keyring.network = this.networkController.getProviderConfig().type
+    console.log('setting network', keyring.network)
 
     return keyring
 
-- 
cgit 


From 82a5ed1e03e0a6a9bc19b946bc178b236d9aaa98 Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Tue, 14 Aug 2018 22:40:29 -0400
Subject: remove console logs

---
 app/scripts/metamask-controller.js | 8 +-------
 1 file changed, 1 insertion(+), 7 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index ac188c4df..1e1aa035f 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -551,21 +551,15 @@ module.exports = class MetamaskController extends EventEmitter {
       default:
         throw new Error('MetamaskController:getKeyringForDevice - Unknown device')
     }
-    console.log('getting keyring for device ', deviceName, hdPath)
     let keyring = await this.keyringController.getKeyringsByType(keyringName)[0]
-    console.log('got Keyring', keyring)
     if (!keyring) {
-      console.log('we did not so lets add it', keyringName)
       keyring = await this.keyringController.addNewKeyring(keyringName)
-      console.log('what about now', keyring)
     }
-    console.log('setting hdPath', hdPath)
     if (hdPath && keyring.setHdPath) {
       keyring.setHdPath(hdPath)
     }
 
     keyring.network = this.networkController.getProviderConfig().type
-    console.log('setting network', keyring.network)
 
     return keyring
 
@@ -635,7 +629,7 @@ module.exports = class MetamaskController extends EventEmitter {
     this.preferencesController.setAddresses(newAccounts)
     newAccounts.forEach(address => {
       if (!oldAccounts.includes(address)) {
-        this.preferencesController.setAccountLabel(address, `${deviceName.toUpperCase()} #${parseInt(index, 10) + 1}`)
+        this.preferencesController.setAccountLabel(address, `${deviceName.toUpperCase()} ${parseInt(index, 10) + 1}`)
         this.preferencesController.setSelectedAddress(address)
       }
     })
-- 
cgit 


From df799d7fd6c49888e3eb659adbfca18030b85975 Mon Sep 17 00:00:00 2001
From: Dan Matthews <dan@matthews.es>
Date: Thu, 26 Jul 2018 23:40:11 -0400
Subject: Restores accounts until one with a zero balance is found

---
 app/scripts/metamask-controller.js | 49 ++++++++++++++++++++++++++++++++++++--
 1 file changed, 47 insertions(+), 2 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 81bb080ab..166be720f 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -48,6 +48,7 @@ const percentile = require('percentile')
 const seedPhraseVerifier = require('./lib/seed-phrase-verifier')
 const log = require('loglevel')
 const TrezorKeyring = require('eth-trezor-keyring')
+const EthQuery = require('eth-query')
 
 module.exports = class MetamaskController extends EventEmitter {
 
@@ -475,12 +476,32 @@ module.exports = class MetamaskController extends EventEmitter {
   async createNewVaultAndRestore (password, seed) {
     const releaseLock = await this.createVaultMutex.acquire()
     try {
+      let accounts, lastBalance
+
+      const keyringController = this.keyringController
+
       // clear known identities
       this.preferencesController.setAddresses([])
       // create new vault
-      const vault = await this.keyringController.createNewVaultAndRestore(password, seed)
+      const vault = await keyringController.createNewVaultAndRestore(password, seed)
+
+      const ethQuery = new EthQuery(this.provider)
+      accounts = await keyringController.getAccounts()
+      lastBalance = await this.getBalance(accounts[accounts.length - 1], ethQuery)
+
+      const primaryKeyring = keyringController.getKeyringsByType('HD Key Tree')[0]
+      if (!primaryKeyring) {
+        throw new Error('MetamaskController - No HD Key Tree found')
+      }
+
+      // seek out the first zero balance
+      while (lastBalance !== '0x0') {
+        await keyringController.addNewAccount(primaryKeyring)
+        accounts = await keyringController.getAccounts()
+        lastBalance = await this.getBalance(accounts[accounts.length - 1], ethQuery)
+      }
+
       // set new identities
-      const accounts = await this.keyringController.getAccounts()
       this.preferencesController.setAddresses(accounts)
       this.selectFirstIdentity()
       releaseLock()
@@ -491,6 +512,30 @@ module.exports = class MetamaskController extends EventEmitter {
     }
   }
 
+  /**
+   * Get an account balance from the AccountTracker or request it directly from the network.
+   * @param {string} address - The account address
+   * @param {EthQuery} ethQuery - The EthQuery instance to use when asking the network
+   */
+  getBalance (address, ethQuery) {
+    return new Promise((resolve, reject) => {
+      const cached = this.accountTracker.store.getState().accounts[address]
+
+      if (cached && cached.balance) {
+        resolve(cached.balance)
+      } else {
+        ethQuery.getBalance(address, (error, balance) => {
+          if (error) {
+            reject(error)
+            log.error(error)
+          } else {
+            resolve(balance || '0x0')
+          }
+        })
+      }
+    })
+  }
+
   /*
    * Submits the user's password and attempts to unlock the vault.
    * Also synchronizes the preferencesController, to ensure its schema
-- 
cgit 


From 992e7f1b5aae5ae4a96c67dd40b6626f181b51c1 Mon Sep 17 00:00:00 2001
From: brunobar79 <brunobar79@gmail.com>
Date: Fri, 17 Aug 2018 12:56:07 -0400
Subject: fix merge conflicts

---
 app/scripts/metamask-controller.js | 99 +++++++++++++-------------------------
 1 file changed, 34 insertions(+), 65 deletions(-)

(limited to 'app/scripts/metamask-controller.js')

diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 1e1aa035f..585bb005e 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -46,7 +46,6 @@ const BN = require('ethereumjs-util').BN
 const GWEI_BN = new BN('1000000000')
 const percentile = require('percentile')
 const seedPhraseVerifier = require('./lib/seed-phrase-verifier')
-const cleanErrorStack = require('./lib/cleanErrorStack')
 const log = require('loglevel')
 const TrezorKeyring = require('eth-trezor-keyring')
 const LedgerBridgeKeyring = require('eth-ledger-bridge-keyring')
@@ -108,8 +107,9 @@ module.exports = class MetamaskController extends EventEmitter {
     this.blacklistController.scheduleUpdates()
 
     // rpc provider
-    this.provider = this.initializeProvider()
-    this.blockTracker = this.provider._blockTracker
+    this.initializeProvider()
+    this.provider = this.networkController.getProviderAndBlockTracker().provider
+    this.blockTracker = this.networkController.getProviderAndBlockTracker().blockTracker
 
     // token exchange rate tracker
     this.tokenRatesController = new TokenRatesController({
@@ -253,28 +253,22 @@ module.exports = class MetamaskController extends EventEmitter {
       static: {
         eth_syncing: false,
         web3_clientVersion: `MetaMask/v${version}`,
-        eth_sendTransaction: (payload, next, end) => {
-          const origin = payload.origin
-          const txParams = payload.params[0]
-          nodeify(this.txController.newUnapprovedTransaction, this.txController)(txParams, { origin }, end)
-        },
       },
       // account mgmt
-      getAccounts: (cb) => {
+      getAccounts: async () => {
         const isUnlocked = this.keyringController.memStore.getState().isUnlocked
-        const result = []
         const selectedAddress = this.preferencesController.getSelectedAddress()
-
         // only show address if account is unlocked
         if (isUnlocked && selectedAddress) {
-          result.push(selectedAddress)
+          return [selectedAddress]
+        } else {
+          return []
         }
-        cb(null, result)
       },
       // tx signing
-      // old style msg signing
-      processMessage: this.newUnsignedMessage.bind(this),
-      // personal_sign msg signing
+      processTransaction: this.newUnapprovedTransaction.bind(this),
+      // msg signing
+      processEthSignMessage: this.newUnsignedMessage.bind(this),
       processPersonalMessage: this.newUnsignedPersonalMessage.bind(this),
       processTypedMessage: this.newUnsignedTypedMessage.bind(this),
     }
@@ -791,6 +785,18 @@ module.exports = class MetamaskController extends EventEmitter {
   // ---------------------------------------------------------------------------
   // Identity Management (signature operations)
 
+  /**
+   * Called when a Dapp suggests a new tx to be signed.
+   * this wrapper needs to exist so we can provide a reference to
+   *  "newUnapprovedTransaction" before "txController" is instantiated
+   *
+   * @param {Object} msgParams - The params passed to eth_sign.
+   * @param {Object} req - (optional) the original request, containing the origin
+   */
+  async newUnapprovedTransaction (txParams, req) {
+    return await this.txController.newUnapprovedTransaction(txParams, req)
+  }
+
   // eth_sign methods:
 
   /**
@@ -802,20 +808,11 @@ module.exports = class MetamaskController extends EventEmitter {
    * @param {Object} msgParams - The params passed to eth_sign.
    * @param {Function} cb = The callback function called with the signature.
    */
-  newUnsignedMessage (msgParams, cb) {
-    const msgId = this.messageManager.addUnapprovedMessage(msgParams)
+  newUnsignedMessage (msgParams, req) {
+    const promise = this.messageManager.addUnapprovedMessageAsync(msgParams, req)
     this.sendUpdate()
     this.opts.showUnconfirmedMessage()
-    this.messageManager.once(`${msgId}:finished`, (data) => {
-      switch (data.status) {
-        case 'signed':
-          return cb(null, data.rawSig)
-        case 'rejected':
-          return cb(cleanErrorStack(new Error('MetaMask Message Signature: User denied message signature.')))
-        default:
-          return cb(cleanErrorStack(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)))
-      }
-    })
+    return promise
   }
 
   /**
@@ -869,24 +866,11 @@ module.exports = class MetamaskController extends EventEmitter {
    * @param {Function} cb - The callback function called with the signature.
    * Passed back to the requesting Dapp.
    */
-  newUnsignedPersonalMessage (msgParams, cb) {
-    if (!msgParams.from) {
-      return cb(cleanErrorStack(new Error('MetaMask Message Signature: from field is required.')))
-    }
-
-    const msgId = this.personalMessageManager.addUnapprovedMessage(msgParams)
+  async newUnsignedPersonalMessage (msgParams, req) {
+    const promise = this.personalMessageManager.addUnapprovedMessageAsync(msgParams, req)
     this.sendUpdate()
     this.opts.showUnconfirmedMessage()
-    this.personalMessageManager.once(`${msgId}:finished`, (data) => {
-      switch (data.status) {
-        case 'signed':
-          return cb(null, data.rawSig)
-        case 'rejected':
-          return cb(cleanErrorStack(new Error('MetaMask Message Signature: User denied message signature.')))
-        default:
-          return cb(cleanErrorStack(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)))
-      }
-    })
+    return promise
   }
 
   /**
@@ -935,26 +919,11 @@ module.exports = class MetamaskController extends EventEmitter {
    * @param {Object} msgParams - The params passed to eth_signTypedData.
    * @param {Function} cb - The callback function, called with the signature.
    */
-  newUnsignedTypedMessage (msgParams, cb) {
-    let msgId
-    try {
-      msgId = this.typedMessageManager.addUnapprovedMessage(msgParams)
-      this.sendUpdate()
-      this.opts.showUnconfirmedMessage()
-    } catch (e) {
-      return cb(e)
-    }
-
-    this.typedMessageManager.once(`${msgId}:finished`, (data) => {
-      switch (data.status) {
-        case 'signed':
-          return cb(null, data.rawSig)
-        case 'rejected':
-          return cb(cleanErrorStack(new Error('MetaMask Message Signature: User denied message signature.')))
-        default:
-          return cb(cleanErrorStack(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)))
-      }
-    })
+  newUnsignedTypedMessage (msgParams, req) {
+    const promise = this.typedMessageManager.addUnapprovedMessageAsync(msgParams, req)
+    this.sendUpdate()
+    this.opts.showUnconfirmedMessage()
+    return promise
   }
 
   /**
@@ -1219,7 +1188,7 @@ module.exports = class MetamaskController extends EventEmitter {
     // create filter polyfill middleware
     const filterMiddleware = createFilterMiddleware({
       provider: this.provider,
-      blockTracker: this.provider._blockTracker,
+      blockTracker: this.blockTracker,
     })
 
     engine.push(createOriginMiddleware({ origin }))
-- 
cgit