1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-22 17:33:23 +01:00

3box integration 2.0 (#6972)

* Adds threebox controller

* Adds threebox approval modal

* Fix unit tests and lint after addition of threebox

* Correct threebox behaviour after rejecting request for backup; fixes e2e tests.

* Update threebox controller for automatic syncing

* Ensure frontend locale updates when preferences are changed via direct update within controller

* Add toggle in settings for 3box syncing

* Update threebox controller for latest 3box version

* Delete unnecessary frontend changes for threebox integration

* Backing up address book contacts with threebox

* Update unit tests for 3box-integration additions

* Only enable threebox by default for new wallets

* Mock globals for correct unit tests

* 3box '1.10.2' -> '^1.10.2'

* Correct capilalization on 3Box

* Use log.debug instead of console.log in threebox controller

* Update yarn.lock

* Remove edge build

* Split 3box module into background deps js file

* extra bundle opts for bg-libs

* sync yarn.lock

* new3Box logic

* Show confirm threebox restore after import

* Remove bg-libs.js from manifest file for dev builds

* Switch 3Box controller to using the spaces api (instead of the profile api)

* Finalize switching to spaces api and only restoring from 3box after import

* Update metamask-controller-test.js for threebox controller changes

* Make threebox modal style consistent with others and update success button wording

* Use mock 3box when in test

* Correct 3box modal header

* Remove unnecessary property of threebox controller provider

* Remove unnecessary method calls after restoration from 3box in the threebox-restore-confirm modal.

* Replace setThreeBoxSyncingPermission calls in routes/index.js with turnThreeBoxSyncingOn

* Replace erroneous use of  with

* Replace erroneous use of threeboxSyncing with threeBoxSyncingAllowed in advancted-tab directory

* Lint fixes for 3box changes

* Log errors encountered when updating 3Box

* Remove unnecessary parameter from state update

* Add timeout to initial 3Box sync

The initial 3Box sync will now timeout after 1 minute. If the timeout
is triggered, 3Box is disabled and cannot be re-enabled unless the
initial sync does finally finish. If it never finishes, 3Box cannot
be enabled unless the extension is reinstalled.

The Advanced Settings page was updated to show this option as disabled
in that circumstance, with a new discription explaining why it's
disabled. The UI here could certainly be improved.

Additionally, "on" and "off" labels were added to the toggle to match
the other toggles on the Advanced Settings page.

* Use non-minified 3Box module

We had previously used the minified 3Box module to avoid a build error
encountered when `envify` was processing the `libp2p` module (which is
used by 3Box). The build would fail because `esprima` (used by `envify`)
is incompatible with the object spread/rest operator (which is used in
`libp2p`).

That issue has been solved by adding a global Babelify transformation
specifically for transpiling out the object rest/spread operator from
dependencies. It has been targetted to only affect `libp2p` to avoid
extending the build time too much. This workaround can be used until
a new version of `esprima` is released that includes this bug fix.

* Use app key addresses for threebox

* Replace use of modal for confirming 3box restoration with a home notification

* Adds e2e tests for restoring from threebox

* Update eth-keyring-controller to 5.1.0

* Correct parameters passed to getAppKeyAddress in threebox.js

* Add prefix to origin passed to getAppKeyAddress in threebox.js

* Remove unused locale message.

* Prevent CORS errors in firefox e2e tests

* Ensure extraneous scripts are excluded from the local test dev build

* Move threeBoxLastUpdate state from home.component to redux

* Threebox PR code cleanup

* Always use first address when initializing threebox

* Replace setRestoredFromThreeBox api with setRestoredFromThreeBoxToFalse and setRestoredFromThreeBoxToTrue

* Update development/metamaskbot-build-announce.js to include ui-libs and bg-libs in hard coded bundle list

* Update test/e2e/threebox.spec.js to use new helpers added with pull #7144

* Make setFeatureFlag available on the ui window during testing

* Hide threebox feature behind a feature flag that can only be activated via dev console

* Remove unnecessary migration of threebox feature flag

* Prevent this.init() call in threebox constructor if feature flag is not turned on

* Prevent threebox notification from showing if feature flag is falsy

* http://localhost/8889 -> http://localhost/* in gulp manifest:testing tasks
This commit is contained in:
Dan J Miller 2019-09-16 14:41:01 -02:30 committed by GitHub
parent bf72f39ff1
commit 7985f4f4f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 5153 additions and 115 deletions

View File

@ -505,6 +505,9 @@
"customRPC": {
"message": "Custom RPC"
},
"dataBackupFoundInfo": {
"message": "Some of your account data was backed up during a previous installation of MetaMask. This could include your settings, contacts and tokens. Would you like to restore this data now?"
},
"decimalsMustZerotoTen": {
"message": "Decimals must be at least 0, and not over 36."
},
@ -1148,6 +1151,9 @@
"noTransactions": {
"message": "You have no transactions"
},
"noThanks": {
"message": "No Thanks"
},
"notEnoughGas": {
"message": "Not Enough Gas"
},
@ -1337,6 +1343,10 @@
"restoreAccountWithSeed": {
"message": "Restore your Account with Seed Phrase"
},
"restoreWalletPreferences": {
"message": "A backup of your data from $1 has been found. Would you like to restore your wallet preferences?",
"description": "$1 is the date at which the data was backed up"
},
"requestsAwaitingAcknowledgement": {
"message": "requests waiting to be acknowledged"
},
@ -1642,6 +1652,15 @@
"symbolBetweenZeroTwelve": {
"message": "Symbol must be between 0 and 12 characters."
},
"syncWithThreeBox": {
"message": "Sync data with 3Box"
},
"syncWithThreeBoxDescription": {
"message": "Turn on to have your settings backed up with 3Box"
},
"syncWithThreeBoxDisabled": {
"message": "3Box has been disabled due to an error during the initial sync"
},
"syncWithMobile": {
"message": "Sync with mobile"
},

View File

@ -9,7 +9,7 @@
</head>
<body>
<div id="app-content"></div>
<script src="./libs.js" type="text/javascript" charset="utf-8"></script>
<script src="./ui-libs.js" type="text/javascript" charset="utf-8"></script>
<script src="./ui.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

View File

@ -29,6 +29,7 @@
"background": {
"scripts": [
"chromereload.js",
"bg-libs.js",
"background.js"
],
"persistent": true

View File

@ -36,7 +36,7 @@
<img id="loading__logo" src="./images/logo/metamask-fox.svg" />
<img id="loading__spinner" src="./images/spinner.gif" />
</div>
<script src="./libs.js" type="text/javascript" charset="utf-8"></script>
<script src="./ui-libs.js" type="text/javascript" charset="utf-8"></script>
<script src="./ui.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

View File

@ -9,7 +9,7 @@
</head>
<body style="width:357px; height:600px;">
<div id="app-content"></div>
<script src="./libs.js" type="text/javascript" charset="utf-8"></script>
<script src="./ui-libs.js" type="text/javascript" charset="utf-8"></script>
<script src="./ui.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

View File

@ -42,6 +42,7 @@ class PreferencesController {
// perform sensitive operations.
featureFlags: {
showIncomingTransactions: true,
threeBox: false,
},
knownMethodData: {},
participateInMetaMetrics: null,

View File

@ -0,0 +1,213 @@
const ObservableStore = require('obs-store')
const Box = process.env.IN_TEST
? require('../../../development/mock-3box')
: require('3box')
// const Box = require(process.env.IN_TEST ? '../lib/mock-3box' : '3box/dist/3box.min')
const log = require('loglevel')
const JsonRpcEngine = require('json-rpc-engine')
const providerFromEngine = require('eth-json-rpc-middleware/providerFromEngine')
const createMetamaskMiddleware = require('./network/createMetamaskMiddleware')
const createOriginMiddleware = require('../lib/createOriginMiddleware')
const SYNC_TIMEOUT = 60 * 1000 // one minute
class ThreeBoxController {
constructor (opts = {}) {
const {
preferencesController,
keyringController,
addressBookController,
version,
getKeyringControllerState,
getSelectedAddress,
} = opts
this.preferencesController = preferencesController
this.addressBookController = addressBookController
this.keyringController = keyringController
this.provider = this._createProvider({
version,
getAccounts: async ({ origin }) => {
if (origin !== '3Box') { return [] }
const isUnlocked = getKeyringControllerState().isUnlocked
const selectedAddress = getSelectedAddress()
if (isUnlocked && selectedAddress) {
return [selectedAddress]
} else {
return []
}
},
processPersonalMessage: (msgParams) => {
return Promise.resolve(keyringController.signPersonalMessage(msgParams, {
withAppKeyOrigin: 'wallet://3box.metamask.io',
}))
},
})
const initState = {
threeBoxSyncingAllowed: true,
restoredFromThreeBox: null,
...opts.initState,
threeBoxAddress: null,
threeBoxSynced: false,
threeBoxDisabled: false,
}
this.store = new ObservableStore(initState)
this.registeringUpdates = false
const threeBoxFeatureFlagTurnedOn = this.preferencesController.getFeatureFlags().threeBox
if (threeBoxFeatureFlagTurnedOn) {
this.init()
}
}
async init () {
const accounts = await this.keyringController.getAccounts()
this.address = accounts[0]
if (this.address && !(this.box && this.store.getState().threeBoxSynced)) {
await this.new3Box()
}
}
async _update3Box ({ type }, newState) {
try {
const { threeBoxSyncingAllowed, threeBoxSynced } = this.store.getState()
if (threeBoxSyncingAllowed && threeBoxSynced) {
await this.space.private.set('lastUpdated', Date.now())
await this.space.private.set(type, JSON.stringify(newState))
}
} catch (error) {
console.error(error)
}
}
_createProvider (providerOpts) {
const metamaskMiddleware = createMetamaskMiddleware(providerOpts)
const engine = new JsonRpcEngine()
engine.push(createOriginMiddleware({ origin: '3Box' }))
engine.push(metamaskMiddleware)
const provider = providerFromEngine(engine)
return provider
}
_waitForOnSyncDone () {
return new Promise((resolve) => {
this.box.onSyncDone(() => {
log.debug('3Box box sync done')
return resolve()
})
})
}
async new3Box () {
const accounts = await this.keyringController.getAccounts()
const address = accounts[0]
if (this.getThreeBoxSyncingState()) {
this.store.updateState({ threeBoxSynced: false })
this.address = await this.keyringController.getAppKeyAddress(address, 'wallet://3box.metamask.io')
let timedOut = false
const syncTimeout = setTimeout(() => {
log.error(`3Box sync timed out after ${SYNC_TIMEOUT} ms`)
timedOut = true
this.store.updateState({
threeBoxDisabled: true,
threeBoxSyncingAllowed: false,
})
}, SYNC_TIMEOUT)
try {
this.box = await Box.openBox(address, this.provider)
await this._waitForOnSyncDone()
this.space = await this.box.openSpace('metamask', {
onSyncDone: async () => {
const stateUpdate = {
threeBoxSynced: true,
threeBoxAddress: address,
}
if (timedOut) {
log.info(`3Box sync completed after timeout; no longer disabled`)
stateUpdate.threeBoxDisabled = false
}
clearTimeout(syncTimeout)
this.store.updateState(stateUpdate)
log.debug('3Box space sync done')
},
})
} catch (e) {
console.error(e)
throw e
}
}
}
async getLastUpdated () {
return await this.space.private.get('lastUpdated')
}
async restoreFromThreeBox () {
this.setRestoredFromThreeBoxToTrue()
const backedUpPreferences = await this.space.private.get('preferences')
backedUpPreferences && this.preferencesController.store.updateState(JSON.parse(backedUpPreferences))
const backedUpAddressBook = await this.space.private.get('addressBook')
backedUpAddressBook && this.addressBookController.update(JSON.parse(backedUpAddressBook), true)
}
turnThreeBoxSyncingOn () {
this._registerUpdates()
}
turnThreeBoxSyncingOff () {
this.box.logout()
}
setRestoredFromThreeBoxToTrue () {
this.store.updateState({ restoredFromThreeBox: true })
}
setRestoredFromThreeBoxToFalse () {
this.store.updateState({ restoredFromThreeBox: false })
}
setThreeBoxSyncingPermission (newThreeboxSyncingState) {
if (this.store.getState().threeBoxDisabled) {
return
}
this.store.updateState({
threeBoxSyncingAllowed: newThreeboxSyncingState,
})
if (newThreeboxSyncingState && this.box) {
this.turnThreeBoxSyncingOn()
}
if (!newThreeboxSyncingState && this.box) {
this.turnThreeBoxSyncingOff()
}
}
getThreeBoxSyncingState () {
return this.store.getState().threeBoxSyncingAllowed
}
getThreeBoxAddress () {
return this.store.getState().threeBoxAddress
}
_registerUpdates () {
if (!this.registeringUpdates) {
const updatePreferences = this._update3Box.bind(this, { type: 'preferences' })
this.preferencesController.store.subscribe(updatePreferences)
const updateAddressBook = this._update3Box.bind(this, { type: 'addressBook' })
this.addressBookController.subscribe(updateAddressBook)
this.registeringUpdates = true
}
}
}
module.exports = ThreeBoxController

View File

@ -228,7 +228,7 @@ module.exports = class PersonalMessageManager extends EventEmitter {
*/
_setMsgStatus (msgId, status) {
const msg = this.getMsg(msgId)
if (!msg) throw new Error('PersonalMessageManager - Message not found for id: "${msgId}".')
if (!msg) throw new Error(`PersonalMessageManager - Message not found for id: "${msgId}".`)
msg.status = status
this._updateMsg(msg)
this.emit(`${msgId}:${status}`, msg)

View File

@ -29,6 +29,7 @@ const AppStateController = require('./controllers/app-state')
const InfuraController = require('./controllers/infura')
const CachedBalancesController = require('./controllers/cached-balances')
const OnboardingController = require('./controllers/onboarding')
const ThreeBoxController = require('./controllers/threebox')
const RecentBlocksController = require('./controllers/recent-blocks')
const IncomingTransactionsController = require('./controllers/incoming-transactions')
const MessageManager = require('./lib/message-manager')
@ -198,6 +199,16 @@ module.exports = class MetamaskController extends EventEmitter {
this.addressBookController = new AddressBookController(undefined, initState.AddressBookController)
this.threeBoxController = new ThreeBoxController({
preferencesController: this.preferencesController,
addressBookController: this.addressBookController,
keyringController: this.keyringController,
initState: initState.ThreeBoxController,
getKeyringControllerState: this.keyringController.memStore.getState.bind(this.keyringController.memStore),
getSelectedAddress: this.preferencesController.getSelectedAddress.bind(this.preferencesController),
version,
})
// tx mgmt
this.txController = new TransactionController({
initState: initState.TransactionController || initState.TransactionManager,
@ -273,6 +284,7 @@ module.exports = class MetamaskController extends EventEmitter {
OnboardingController: this.onboardingController.store,
ProviderApprovalController: this.providerApprovalController.store,
IncomingTransactionsController: this.incomingTransactionsController.store,
ThreeBoxController: this.threeBoxController.store,
})
this.memStore = new ComposableObservableStore(null, {
@ -297,6 +309,8 @@ module.exports = class MetamaskController extends EventEmitter {
ProviderApprovalController: this.providerApprovalController.store,
ProviderApprovalControllerMemStore: this.providerApprovalController.memStore,
IncomingTransactionsController: this.incomingTransactionsController.store,
// ThreeBoxController
ThreeBoxController: this.threeBoxController.store,
})
this.memStore.subscribe(this.sendUpdate.bind(this))
}
@ -411,6 +425,7 @@ module.exports = class MetamaskController extends EventEmitter {
const networkController = this.networkController
const providerApprovalController = this.providerApprovalController
const onboardingController = this.onboardingController
const threeBoxController = this.threeBoxController
return {
// etc
@ -516,6 +531,14 @@ module.exports = class MetamaskController extends EventEmitter {
// onboarding controller
setSeedPhraseBackedUp: nodeify(onboardingController.setSeedPhraseBackedUp, onboardingController),
// 3Box
setThreeBoxSyncingPermission: nodeify(threeBoxController.setThreeBoxSyncingPermission, threeBoxController),
restoreFromThreeBox: nodeify(threeBoxController.restoreFromThreeBox, threeBoxController),
setRestoredFromThreeBoxToFalse: nodeify(threeBoxController.setRestoredFromThreeBoxToFalse, threeBoxController),
getThreeBoxLastUpdated: nodeify(threeBoxController.getLastUpdated, threeBoxController),
turnThreeBoxSyncingOn: nodeify(threeBoxController.turnThreeBoxSyncingOn, threeBoxController),
initializeThreeBox: nodeify(this.initializeThreeBox, this),
}
}
@ -717,6 +740,19 @@ module.exports = class MetamaskController extends EventEmitter {
await this.preferencesController.syncAddresses(accounts)
await this.txController.pendingTxTracker.updatePendingTxs()
const threeBoxFeatureFlagTurnedOn = this.preferencesController.getFeatureFlags().threeBox
if (threeBoxFeatureFlagTurnedOn) {
const threeBoxSyncingAllowed = this.threeBoxController.getThreeBoxSyncingState()
if (threeBoxSyncingAllowed && !this.threeBoxController.box) {
await this.threeBoxController.new3Box()
this.threeBoxController.turnThreeBoxSyncingOn()
} else if (threeBoxSyncingAllowed && this.threeBoxController.box) {
this.threeBoxController.turnThreeBoxSyncingOn()
}
}
return this.keyringController.fullUpdate()
}
@ -1666,6 +1702,10 @@ module.exports = class MetamaskController extends EventEmitter {
await this.preferencesController.removeFromFrequentRpcList(rpcTarget)
}
async initializeThreeBox () {
await this.threeBoxController.new3Box()
}
/**
* Sets whether or not to use the blockie identicon format.
* @param {boolean} val - True for bockie, false for jazzicon.

View File

@ -33,7 +33,7 @@ async function start () {
}).join(', ')
// links to bundle browser builds
const bundles = ['background', 'ui', 'inpage', 'contentscript', 'libs', 'phishing-detect']
const bundles = ['background', 'ui', 'inpage', 'contentscript', 'ui-libs', 'bg-libs', 'phishing-detect']
const bundleLinks = bundles.map(bundle => {
const url = `${BUILD_LINK_BASE}/build-artifacts/source-map-explorer/${bundle}.html`
return `<a href="${url}">${bundle}</a>`

60
development/mock-3box.js Normal file
View File

@ -0,0 +1,60 @@
function delay (time) {
return new Promise(resolve => setTimeout(resolve, time))
}
function loadFromMock3Box (key) {
return new Promise(async (resolve) => {
const res = await fetch('http://localhost:8889?key=' + key)
const text = await res.text()
resolve(text.length ? JSON.parse(text) : null)
})
}
function saveToMock3Box (key, newDataAtKey) {
return new Promise(async (resolve) => {
const res = await fetch('http://localhost:8889', {
method: 'POST',
body: JSON.stringify({
key,
data: newDataAtKey,
}),
})
resolve(res.text())
})
}
class Mock3Box {
static openBox (address) {
this.address = address
return Promise.resolve({
onSyncDone: cb => { setTimeout(cb, 200) },
openSpace: async (spaceName, config) => {
const { onSyncDone } = config
this.spaceName = spaceName
setTimeout(onSyncDone, 150)
await delay(50)
return {
private: {
get: async (key) => {
await delay(50)
const res = await loadFromMock3Box(`${this.address}-${this.spaceName}-${key}`)
return res
},
set: async (key, data) => {
await saveToMock3Box(`${this.address}-${this.spaceName}-${key}`, data)
await delay(50)
return null
},
},
}
},
logout: () => {},
})
}
}
module.exports = Mock3Box

View File

@ -33,11 +33,14 @@ const materialUIDependencies = ['@material-ui/core']
const reactDepenendencies = dependencies.filter(dep => dep.match(/react/))
const d3Dependencies = ['c3', 'd3']
const uiDependenciesToBundle = [
...materialUIDependencies,
...reactDepenendencies,
...d3Dependencies,
]
const externalDependenciesMap = {
background: [
'3box',
],
ui: [
...materialUIDependencies, ...reactDepenendencies, ...d3Dependencies,
],
}
function gulpParallel (...args) {
return function spawnGulpChildProcess (cb) {
@ -49,7 +52,6 @@ const browserPlatforms = [
'firefox',
'chrome',
'brave',
'edge',
'opera',
]
const commonPlatforms = [
@ -188,7 +190,6 @@ gulp.task('manifest:production', function () {
'./dist/firefox/manifest.json',
'./dist/chrome/manifest.json',
'./dist/brave/manifest.json',
'./dist/edge/manifest.json',
'./dist/opera/manifest.json',
], {base: './dist/'})
@ -211,6 +212,47 @@ gulp.task('manifest:testing', function () {
// Exclude chromereload script in production:
.pipe(jsoneditor(function (json) {
json.permissions = [...json.permissions, 'webRequestBlocking', 'http://localhost/*']
return json
}))
.pipe(gulp.dest('./dist/', { overwrite: true }))
})
const scriptsToExcludeFromBackgroundDevBuild = {
'bg-libs.js': true,
}
gulp.task('manifest:testing-local', function () {
return gulp.src([
'./dist/firefox/manifest.json',
'./dist/chrome/manifest.json',
], {base: './dist/'})
.pipe(jsoneditor(function (json) {
json.background = {
...json.background,
scripts: json.background.scripts.filter(scriptName => !scriptsToExcludeFromBackgroundDevBuild[scriptName]),
}
json.permissions = [...json.permissions, 'webRequestBlocking', 'http://localhost/*']
return json
}))
.pipe(gulp.dest('./dist/', { overwrite: true }))
})
gulp.task('manifest:dev', function () {
return gulp.src([
'./dist/firefox/manifest.json',
'./dist/chrome/manifest.json',
], {base: './dist/'})
.pipe(jsoneditor(function (json) {
json.background = {
...json.background,
scripts: json.background.scripts.filter(scriptName => !scriptsToExcludeFromBackgroundDevBuild[scriptName]),
}
json.permissions = [...json.permissions, 'webRequestBlocking']
return json
}))
@ -230,6 +272,7 @@ gulp.task('copy',
gulp.task('dev:copy',
gulp.series(
gulp.parallel(...copyDevTaskNames),
'manifest:dev',
'manifest:chrome',
'manifest:opera'
)
@ -240,7 +283,7 @@ gulp.task('test:copy',
gulp.parallel(...copyDevTaskNames),
'manifest:chrome',
'manifest:opera',
'manifest:testing'
'manifest:testing-local'
)
)
@ -324,16 +367,16 @@ const buildJsFiles = [
]
// bundle tasks
createTasksForBuildJsUIDeps({ dependenciesToBundle: uiDependenciesToBundle, filename: 'libs' })
createTasksForBuildJsDeps({ filename: 'bg-libs', key: 'background' })
createTasksForBuildJsDeps({ filename: 'ui-libs', key: 'ui' })
createTasksForBuildJsExtension({ buildJsFiles, taskPrefix: 'dev:extension:js', devMode: true })
createTasksForBuildJsExtension({ buildJsFiles, taskPrefix: 'dev:test-extension:js', devMode: true, testing: 'true' })
createTasksForBuildJsExtension({ buildJsFiles, taskPrefix: 'build:extension:js' })
createTasksForBuildJsExtension({ buildJsFiles, taskPrefix: 'build:test:extension:js', testing: 'true' })
function createTasksForBuildJsUIDeps ({ filename }) {
function createTasksForBuildJsDeps ({ key, filename }) {
const destinations = browserPlatforms.map(platform => `./dist/${platform}`)
const bundleTaskOpts = Object.assign({
buildSourceMaps: true,
sourceMapDir: '../sourcemaps',
@ -341,12 +384,12 @@ function createTasksForBuildJsUIDeps ({ filename }) {
devMode: false,
})
gulp.task('build:extension:js:uideps', bundleTask(Object.assign({
gulp.task(`build:extension:js:deps:${key}`, bundleTask(Object.assign({
label: filename,
filename: `${filename}.js`,
destinations,
buildLib: true,
dependenciesToBundle: uiDependenciesToBundle,
dependenciesToBundle: externalDependenciesMap[key],
}, bundleTaskOpts)))
}
@ -378,7 +421,7 @@ function createTasksForBuildJs ({ rootDir, taskPrefix, bundleTaskOpts, destinati
label: jsFile,
filename: `${jsFile}.js`,
filepath: `${rootDir}/${jsFile}.js`,
externalDependencies: jsFile === 'ui' && !bundleTaskOpts.devMode && uiDependenciesToBundle,
externalDependencies: bundleTaskOpts.devMode ? undefined : externalDependenciesMap[jsFile],
destinations,
}, bundleTaskOpts)))
})
@ -399,9 +442,8 @@ gulp.task('clean', function clean () {
// zip tasks for distribution
gulp.task('zip:chrome', zipTask('chrome'))
gulp.task('zip:firefox', zipTask('firefox'))
gulp.task('zip:edge', zipTask('edge'))
gulp.task('zip:opera', zipTask('opera'))
gulp.task('zip', gulp.parallel('zip:chrome', 'zip:firefox', 'zip:edge', 'zip:opera'))
gulp.task('zip', gulp.parallel('zip:chrome', 'zip:firefox', 'zip:opera'))
// high level tasks
@ -446,7 +488,8 @@ gulp.task('build',
'clean',
'build:scss',
gulpParallel(
'build:extension:js:uideps',
'build:extension:js:deps:background',
'build:extension:js:deps:ui',
'build:extension:js',
'copy'
)
@ -458,7 +501,8 @@ gulp.task('build:test',
'clean',
'build:scss',
gulpParallel(
'build:extension:js:uideps',
'build:extension:js:deps:background',
'build:extension:js:deps:ui',
'build:test:extension:js',
'copy'
),
@ -526,6 +570,16 @@ function generateBundler (opts, performBundle) {
let bundler = browserify(browserifyOpts)
.transform('babelify')
// Transpile any dependencies using the object spread/rest operator
// because it is incompatible with `esprima`, which is used by `envify`
// See https://github.com/jquery/esprima/issues/1927
.transform('babelify', {
only: [
'./**/node_modules/libp2p',
],
global: true,
plugins: ['@babel/plugin-proposal-object-rest-spread'],
})
.transform('brfs')
if (opts.buildLib) {
@ -536,7 +590,7 @@ function generateBundler (opts, performBundle) {
bundler = bundler.external(opts.externalDependencies)
}
// inject variables into bundle
// Inject variables into bundle
bundler.transform(envify({
METAMASK_DEBUG: opts.devMode,
NODE_ENV: opts.devMode ? 'development' : 'production',

View File

@ -47,11 +47,15 @@
"update-changelog": "./development/auto-changelog.sh",
"rollback": "./development/rollback.sh"
},
"resolutions": {
"3box/ipfs/ipld-zcash/zcash-bitcore-lib/lodash": "^4.17.12"
},
"dependencies": {
"@babel/runtime": "^7.5.5",
"@material-ui/core": "1.0.0",
"@sentry/browser": "^4.1.1",
"@zxing/library": "^0.8.0",
"3box": "^1.10.2",
"abi-decoder": "^1.2.0",
"abortcontroller-polyfill": "^1.3.0",
"asmcrypto.js": "^2.3.2",
@ -84,7 +88,7 @@
"eth-json-rpc-filters": "^4.1.0",
"eth-json-rpc-infura": "^4.0.1",
"eth-json-rpc-middleware": "^4.2.0",
"eth-keyring-controller": "^5.0.1",
"eth-keyring-controller": "^5.1.0",
"eth-ledger-bridge-keyring": "^0.2.0",
"eth-method-registry": "^1.2.0",
"eth-phishing-detect": "^1.1.4",

View File

@ -0,0 +1,36 @@
const http = require('http')
const url = require('url')
const port = 8889
const database = {}
const requestHandler = (request, response) => {
response.setHeader('Content-Type', 'application/json')
if (request.method === 'POST') {
let body = ''
request.on('data', chunk => {
body += chunk.toString() // convert Buffer to string
})
request.on('end', () => {
const { key, data } = JSON.parse(body)
database[key] = data
response.setHeader('Access-Control-Allow-Headers', '*')
response.end('ok')
})
} else if (request.method === 'GET') {
const { key } = url.parse(request.url, true).query
response.setHeader('Access-Control-Allow-Headers', '*')
response.end(JSON.stringify(database[key] || ''))
} else {
response.end('unknown request')
}
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('mock 3box server error: ', err)
}
})

View File

@ -72,3 +72,13 @@ concurrently --kill-others \
'yarn dapp' \
'sleep 5 && mocha test/e2e/address-book.spec'
export GANACHE_ARGS="${BASE_GANACHE_ARGS} --deterministic --account=0x53CB0AB5226EEBF4D872113D98332C1555DC304443BEE1CF759D15798D3C55A9,25000000000000000000"
concurrently --kill-others \
--names 'ganache,dapp,e2e' \
--prefix '[{time}][{name}]' \
--success first \
'node test/e2e/mock-3box/server.js' \
'yarn ganache:start' \
'yarn dapp' \
'sleep 5 && mocha test/e2e/threebox.spec'

254
test/e2e/threebox.spec.js Normal file
View File

@ -0,0 +1,254 @@
const assert = require('assert')
const webdriver = require('selenium-webdriver')
const { By, until } = webdriver
const {
delay,
} = require('./func')
const {
checkBrowserForConsoleErrors,
findElement,
findElements,
verboseReportOnFailure,
setupFetchMocking,
prepareExtensionForTesting,
} = require('./helpers')
describe('MetaMask', function () {
let driver
const testSeedPhrase = 'forum vessel pink push lonely enact gentle tail admit parrot grunt dress'
const tinyDelayMs = 200
const regularDelayMs = tinyDelayMs * 2
const largeDelayMs = regularDelayMs * 2
this.timeout(0)
this.bail(true)
before(async function () {
const result = await prepareExtensionForTesting()
driver = result.driver
await setupFetchMocking(driver)
})
afterEach(async function () {
if (process.env.SELENIUM_BROWSER === 'chrome') {
const errors = await checkBrowserForConsoleErrors(driver)
if (errors.length) {
const errorReports = errors.map(err => err.message)
const errorMessage = `Errors found in browser console:\n${errorReports.join('\n')}`
console.error(new Error(errorMessage))
}
}
if (this.currentTest.state === 'failed') {
await verboseReportOnFailure(driver, this.currentTest)
}
})
after(async function () {
await driver.quit()
})
describe('set up data to be restored by 3box', () => {
describe('First time flow starting from an existing seed phrase', () => {
it('turns on the threebox feature flag', async () => {
await delay(largeDelayMs)
await driver.executeScript('window.metamask.setFeatureFlag("threeBox", true)')
await delay(largeDelayMs)
})
it('clicks the continue button on the welcome screen', async () => {
await findElement(driver, By.css('.welcome-page__header'))
const welcomeScreenBtn = await findElement(driver, By.css('.first-time-flow__button'))
welcomeScreenBtn.click()
await delay(largeDelayMs)
})
it('clicks the "Import Wallet" option', async () => {
const customRpcButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Import Wallet')]`))
customRpcButton.click()
await delay(largeDelayMs)
})
it('clicks the "No thanks" option on the metametrics opt-in screen', async () => {
const optOutButton = await findElement(driver, By.css('.btn-default'))
optOutButton.click()
await delay(largeDelayMs)
})
it('imports a seed phrase', async () => {
const [seedTextArea] = await findElements(driver, By.css('textarea.first-time-flow__textarea'))
await seedTextArea.sendKeys(testSeedPhrase)
await delay(regularDelayMs)
const [password] = await findElements(driver, By.id('password'))
await password.sendKeys('correct horse battery staple')
const [confirmPassword] = await findElements(driver, By.id('confirm-password'))
confirmPassword.sendKeys('correct horse battery staple')
const tosCheckBox = await findElement(driver, By.css('.first-time-flow__checkbox'))
await tosCheckBox.click()
const [importButton] = await findElements(driver, By.xpath(`//button[contains(text(), 'Import')]`))
await importButton.click()
await delay(regularDelayMs)
})
it('clicks through the success screen', async () => {
await findElement(driver, By.xpath(`//div[contains(text(), 'Congratulations')]`))
const doneButton = await findElement(driver, By.css('button.first-time-flow__button'))
await doneButton.click()
await delay(regularDelayMs)
})
it('balance renders', async () => {
const balance = await findElement(driver, By.css('.balance-display .token-amount'))
await driver.wait(until.elementTextMatches(balance, /25\s*ETH/))
await delay(regularDelayMs)
})
})
describe('updates settings and address book', () => {
it('goes to the settings screen', async () => {
await driver.findElement(By.css('.account-menu__icon')).click()
await delay(regularDelayMs)
const settingsButton = await findElement(driver, By.xpath(`//div[contains(text(), 'Settings')]`))
settingsButton.click()
})
it('turns on use of blockies', async () => {
const toggleButton = await findElement(driver, By.css('.toggle-button > div'))
await toggleButton.click()
})
it('adds an address to the contact list', async () => {
const contactsButton = await findElement(driver, By.xpath(`//div[contains(text(), 'Contacts')]`))
await contactsButton.click()
const addressBookAddButton = await findElement(driver, By.css('.address-book-add-button__button'))
await addressBookAddButton.click()
await delay(tinyDelayMs)
const addAddressInputs = await findElements(driver, By.css('input'))
await addAddressInputs[0].sendKeys('Test User Name 11')
await delay(tinyDelayMs)
await addAddressInputs[1].sendKeys('0x2f318C334780961FB129D2a6c30D0763d9a5C970')
await delay(largeDelayMs * 2)
const saveButton = await findElement(driver, By.xpath(`//button[contains(text(), 'Save')]`))
await saveButton.click()
await findElement(driver, By.xpath(`//div[contains(text(), 'Test User Name 11')]`))
await delay(regularDelayMs)
})
})
})
describe('restoration from 3box', () => {
let driver2
before(async function () {
const result = await prepareExtensionForTesting()
driver2 = result.driver
await setupFetchMocking(driver2)
})
after(async function () {
await driver2.quit()
})
describe('First time flow starting from an existing seed phrase', () => {
it('turns on the threebox feature flag', async () => {
await delay(largeDelayMs)
await driver2.executeScript('window.metamask.setFeatureFlag("threeBox", true)')
await delay(largeDelayMs)
})
it('clicks the continue button on the welcome screen', async () => {
await findElement(driver2, By.css('.welcome-page__header'))
const welcomeScreenBtn = await findElement(driver2, By.css('.first-time-flow__button'))
welcomeScreenBtn.click()
await delay(largeDelayMs)
})
it('clicks the "Import Wallet" option', async () => {
const customRpcButton = await findElement(driver2, By.xpath(`//button[contains(text(), 'Import Wallet')]`))
customRpcButton.click()
await delay(largeDelayMs)
})
it('clicks the "No thanks" option on the metametrics opt-in screen', async () => {
const optOutButton = await findElement(driver2, By.css('.btn-default'))
optOutButton.click()
await delay(largeDelayMs)
})
it('imports a seed phrase', async () => {
const [seedTextArea] = await findElements(driver2, By.css('textarea.first-time-flow__textarea'))
await seedTextArea.sendKeys(testSeedPhrase)
await delay(regularDelayMs)
const [password] = await findElements(driver2, By.id('password'))
await password.sendKeys('correct horse battery staple')
const [confirmPassword] = await findElements(driver2, By.id('confirm-password'))
confirmPassword.sendKeys('correct horse battery staple')
const tosCheckBox = await findElement(driver2, By.css('.first-time-flow__checkbox'))
await tosCheckBox.click()
const [importButton] = await findElements(driver2, By.xpath(`//button[contains(text(), 'Import')]`))
await importButton.click()
await delay(regularDelayMs)
})
it('clicks through the success screen', async () => {
await findElement(driver2, By.xpath(`//div[contains(text(), 'Congratulations')]`))
const doneButton = await findElement(driver2, By.css('button.first-time-flow__button'))
await doneButton.click()
await delay(regularDelayMs)
})
it('balance renders', async () => {
const balance = await findElement(driver2, By.css('.balance-display .token-amount'))
await driver2.wait(until.elementTextMatches(balance, /25\s*ETH/))
await delay(regularDelayMs)
})
})
describe('restores 3box data', () => {
it('confirms the 3box restore notification', async () => {
const restoreButton = await findElement(driver2, By.css('.home-notification__accept-button'))
await restoreButton.click()
})
it('goes to the settings screen', async () => {
await driver.findElement(By.css('.account-menu__icon')).click()
await delay(regularDelayMs)
const settingsButton = await findElement(driver, By.xpath(`//div[contains(text(), 'Settings')]`))
settingsButton.click()
})
it('finds the blockies toggle turned on', async () => {
await delay(regularDelayMs)
const toggleLabel = await findElement(driver, By.css('.toggle-button__status-label'))
const toggleLabelText = await toggleLabel.getText()
assert.equal(toggleLabelText, 'ON')
})
it('finds the restored address in the contact list', async () => {
const contactsButton = await findElement(driver, By.xpath(`//div[contains(text(), 'Contacts')]`))
await contactsButton.click()
await delay(regularDelayMs)
await findElement(driver, By.xpath(`//div[contains(text(), 'Test User Name 11')]`))
await delay(regularDelayMs)
})
})
})
})

View File

@ -5,3 +5,6 @@ require('@babel/register')({
require('./helper')
window.SVGPathElement = window.SVGPathElement || { prototype: {} }
window.fetch = window.fetch || function fetch () { return Promise.resolve() }
global.indexedDB = {}
global.fetch = global.fetch || function fetch () { return Promise.resolve() }

View File

@ -4,11 +4,37 @@ const clone = require('clone')
const nock = require('nock')
const createThoughStream = require('through2').obj
const blacklistJSON = require('eth-phishing-detect/src/config')
const MetaMaskController = require('../../../../app/scripts/metamask-controller')
const firstTimeState = require('../../../unit/localhostState')
const createTxMeta = require('../../../lib/createTxMeta')
const EthQuery = require('eth-query')
const threeBoxSpies = {
new3Box: sinon.spy(),
getThreeBoxAddress: sinon.spy(),
getThreeBoxSyncingState: sinon.stub().returns(true),
turnThreeBoxSyncingOn: sinon.spy(),
_registerUpdates: sinon.spy(),
}
const proxyquire = require('proxyquire')
class ThreeBoxControllerMock {
constructor () {
this.store = {
subscribe: () => {},
getState: () => ({}),
}
this.new3Box = threeBoxSpies.new3Box
this.getThreeBoxAddress = threeBoxSpies.getThreeBoxAddress
this.getThreeBoxSyncingState = threeBoxSpies.getThreeBoxSyncingState
this.turnThreeBoxSyncingOn = threeBoxSpies.turnThreeBoxSyncingOn
this._registerUpdates = threeBoxSpies._registerUpdates
}
}
const MetaMaskController = proxyquire('../../../../app/scripts/metamask-controller', {
'./controllers/threebox': ThreeBoxControllerMock,
})
const currentNetworkId = 42
const DEFAULT_LABEL = 'Account 1'
const DEFAULT_LABEL_2 = 'Account 2'
@ -82,6 +108,8 @@ describe('MetaMaskController', function () {
beforeEach(async function () {
await metamaskController.createNewVaultAndKeychain(password)
threeBoxSpies.new3Box.reset()
threeBoxSpies.turnThreeBoxSyncingOn.reset()
})
it('removes any identities that do not correspond to known accounts.', async function () {
@ -100,6 +128,19 @@ describe('MetaMaskController', function () {
assert.ok(identities.includes(address), `identities should include all Addresses: ${address}`)
})
})
it('gets does not instantiate 3box if the feature flag is false', async () => {
await metamaskController.submitPassword(password)
assert(threeBoxSpies.new3Box.notCalled)
assert(threeBoxSpies.turnThreeBoxSyncingOn.notCalled)
})
it('gets the address from threebox and creates a new 3box instance if the feature flag is true', async () => {
metamaskController.preferencesController.setFeatureFlag('threeBox', true)
await metamaskController.submitPassword(password)
assert(threeBoxSpies.new3Box.calledOnce)
assert(threeBoxSpies.turnThreeBoxSyncingOn.calledOnce)
})
})
describe('#getGasPrice', function () {

View File

@ -55,6 +55,12 @@ describe('Actions', () => {
initState: clone(firstTimeState),
})
metamaskController.threeBoxController = {
new3Box: sinon.spy(),
getThreeBoxAddress: sinon.spy(),
getThreeBoxSyncingState: sinon.spy(),
}
await metamaskController.createNewVaultAndRestore(password, TEST_SEED)
await metamaskController.importAccountWithStrategy('Private Key', [ importPrivkey ])

View File

@ -3,10 +3,10 @@ const actions = require('../../store/actions')
const txHelper = require('../../../lib/tx-helper')
const log = require('loglevel')
module.exports = reduceApp
// Actions
const SET_THREEBOX_LAST_UPDATED = 'metamask/app/SET_THREEBOX_LAST_UPDATED'
function reduceApp (state, action) {
export default function reduceApp (state, action) {
log.debug('App Reducer got ' + action.type)
// clone and defaults
const selectedAddress = state.metamask.selectedAddress
@ -73,6 +73,8 @@ function reduceApp (state, action) {
networksTabSelectedRpcUrl: '',
networksTabIsInAddMode: false,
loadingMethodData: false,
show3BoxModalAfterImport: false,
threeBoxLastUpdated: null,
}, state.appState)
switch (action.type) {
@ -756,11 +758,25 @@ function reduceApp (state, action) {
loadingMethodData: false,
})
case SET_THREEBOX_LAST_UPDATED:
return extend(appState, {
threeBoxLastUpdated: action.value,
})
default:
return appState
}
}
// Action Creators
export function setThreeBoxLastUpdated (lastUpdated) {
return {
type: SET_THREEBOX_LAST_UPDATED,
value: lastUpdated,
}
}
// Helpers
function checkUnconfActions (state) {
const unconfActionList = getUnconfActionList(state)
const hasUnconfActions = unconfActionList.length > 0

View File

@ -6,9 +6,9 @@ const copyToClipboard = require('copy-to-clipboard')
// Sub-Reducers take in the complete state and return their sub-state
//
const reduceMetamask = require('./metamask/metamask')
const reduceApp = require('./app/app')
const reduceLocale = require('./locale/locale')
const reduceSend = require('./send/send.duck').default
import reduceApp from './app/app'
import reduceConfirmTransaction from './confirm-transaction/confirm-transaction.duck'
import reduceGas from './gas/gas.duck'

View File

@ -18,6 +18,7 @@ export default class ImportWithSeedPhrase extends PureComponent {
history: PropTypes.object,
onSubmit: PropTypes.func.isRequired,
setSeedPhraseBackedUp: PropTypes.func,
initializeThreeBox: PropTypes.func,
}
state = {
@ -127,7 +128,7 @@ export default class ImportWithSeedPhrase extends PureComponent {
}
const { password, seedPhrase } = this.state
const { history, onSubmit, setSeedPhraseBackedUp } = this.props
const { history, onSubmit, setSeedPhraseBackedUp, initializeThreeBox } = this.props
try {
await onSubmit(password, this.parseSeedPhrase(seedPhrase))
@ -140,6 +141,7 @@ export default class ImportWithSeedPhrase extends PureComponent {
})
setSeedPhraseBackedUp(true).then(() => {
initializeThreeBox()
history.push(INITIALIZE_END_OF_FLOW_ROUTE)
})
} catch (error) {

View File

@ -2,11 +2,13 @@ import { connect } from 'react-redux'
import ImportWithSeedPhrase from './import-with-seed-phrase.component'
import {
setSeedPhraseBackedUp,
initializeThreeBox,
} from '../../../../store/actions'
const mapDispatchToProps = dispatch => {
return {
setSeedPhraseBackedUp: (seedPhraseBackupState) => dispatch(setSeedPhraseBackedUp(seedPhraseBackupState)),
initializeThreeBox: () => dispatch(initializeThreeBox()),
}
}

View File

@ -77,8 +77,9 @@ export default class FirstTimeFlow extends PureComponent {
const { createNewAccountFromSeed } = this.props
try {
await createNewAccountFromSeed(password, seedPhrase)
const vault = await createNewAccountFromSeed(password, seedPhrase)
this.setState({ isImportedKeyring: true })
return vault
} catch (error) {
throw new Error(error.message)
}

View File

@ -27,6 +27,8 @@ export default class ConfirmSeedPhrase extends PureComponent {
history: PropTypes.object,
onSubmit: PropTypes.func,
seedPhrase: PropTypes.string,
selectedAddress: PropTypes.string,
initializeThreeBox: PropTypes.func,
}
state = {
@ -89,7 +91,13 @@ export default class ConfirmSeedPhrase extends PureComponent {
}
handleSubmit = async () => {
const { history, setSeedPhraseBackedUp, showingSeedPhraseBackupAfterOnboarding, hideSeedPhraseBackupAfterOnboarding } = this.props
const {
history,
setSeedPhraseBackedUp,
showingSeedPhraseBackupAfterOnboarding,
hideSeedPhraseBackupAfterOnboarding,
initializeThreeBox,
} = this.props
if (!this.isValid()) {
return
@ -109,6 +117,7 @@ export default class ConfirmSeedPhrase extends PureComponent {
hideSeedPhraseBackupAfterOnboarding()
history.push(DEFAULT_ROUTE)
} else {
initializeThreeBox()
history.push(INITIALIZE_END_OF_FLOW_ROUTE)
}
})

View File

@ -3,13 +3,16 @@ import ConfirmSeedPhrase from './confirm-seed-phrase.component'
import {
setSeedPhraseBackedUp,
hideSeedPhraseBackupAfterOnboarding,
initializeThreeBox,
} from '../../../../store/actions'
import { getSelectedAddress } from '../../../../selectors/selectors'
const mapStateToProps = state => {
const { appState: { showingSeedPhraseBackupAfterOnboarding } } = state
return {
showingSeedPhraseBackupAfterOnboarding,
selectedAddress: getSelectedAddress(state),
}
}
@ -17,6 +20,7 @@ const mapDispatchToProps = dispatch => {
return {
setSeedPhraseBackedUp: (seedPhraseBackupState) => dispatch(setSeedPhraseBackedUp(seedPhraseBackupState)),
hideSeedPhraseBackupAfterOnboarding: () => dispatch(hideSeedPhraseBackupAfterOnboarding()),
initializeThreeBox: () => dispatch(initializeThreeBox()),
}
}

View File

@ -135,11 +135,13 @@ describe('ConfirmSeedPhrase Component', () => {
const originalSeed = ['鼠', '牛', '虎', '兔', '龍', '蛇', '馬', '羊', '猴', '雞', '狗', '豬']
const metricsEventSpy = sinon.spy()
const pushSpy = sinon.spy()
const initialize3BoxSpy = sinon.spy()
const root = shallowRender(
{
seedPhrase: '鼠 牛 虎 兔 龍 蛇 馬 羊 猴 雞 狗 豬',
history: { push: pushSpy },
setSeedPhraseBackedUp: () => Promise.resolve(),
initializeThreeBox: initialize3BoxSpy,
},
{
metricsEvent: metricsEventSpy,
@ -168,6 +170,7 @@ describe('ConfirmSeedPhrase Component', () => {
name: 'Verify Complete',
},
})
assert(initialize3BoxSpy.calledOnce)
assert.equal(pushSpy.args[0][0], '/initialize/end-of-flow')
})
})

View File

@ -2,6 +2,7 @@ import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import Media from 'react-media'
import { Redirect } from 'react-router-dom'
import { formatDate } from '../../helpers/utils/util'
import HomeNotification from '../../components/app/home-notification'
import MultipleNotifications from '../../components/app/multiple-notifications'
import WalletView from '../../components/app/wallet-view'
@ -34,6 +35,15 @@ export default class Home extends PureComponent {
unsetMigratedPrivacyMode: PropTypes.func,
shouldShowSeedPhraseReminder: PropTypes.bool,
isPopup: PropTypes.bool,
threeBoxSynced: PropTypes.bool,
setupThreeBox: PropTypes.func,
turnThreeBoxSyncingOn: PropTypes.func,
restoredFromThreeBox: PropTypes.bool,
selectedAddress: PropTypes.string,
restoreFromThreeBox: PropTypes.func,
setRestoredFromThreeBoxToFalse: PropTypes.func,
threeBoxLastUpdated: PropTypes.string,
threeBoxFeatureFlagIsTrue: PropTypes.bool,
}
componentWillMount () {
@ -59,6 +69,18 @@ export default class Home extends PureComponent {
}
}
componentDidUpdate () {
const {
threeBoxSynced,
setupThreeBox,
restoredFromThreeBox,
threeBoxLastUpdated,
} = this.props
if (threeBoxSynced && restoredFromThreeBox === null && threeBoxLastUpdated === null) {
setupThreeBox()
}
}
render () {
const { t } = this.context
const {
@ -69,6 +91,13 @@ export default class Home extends PureComponent {
unsetMigratedPrivacyMode,
shouldShowSeedPhraseReminder,
isPopup,
selectedAddress,
restoreFromThreeBox,
turnThreeBoxSyncingOn,
setRestoredFromThreeBoxToFalse,
restoredFromThreeBox,
threeBoxLastUpdated,
threeBoxFeatureFlagIsTrue,
} = this.props
if (forgottenPassword) {
@ -125,6 +154,25 @@ export default class Home extends PureComponent {
key="home-backupApprovalNotice"
/>,
},
{
shouldBeRendered: threeBoxFeatureFlagIsTrue && threeBoxLastUpdated && restoredFromThreeBox === null,
component: <HomeNotification
descriptionText={t('restoreWalletPreferences', [ formatDate(parseInt(threeBoxLastUpdated), 'M/d/y') ])}
acceptText={t('restore')}
ignoreText={t('noThanks')}
infoText={t('dataBackupFoundInfo')}
onAccept={() => {
restoreFromThreeBox(selectedAddress)
.then(() => {
turnThreeBoxSyncingOn()
})
}}
onIgnore={() => {
setRestoredFromThreeBoxToFalse()
}}
key="home-privacyModeDefault"
/>,
},
]}/>
</TransactionView>
)

View File

@ -6,7 +6,12 @@ import { unconfirmedTransactionsCountSelector } from '../../selectors/confirm-tr
import { getCurrentEthBalance } from '../../selectors/selectors'
import {
unsetMigratedPrivacyMode,
restoreFromThreeBox,
turnThreeBoxSyncingOn,
getThreeBoxLastUpdated,
setRestoredFromThreeBoxToFalse,
} from '../../store/actions'
import { setThreeBoxLastUpdated } from '../../ducks/app/app'
import { getEnvironmentType } from '../../../../app/scripts/lib/util'
import { ENVIRONMENT_TYPE_POPUP } from '../../../../app/scripts/lib/enums'
@ -18,9 +23,13 @@ const mapStateToProps = state => {
migratedPrivacyMode,
seedPhraseBackedUp,
tokens,
threeBoxSynced,
restoredFromThreeBox,
selectedAddress,
featureFlags,
} = metamask
const accountBalance = getCurrentEthBalance(state)
const { forgottenPassword } = appState
const { forgottenPassword, threeBoxLastUpdated } = appState
const isPopup = getEnvironmentType(window.location.href) === ENVIRONMENT_TYPE_POPUP
@ -32,11 +41,30 @@ const mapStateToProps = state => {
showPrivacyModeNotification: migratedPrivacyMode,
shouldShowSeedPhraseReminder: !seedPhraseBackedUp && (parseInt(accountBalance, 16) > 0 || tokens.length > 0),
isPopup,
threeBoxSynced,
restoredFromThreeBox,
selectedAddress,
threeBoxLastUpdated,
threeBoxFeatureFlagIsTrue: featureFlags.threeBox,
}
}
const mapDispatchToProps = (dispatch) => ({
unsetMigratedPrivacyMode: () => dispatch(unsetMigratedPrivacyMode()),
turnThreeBoxSyncingOn: () => dispatch(turnThreeBoxSyncingOn()),
setupThreeBox: () => {
dispatch(getThreeBoxLastUpdated())
.then(lastUpdated => {
if (lastUpdated) {
dispatch(setThreeBoxLastUpdated(lastUpdated))
} else {
dispatch(setRestoredFromThreeBoxToFalse())
dispatch(turnThreeBoxSyncingOn())
}
})
},
restoreFromThreeBox: (address) => dispatch(restoreFromThreeBox(address)),
setRestoredFromThreeBoxToFalse: () => dispatch(setRestoredFromThreeBoxToFalse()),
})
export default compose(

View File

@ -1,5 +1,6 @@
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import { exportAsFile } from '../../../helpers/utils/util'
import ToggleButton from '../../../components/ui/toggle-button'
import TextField from '../../../components/ui/text-field'
@ -26,6 +27,10 @@ export default class AdvancedTab extends PureComponent {
autoLogoutTimeLimit: PropTypes.number,
setAutoLogoutTimeLimit: PropTypes.func.isRequired,
setShowFiatConversionOnTestnetsPreference: PropTypes.func.isRequired,
threeBoxSyncingAllowed: PropTypes.bool.isRequired,
setThreeBoxSyncingPermission: PropTypes.func.isRequired,
threeBoxDisabled: PropTypes.bool.isRequired,
threeBoxFeatureFlag: PropTypes.bool.isRequired,
}
state = { autoLogoutTimeLimit: this.props.autoLogoutTimeLimit }
@ -250,8 +255,53 @@ export default class AdvancedTab extends PureComponent {
)
}
renderThreeBoxControl () {
const { t } = this.context
const {
threeBoxSyncingAllowed,
setThreeBoxSyncingPermission,
threeBoxDisabled,
} = this.props
let allowed = threeBoxSyncingAllowed
let description = t('syncWithThreeBoxDescription')
if (threeBoxDisabled) {
allowed = false
description = t('syncWithThreeBoxDisabled')
}
return (
<div className="settings-page__content-row">
<div className="settings-page__content-item">
<span>{ t('syncWithThreeBox') }</span>
<div className="settings-page__content-description">
{ description }
</div>
</div>
<div
className={classnames('settings-page__content-item', {
'settings-page__content-item--disabled': threeBoxDisabled,
})}
>
<div className="settings-page__content-item-col">
<ToggleButton
value={allowed}
onToggle={value => {
if (!threeBoxDisabled) {
setThreeBoxSyncingPermission(!value)
}
}}
offLabel={t('off')}
onLabel={t('on')}
/>
</div>
</div>
</div>
)
}
renderContent () {
const { warning } = this.props
const { warning, threeBoxFeatureFlag } = this.props
return (
<div className="settings-page__body">
@ -263,6 +313,7 @@ export default class AdvancedTab extends PureComponent {
{ this.renderHexDataOptIn() }
{ this.renderShowConversionInTestnets() }
{ this.renderAutoLogoutTimeLimit() }
{ threeBoxFeatureFlag ? this.renderThreeBoxControl() : null }
</div>
)
}

View File

@ -9,6 +9,7 @@ import {
showModal,
setShowFiatConversionOnTestnetsPreference,
setAutoLogoutTimeLimit,
setThreeBoxSyncingPermission,
} from '../../../store/actions'
import {preferencesSelector} from '../../../selectors/selectors'
@ -18,7 +19,10 @@ export const mapStateToProps = state => {
featureFlags: {
sendHexData,
advancedInlineGas,
threeBox,
} = {},
threeBoxSyncingAllowed,
threeBoxDisabled,
} = metamask
const { showFiatInTestnets, autoLogoutTimeLimit } = preferencesSelector(state)
@ -28,6 +32,9 @@ export const mapStateToProps = state => {
advancedInlineGas,
showFiatInTestnets,
autoLogoutTimeLimit,
threeBoxSyncingAllowed,
threeBoxDisabled,
threeBoxFeatureFlag: threeBox,
}
}
@ -44,6 +51,7 @@ export const mapDispatchToProps = dispatch => {
setAutoLogoutTimeLimit: value => {
return dispatch(setAutoLogoutTimeLimit(value))
},
setThreeBoxSyncingPermission: newThreeBoxSyncingState => dispatch(setThreeBoxSyncingPermission(newThreeBoxSyncingState)),
}
}

View File

@ -6,7 +6,7 @@ import AdvancedTab from '../advanced-tab.component'
import TextField from '../../../../components/ui/text-field'
describe('AdvancedTab Component', () => {
it('should render correctly', () => {
it('should render correctly when threeBoxFeatureFlag is false', () => {
const root = shallow(
<AdvancedTab />,
{
@ -19,6 +19,19 @@ describe('AdvancedTab Component', () => {
assert.equal(root.find('.settings-page__content-row').length, 7)
})
it('should render correctly threeBoxFeatureFlag is true', () => {
const root = shallow(
<AdvancedTab threeBoxFeatureFlag={true} />,
{
context: {
t: s => `_${s}`,
},
}
)
assert.equal(root.find('.settings-page__content-row').length, 8)
})
it('should update autoLogoutTimeLimit', () => {
const setAutoLogoutTimeLimitSpy = sinon.spy()
const root = shallow(
@ -32,7 +45,7 @@ describe('AdvancedTab Component', () => {
}
)
const autoTimeout = root.find('.settings-page__content-row').last()
const autoTimeout = root.find('.settings-page__content-row').at(6)
const textField = autoTimeout.find(TextField)
textField.props().onChange({ target: { value: 1440 } })

View File

@ -9,12 +9,15 @@ const defaultState = {
featureFlags: {
sendHexData: false,
advancedInlineGas: false,
threeBox: false,
},
preferences: {
autoLogoutTimeLimit: 0,
showFiatInTestnets: false,
useNativeCurrencyAsPrimaryCurrency: true,
},
threeBoxSyncingAllowed: false,
threeBoxDisabled: false,
},
}
@ -27,6 +30,9 @@ describe('AdvancedTab Container', () => {
advancedInlineGas: false,
showFiatInTestnets: false,
autoLogoutTimeLimit: 0,
threeBoxSyncingAllowed: false,
threeBoxDisabled: false,
threeBoxFeatureFlag: false,
}
assert.deepEqual(props, expected)

View File

@ -177,6 +177,11 @@
&--without-height {
height: initial;
}
&--disabled {
cursor: not-allowed;
opacity: .5;
}
}
&__content-label {

View File

@ -58,6 +58,7 @@ const selectors = {
getKnownMethodData,
getAddressBookEntry,
getAddressBookEntryName,
getFeatureFlags,
}
module.exports = selectors
@ -369,3 +370,7 @@ function getKnownMethodData (state, data) {
return knownMethodData && knownMethodData[fourBytePrefix]
}
function getFeatureFlags (state) {
return state.metamask.featureFlags
}

View File

@ -16,6 +16,7 @@ const { ENVIRONMENT_TYPE_NOTIFICATION } = require('../../../app/scripts/lib/enum
const { hasUnconfirmedTransactions } = require('../helpers/utils/confirm-tx.util')
const gasDuck = require('../ducks/gas/gas.duck')
const WebcamUtils = require('../../lib/webcam-utils')
const { getFeatureFlags } = require('../selectors/selectors')
var actions = {
_setBackgroundConnection: _setBackgroundConnection,
@ -376,7 +377,15 @@ var actions = {
setSeedPhraseBackedUp,
verifySeedPhrase,
hideSeedPhraseBackupAfterOnboarding,
SET_SEED_PHRASE_BACKED_UP_TO_TRUE: 'SET_SEED_PHRASE_BACKED_UP_TO_TRUE',
initializeThreeBox,
restoreFromThreeBox,
getThreeBoxLastUpdated,
setThreeBoxSyncingPermission,
setRestoredFromThreeBoxToFalse,
turnThreeBoxSyncingOn,
}
module.exports = actions
@ -453,13 +462,13 @@ function createNewVaultAndRestore (password, seed) {
return (dispatch) => {
dispatch(actions.showLoadingIndication())
log.debug(`background.createNewVaultAndRestore`)
let vault
return new Promise((resolve, reject) => {
background.createNewVaultAndRestore(password, seed, (err) => {
background.createNewVaultAndRestore(password, seed, (err, _vault) => {
if (err) {
return reject(err)
}
vault = _vault
resolve()
})
})
@ -467,6 +476,7 @@ function createNewVaultAndRestore (password, seed) {
.then(() => {
dispatch(actions.showAccountsPage())
dispatch(actions.hideLoadingIndication())
return vault
})
.catch(err => {
dispatch(actions.displayWarning(err.message))
@ -2789,3 +2799,124 @@ function setSeedPhraseBackedUp (seedPhraseBackupState) {
})
}
}
function hideSeedPhraseBackupAfterOnboarding () {
return {
type: actions.HIDE_SEED_PHRASE_BACKUP_AFTER_ONBOARDING,
}
}
function initializeThreeBox () {
return (dispatch, getState) => {
const state = getState()
if (getFeatureFlags(state).threeBox) {
return new Promise((resolve, reject) => {
background.initializeThreeBox((err) => {
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
resolve()
})
})
} else {
return Promise.resolve()
}
}
}
function setRestoredFromThreeBoxToFalse () {
return (dispatch, getState) => {
const state = getState()
if (getFeatureFlags(state).threeBox) {
return new Promise((resolve, reject) => {
background.setRestoredFromThreeBoxToFalse((err) => {
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
resolve()
})
})
} else {
return Promise.resolve()
}
}
}
function turnThreeBoxSyncingOn () {
return (dispatch, getState) => {
const state = getState()
if (getFeatureFlags(state).threeBox) {
return new Promise((resolve, reject) => {
background.turnThreeBoxSyncingOn((err) => {
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
resolve()
})
})
} else {
return Promise.resolve()
}
}
}
function restoreFromThreeBox (accountAddress) {
return (dispatch, getState) => {
const state = getState()
if (getFeatureFlags(state).threeBox) {
return new Promise((resolve, reject) => {
background.restoreFromThreeBox(accountAddress, (err) => {
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
resolve()
})
})
} else {
return Promise.resolve()
}
}
}
function getThreeBoxLastUpdated () {
return (dispatch, getState) => {
const state = getState()
if (getFeatureFlags(state).threeBox) {
return new Promise((resolve, reject) => {
background.getThreeBoxLastUpdated((err, lastUpdated) => {
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
resolve(lastUpdated)
})
})
} else {
return Promise.resolve()
}
}
}
function setThreeBoxSyncingPermission (threeBoxSyncingAllowed) {
return (dispatch, getState) => {
const state = getState()
if (getFeatureFlags(state).threeBox) {
return new Promise((resolve, reject) => {
background.setThreeBoxSyncingPermission(threeBoxSyncingAllowed, (err) => {
if (err) {
dispatch(actions.displayWarning(err.message))
return reject(err)
}
resolve()
})
})
} else {
return Promise.resolve()
}
}
}

View File

@ -66,6 +66,14 @@ async function startApp (metamaskState, backgroundConnection, opts) {
}
backgroundConnection.on('update', function (metamaskState) {
const currentState = store.getState()
const { currentLocale } = currentState.metamask
const { currentLocale: newLocale } = metamaskState
if (currentLocale && newLocale && currentLocale !== newLocale) {
store.dispatch(actions.updateCurrentLocale(newLocale))
}
store.dispatch(actions.updateMetamaskState(metamaskState))
})
@ -77,6 +85,9 @@ async function startApp (metamaskState, backgroundConnection, opts) {
setProviderType: (type) => {
store.dispatch(actions.setProviderType(type))
},
setFeatureFlag: (key, value) => {
store.dispatch(actions.setFeatureFlag(key, value))
},
}
// start app

4103
yarn.lock

File diff suppressed because it is too large Load Diff