aboutsummaryrefslogtreecommitdiffstats
path: root/test/unit/metamask-controller-test.js
blob: 454b0ae44739ce025677b7c39c1706cb24e18451 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
const assert = require('assert')
const sinon = require('sinon')
const clone = require('clone')
const nock = require('nock')
const MetaMaskController = require('../../app/scripts/metamask-controller')
const blacklistJSON = require('../stub/blacklist')
const firstTimeState = require('../../app/scripts/first-time-state')

describe('MetaMaskController', function () {
  let metamaskController
  const sandbox = sinon.createSandbox()
  const noop = () => {}

  beforeEach(function () {

    nock('https://api.infura.io')
      .persist()
      .get('/v2/blacklist')
      .reply(200, blacklistJSON)

    nock('https://api.infura.io')
      .get('/v1/ticker/ethusd')
      .reply(200, '{"base": "ETH", "quote": "USD", "bid": 288.45, "ask": 288.46, "volume": 112888.17569277, "exchange": "bitfinex", "total_volume": 272175.00106721005, "num_exchanges": 8, "timestamp": 1506444677}')

    nock('https://api.infura.io')
      .get('/v1/ticker/ethjpy')
      .reply(200, '{"base": "ETH", "quote": "JPY", "bid": 32300.0, "ask": 32400.0, "volume": 247.4616071, "exchange": "kraken", "total_volume": 247.4616071, "num_exchanges": 1, "timestamp": 1506444676}')

    nock('https://api.infura.io')
      .persist()
      .get(/.*/)
      .reply(200)

    metamaskController = new MetaMaskController({
      showUnapprovedTx: noop,
      encryptor: {
        encrypt: function (password, object) {
          this.object = object
          return Promise.resolve()
        },
        decrypt: function () {
          return Promise.resolve(this.object)
        },
      },
      initState: clone(firstTimeState),
    })
    sandbox.spy(metamaskController.keyringController, 'createNewVaultAndKeychain')
    sandbox.spy(metamaskController.keyringController, 'createNewVaultAndRestore')
  })

  afterEach(function () {
    nock.cleanAll()
    sandbox.restore()
  })

  describe('#getGasPrice', function () {

    it('gives the 50th percentile lowest accepted gas price from recentBlocksController', async function () {
      const realRecentBlocksController = metamaskController.recentBlocksController
      metamaskController.recentBlocksController = {
        store: {
          getState: () => {
            return {
              recentBlocks: [
                { gasPrices: [ '0x3b9aca00', '0x174876e800'] },
                { gasPrices: [ '0x3b9aca00', '0x174876e800'] },
                { gasPrices: [ '0x174876e800', '0x174876e800' ]},
                { gasPrices: [ '0x174876e800', '0x174876e800' ]},
              ],
            }
          },
        },
      }

      const gasPrice = metamaskController.getGasPrice()
      assert.equal(gasPrice, '0x3b9aca00', 'accurately estimates 50th percentile accepted gas price')

      metamaskController.recentBlocksController = realRecentBlocksController
    })
  })

  describe('#createNewVaultAndKeychain', function () {
    it('can only create new vault on keyringController once', async function () {
      const selectStub = sandbox.stub(metamaskController, 'selectFirstIdentity')

      const password = 'a-fake-password'

      await metamaskController.createNewVaultAndKeychain(password)
      await metamaskController.createNewVaultAndKeychain(password)

      assert(metamaskController.keyringController.createNewVaultAndKeychain.calledOnce)

      selectStub.reset()
    })
  })

  describe('#createNewVaultAndRestore', function () {
    it('should be able to call newVaultAndRestore despite a mistake.', async function () {

      const password = 'what-what-what'
      const wrongSeed = 'debris dizzy just program just float decrease vacant alarm reduce speak stadiu'
      const rightSeed = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
      await metamaskController.createNewVaultAndRestore(password, wrongSeed)
        .catch((e) => {
          return
        })
      await metamaskController.createNewVaultAndRestore(password, rightSeed)

      assert(metamaskController.keyringController.createNewVaultAndRestore.calledTwice)
    })
  })

  describe('#getApi', function () {
    let getApi, state

    beforeEach(function () {
      getApi = metamaskController.getApi()
    })

    it('getState', function (done) {
      getApi.getState((err, res) => {
        if (err) {
          done(err)
        } else {
          state = res
        }
      })
      assert.deepEqual(state, metamaskController.getState())
      done()
    })

  })

  describe('preferencesController', function () {

    it('defaults useBlockie to false', function () {
      assert.equal(metamaskController.preferencesController.store.getState().useBlockie, false)
    })

    it('setUseBlockie to true', async function () {
      metamaskController.setUseBlockie(true, noop)
      assert.equal(metamaskController.preferencesController.store.getState().useBlockie, true)
    })

  })

  describe('#selectFirstIdentity', function () {
    let identities, address

    beforeEach(function () {
      address = '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc'
      identities = {
        identities: {
          '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc': {
            'address': '0x0dcd5d886577d5081b0c52e242ef29e70be3e7bc',
            'name': 'Account 1',
          },
        },
      }
      metamaskController.selectFirstIdentity(identities)
    })

    it('changes preferences controller select address', function () {
      const preferenceControllerState = metamaskController.preferencesController.store.getState()
      assert.equal(preferenceControllerState.selectedAddress, address)
    })

    it('changes metamask controller selected address', function () {
      const metamaskState = metamaskController.getState()
      assert.equal(metamaskState.selectedAddress, address)
    })
  })

  describe('#setCustomRpc', function () {
    const customRPC = 'https://custom.rpc/'
    let rpcTarget

    beforeEach(function () {

      nock('https://custom.rpc')
      .post('/')
      .reply(200)

      rpcTarget = metamaskController.setCustomRpc(customRPC)
    })

    it('returns custom RPC that when called', async function () {
      assert.equal(await rpcTarget, customRPC)
    })

    it('changes the network controller rpc', function () {
      const networkControllerState = metamaskController.networkController.store.getState()
      assert.equal(networkControllerState.provider.rpcTarget, customRPC)
    })
  })

  describe('#setCurrentCurrency', function () {
    let defaultMetaMaskCurrency

    beforeEach(function () {
      defaultMetaMaskCurrency = metamaskController.currencyController.getCurrentCurrency()
    })

    it('defaults to usd', function () {
      assert.equal(defaultMetaMaskCurrency, 'usd')
    })

    it('sets currency to JPY', function () {
      metamaskController.setCurrentCurrency('JPY', noop)
      assert.equal(metamaskController.currencyController.getCurrentCurrency(), 'JPY')
    })
  })

  describe('#createShapeshifttx', function () {
    let depositAddress, depositType, shapeShiftTxList

    beforeEach(function () {
      nock('https://shapeshift.io')
        .get('/txStat/3EevLFfB4H4XMWQwYCgjLie1qCAGpd2WBc')
        .reply(200, '{"status": "no_deposits", "address": "3EevLFfB4H4XMWQwYCgjLie1qCAGpd2WBc"}')

      depositAddress = '3EevLFfB4H4XMWQwYCgjLie1qCAGpd2WBc'
      depositType = 'ETH'
      shapeShiftTxList = metamaskController.shapeshiftController.store.getState().shapeShiftTxList
    })

    it('creates a shapeshift tx', async function () {
      metamaskController.createShapeShiftTx(depositAddress, depositType)
      assert.equal(shapeShiftTxList[0].depositAddress, depositAddress)
    })

  })

  describe('#addNewAccount', function () {
    let addNewAccount

    beforeEach(function () {
      addNewAccount = metamaskController.addNewAccount()
    })

    it('errors when an primary keyring is does not exist', async function () {
      try {
        await addNewAccount
        assert.equal(1 === 0)
      } catch (e) {
        assert.equal(e.message, 'MetamaskController - No HD Key Tree found')
      }
    })
  })

  describe('#verifyseedPhrase', function () {
    let seedPhrase, getConfigSeed

    it('errors when no keying is provided', async function () {
      try {
        await metamaskController.verifySeedPhrase()
      } catch (error) {
        assert.equal(error.message, 'MetamaskController - No HD Key Tree found')
      }
    })

    beforeEach(async function () {
      await metamaskController.createNewVaultAndKeychain('password')
      seedPhrase = await metamaskController.verifySeedPhrase()
    })

    it('#placeSeedWords should match the initially created vault seed', function () {

      metamaskController.placeSeedWords((err, result) => {
        if (err) {
         console.log(err)
        } else {
          getConfigSeed = metamaskController.configManager.getSeedWords()
          assert.equal(result, seedPhrase)
          assert.equal(result, getConfigSeed)
        }
      })
      assert.equal(getConfigSeed, undefined)
    })
  })

  describe('#clearSeedWordCache', function () {

    it('should have set seed words', function () {
      metamaskController.configManager.setSeedWords('test words')
      const getConfigSeed = metamaskController.configManager.getSeedWords()
      assert.equal(getConfigSeed, 'test words')
    })

    it('should clear config seed phrase', function () {
      metamaskController.configManager.setSeedWords('test words')
      metamaskController.clearSeedWordCache((err, result) => {
        if (err) console.log(err)
      })
      const getConfigSeed = metamaskController.configManager.getSeedWords()
      assert.equal(getConfigSeed, null)
    })

  })

})