diff options
author | Alexander Tseung <alextsg@gmail.com> | 2018-03-30 00:37:29 +0800 |
---|---|---|
committer | Alexander Tseung <alextsg@gmail.com> | 2018-03-30 00:37:29 +0800 |
commit | ef61ef2ce885635862bb242612dd821cb3a65b6b (patch) | |
tree | 0f128f8b56b57a1bbe96dcf5743d34b5f95dc4cc /app/scripts | |
parent | 58f52b2b8de9efd43896e23ab0ac9972f45bb278 (diff) | |
parent | 8766420f19251b95211dd99ff9a45e60cf0177ad (diff) | |
download | tangerine-wallet-browser-ef61ef2ce885635862bb242612dd821cb3a65b6b.tar tangerine-wallet-browser-ef61ef2ce885635862bb242612dd821cb3a65b6b.tar.gz tangerine-wallet-browser-ef61ef2ce885635862bb242612dd821cb3a65b6b.tar.bz2 tangerine-wallet-browser-ef61ef2ce885635862bb242612dd821cb3a65b6b.tar.lz tangerine-wallet-browser-ef61ef2ce885635862bb242612dd821cb3a65b6b.tar.xz tangerine-wallet-browser-ef61ef2ce885635862bb242612dd821cb3a65b6b.tar.zst tangerine-wallet-browser-ef61ef2ce885635862bb242612dd821cb3a65b6b.zip |
Fix i18n merge conflicts
Diffstat (limited to 'app/scripts')
-rw-r--r-- | app/scripts/background.js | 13 | ||||
-rw-r--r-- | app/scripts/controllers/currency.js | 2 | ||||
-rw-r--r-- | app/scripts/controllers/preferences.js | 5 | ||||
-rw-r--r-- | app/scripts/controllers/transactions.js | 10 | ||||
-rw-r--r-- | app/scripts/lib/extractEthjsErrorMessage.js | 27 | ||||
-rw-r--r-- | app/scripts/lib/get-first-preferred-lang-code.js | 16 | ||||
-rw-r--r-- | app/scripts/lib/reportFailedTxToSentry.js | 26 | ||||
-rw-r--r-- | app/scripts/lib/setupRaven.js | 17 | ||||
-rw-r--r-- | app/scripts/lib/tx-state-manager.js | 23 | ||||
-rw-r--r-- | app/scripts/metamask-controller.js | 86 | ||||
-rw-r--r-- | app/scripts/migrations/023.js | 50 | ||||
-rw-r--r-- | app/scripts/migrations/index.js | 2 | ||||
-rw-r--r-- | app/scripts/popup.js | 126 |
13 files changed, 261 insertions, 142 deletions
diff --git a/app/scripts/background.js b/app/scripts/background.js index 8bd7766ad..7782fc41e 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -19,7 +19,7 @@ const setupRaven = require('./lib/setupRaven') const reportFailedTxToSentry = require('./lib/reportFailedTxToSentry') const setupMetamaskMeshMetrics = require('./lib/setupMetamaskMeshMetrics') const EdgeEncryptor = require('./edge-encryptor') - +const getFirstPreferredLangCode = require('./lib/get-first-preferred-lang-code') const STORAGE_KEY = 'metamask-config' const METAMASK_DEBUG = 'GULP_METAMASK_DEBUG' @@ -58,7 +58,8 @@ setupMetamaskMeshMetrics() async function initialize () { const initState = await loadStateFromPersistence() - await setupController(initState) + const initLangCode = await getFirstPreferredLangCode() + await setupController(initState, initLangCode) log.debug('MetaMask initialization complete.') } @@ -84,17 +85,16 @@ async function loadStateFromPersistence () { // write to disk if (localStore.isSupported) localStore.set(versionedData) - diskStore.putState(versionedData) // return just the data return versionedData.data } -function setupController (initState) { +function setupController (initState, initLangCode) { // // MetaMask Controller // - + const controller = new MetamaskController({ // User confirmation callbacks: showUnconfirmedMessage: triggerUi, @@ -102,6 +102,8 @@ function setupController (initState) { showUnapprovedTx: triggerUi, // initial state initState, + // initial locale code + initLangCode, // platform specific api platform, encryptor: isEdge ? new EdgeEncryptor() : undefined, @@ -121,7 +123,6 @@ function setupController (initState) { debounce(1000), storeTransform(versionifyData), storeTransform(syncDataWithExtension), - asStream(diskStore), (error) => { log.error('pump hit error', error) } diff --git a/app/scripts/controllers/currency.js b/app/scripts/controllers/currency.js index 25a7a942e..930fc52e8 100644 --- a/app/scripts/controllers/currency.js +++ b/app/scripts/controllers/currency.js @@ -52,7 +52,7 @@ class CurrencyController { this.setConversionDate(Number(parsedResponse.timestamp)) }).catch((err) => { if (err) { - console.warn('MetaMask - Failed to query currency conversion.') + console.warn(`MetaMask - Failed to query currency conversion:`, currentCurrency, err) this.setConversionRate(0) this.setConversionDate('N/A') } diff --git a/app/scripts/controllers/preferences.js b/app/scripts/controllers/preferences.js index 39d15fd83..b4819d951 100644 --- a/app/scripts/controllers/preferences.js +++ b/app/scripts/controllers/preferences.js @@ -11,6 +11,7 @@ class PreferencesController { tokens: [], useBlockie: false, featureFlags: {}, + currentLocale: opts.initLangCode, }, opts.initState) this.store = new ObservableStore(initState) } @@ -24,6 +25,10 @@ class PreferencesController { return this.store.getState().useBlockie } + setCurrentLocale (key) { + this.store.updateState({ currentLocale: key }) + } + setSelectedAddress (_address) { return new Promise((resolve, reject) => { const address = normalizeAddress(_address) diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index 3e3909361..7e2cc15da 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -250,7 +250,7 @@ module.exports = class TransactionController extends EventEmitter { // wait for a nonce nonceLock = await this.nonceTracker.getNonceLock(fromAddress) // add nonce to txParams - // if txMeta has lastGasPrice then it is a retry at same nonce with higher + // if txMeta has lastGasPrice then it is a retry at same nonce with higher // gas price transaction and their for the nonce should not be calculated const nonce = txMeta.lastGasPrice ? txMeta.txParams.nonce : nonceLock.nextNonce txMeta.txParams.nonce = ethUtil.addHexPrefix(nonce.toString(16)) @@ -273,12 +273,14 @@ module.exports = class TransactionController extends EventEmitter { async signTransaction (txId) { const txMeta = this.txStateManager.getTx(txId) - const txParams = txMeta.txParams - const fromAddress = txParams.from // add network/chain id - txParams.chainId = ethUtil.addHexPrefix(this.getChainId().toString(16)) + const chainId = this.getChainId() + const txParams = Object.assign({}, txMeta.txParams, { chainId }) + // sign tx + const fromAddress = txParams.from const ethTx = new Transaction(txParams) await this.signEthTx(ethTx, fromAddress) + // set state to signed this.txStateManager.setTxStatusSigned(txMeta.id) const rawTx = ethUtil.bufferToHex(ethTx.serialize()) return rawTx diff --git a/app/scripts/lib/extractEthjsErrorMessage.js b/app/scripts/lib/extractEthjsErrorMessage.js new file mode 100644 index 000000000..bac541735 --- /dev/null +++ b/app/scripts/lib/extractEthjsErrorMessage.js @@ -0,0 +1,27 @@ +const ethJsRpcSlug = 'Error: [ethjs-rpc] rpc error with payload ' +const errorLabelPrefix = 'Error: ' + +module.exports = extractEthjsErrorMessage + + +// +// ethjs-rpc provides overly verbose error messages +// if we detect this type of message, we extract the important part +// Below is an example input and output +// +// Error: [ethjs-rpc] rpc error with payload {"id":3947817945380,"jsonrpc":"2.0","params":["0xf8eb8208708477359400830398539406012c8cf97bead5deae237070f9587f8e7a266d80b8843d7d3f5a0000000000000000000000000000000000000000000000000000000000081d1a000000000000000000000000000000000000000000000000001ff973cafa800000000000000000000000000000000000000000000000000000038d7ea4c68000000000000000000000000000000000000000000000000000000000000003f48025a04c32a9b630e0d9e7ff361562d850c86b7a884908135956a7e4a336fa0300d19ca06830776423f25218e8d19b267161db526e66895567147015b1f3fc47aef9a3c7"],"method":"eth_sendRawTransaction"} Error: replacement transaction underpriced +// +// Transaction Failed: replacement transaction underpriced +// + + +function extractEthjsErrorMessage(errorMessage) { + const isEthjsRpcError = errorMessage.includes(ethJsRpcSlug) + if (isEthjsRpcError) { + const payloadAndError = errorMessage.slice(ethJsRpcSlug.length) + const originalError = payloadAndError.slice(payloadAndError.indexOf(errorLabelPrefix) + errorLabelPrefix.length) + return originalError + } else { + return errorMessage + } +} diff --git a/app/scripts/lib/get-first-preferred-lang-code.js b/app/scripts/lib/get-first-preferred-lang-code.js new file mode 100644 index 000000000..28612f763 --- /dev/null +++ b/app/scripts/lib/get-first-preferred-lang-code.js @@ -0,0 +1,16 @@ +const extension = require('extensionizer') +const promisify = require('pify') +const allLocales = require('../../_locales/index.json') + +const existingLocaleCodes = allLocales.map(locale => locale.code) + +async function getFirstPreferredLangCode () { + const userPreferredLocaleCodes = await promisify( + extension.i18n.getAcceptLanguages, + { errorFirst: false } + )() + const firstPreferredLangCode = userPreferredLocaleCodes.find(code => existingLocaleCodes.includes(code)) + return firstPreferredLangCode || 'en' +} + +module.exports = getFirstPreferredLangCode diff --git a/app/scripts/lib/reportFailedTxToSentry.js b/app/scripts/lib/reportFailedTxToSentry.js index ee73f6845..e09f4f1f8 100644 --- a/app/scripts/lib/reportFailedTxToSentry.js +++ b/app/scripts/lib/reportFailedTxToSentry.js @@ -1,5 +1,4 @@ -const ethJsRpcSlug = 'Error: [ethjs-rpc] rpc error with payload ' -const errorLabelPrefix = 'Error: ' +const extractEthjsErrorMessage = require('./extractEthjsErrorMessage') module.exports = reportFailedTxToSentry @@ -9,30 +8,9 @@ module.exports = reportFailedTxToSentry // function reportFailedTxToSentry({ raven, txMeta }) { - const errorMessage = extractErrorMessage(txMeta.err.message) + const errorMessage = 'Transaction Failed: ' + extractEthjsErrorMessage(txMeta.err.message) raven.captureMessage(errorMessage, { // "extra" key is required by Sentry extra: txMeta, }) } - -// -// ethjs-rpc provides overly verbose error messages -// if we detect this type of message, we extract the important part -// Below is an example input and output -// -// Error: [ethjs-rpc] rpc error with payload {"id":3947817945380,"jsonrpc":"2.0","params":["0xf8eb8208708477359400830398539406012c8cf97bead5deae237070f9587f8e7a266d80b8843d7d3f5a0000000000000000000000000000000000000000000000000000000000081d1a000000000000000000000000000000000000000000000000001ff973cafa800000000000000000000000000000000000000000000000000000038d7ea4c68000000000000000000000000000000000000000000000000000000000000003f48025a04c32a9b630e0d9e7ff361562d850c86b7a884908135956a7e4a336fa0300d19ca06830776423f25218e8d19b267161db526e66895567147015b1f3fc47aef9a3c7"],"method":"eth_sendRawTransaction"} Error: replacement transaction underpriced -// -// Transaction Failed: replacement transaction underpriced -// - -function extractErrorMessage(errorMessage) { - const isEthjsRpcError = errorMessage.includes(ethJsRpcSlug) - if (isEthjsRpcError) { - const payloadAndError = errorMessage.slice(ethJsRpcSlug.length) - const originalError = payloadAndError.slice(payloadAndError.indexOf(errorLabelPrefix) + errorLabelPrefix.length) - return `Transaction Failed: ${originalError}` - } else { - return `Transaction Failed: ${errorMessage}` - } -} diff --git a/app/scripts/lib/setupRaven.js b/app/scripts/lib/setupRaven.js index 02c01b755..b93591e65 100644 --- a/app/scripts/lib/setupRaven.js +++ b/app/scripts/lib/setupRaven.js @@ -1,5 +1,6 @@ const Raven = require('raven-js') const METAMASK_DEBUG = 'GULP_METAMASK_DEBUG' +const extractEthjsErrorMessage = require('./extractEthjsErrorMessage') const PROD = 'https://3567c198f8a8412082d32655da2961d0@sentry.io/273505' const DEV = 'https://f59f3dd640d2429d9d0e2445a87ea8e1@sentry.io/273496' @@ -21,8 +22,22 @@ function setupRaven(opts) { const client = Raven.config(ravenTarget, { release, transport: function(opts) { - // modify report urls const report = opts.data + // simplify certain complex error messages + report.exception.values.forEach(item => { + let errorMessage = item.value + // simplify ethjs error messages + errorMessage = extractEthjsErrorMessage(errorMessage) + // simplify 'Transaction Failed: known transaction' + if (errorMessage.indexOf('Transaction Failed: known transaction') === 0) { + // cut the hash from the error message + errorMessage = 'Transaction Failed: known transaction' + } + // finalize + item.value = errorMessage + }) + + // modify report urls rewriteReportUrls(report) // make request normally client._makeRequest(opts) diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index ad07c813f..23c915a61 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -38,11 +38,6 @@ module.exports = class TransactionStateManager extends EventEmitter { }, opts) } - // Returns the number of txs for the current network. - getTxCount () { - return this.getTxList().length - } - getTxList () { const network = this.getNetwork() const fullTxList = this.getFullTxList() @@ -88,7 +83,7 @@ module.exports = class TransactionStateManager extends EventEmitter { txMeta.history.push(snapshot) const transactions = this.getFullTxList() - const txCount = this.getTxCount() + const txCount = transactions.length const txHistoryLimit = this.txHistoryLimit // checks if the length of the tx history is @@ -111,12 +106,9 @@ module.exports = class TransactionStateManager extends EventEmitter { } updateTx (txMeta, note) { + // validate txParams if (txMeta.txParams) { - Object.keys(txMeta.txParams).forEach((key) => { - const value = txMeta.txParams[key] - if (typeof value !== 'string') console.error(`${key}: ${value} in txParams is not a string`) - if (!ethUtil.isHexPrefixed(value)) console.error('is not hex prefixed, anything on txParams must be hex prefixed') - }) + this.validateTxParams(txMeta.txParams) } // create txMeta snapshot for history @@ -144,6 +136,15 @@ module.exports = class TransactionStateManager extends EventEmitter { this.updateTx(txMeta, `txStateManager#updateTxParams`) } + // validates txParams members by type + validateTxParams(txParams) { + Object.keys(txParams).forEach((key) => { + const value = txParams[key] + if (typeof value !== 'string') throw new Error(`${key}: ${value} in txParams is not a string`) + if (!ethUtil.isHexPrefixed(value)) throw new Error('is not hex prefixed, everything on txParams must be hex prefixed') + }) + } + /* Takes an object of fields to search for eg: let thingsToLookFor = { diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 18d71874a..4422a5cf3 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -49,7 +49,7 @@ module.exports = class MetamaskController extends EventEmitter { /** * @constructor - * @param {Object} opts + * @param {Object} opts */ constructor (opts) { super() @@ -57,7 +57,7 @@ module.exports = class MetamaskController extends EventEmitter { this.defaultMaxListeners = 20 this.sendUpdate = debounce(this.privateSendUpdate.bind(this), 200) - + this.opts = opts const initState = opts.initState || {} this.recordFirstTimeInfo(initState) @@ -82,6 +82,7 @@ module.exports = class MetamaskController extends EventEmitter { // preferences controller this.preferencesController = new PreferencesController({ initState: initState.PreferencesController, + initLangCode: opts.initLangCode, }) // currency controller @@ -296,8 +297,8 @@ module.exports = class MetamaskController extends EventEmitter { /** * The metamask-state of the various controllers, made available to the UI - * - * @returns {Object} status + * + * @returns {Object} status */ getState () { const wallet = this.configManager.getWallet() @@ -335,8 +336,8 @@ module.exports = class MetamaskController extends EventEmitter { /** * Returns an api-object which is consumed by the UI - * - * @returns {Object} + * + * @returns {Object} */ getApi () { const keyringController = this.keyringController @@ -351,6 +352,7 @@ module.exports = class MetamaskController extends EventEmitter { getState: (cb) => cb(null, this.getState()), setCurrentCurrency: this.setCurrentCurrency.bind(this), setUseBlockie: this.setUseBlockie.bind(this), + setCurrentLocale: this.setCurrentLocale.bind(this), markAccountsFound: this.markAccountsFound.bind(this), markPasswordForgotten: this.markPasswordForgotten.bind(this), unMarkPasswordForgotten: this.unMarkPasswordForgotten.bind(this), @@ -365,7 +367,7 @@ module.exports = class MetamaskController extends EventEmitter { placeSeedWords: this.placeSeedWords.bind(this), verifySeedPhrase: nodeify(this.verifySeedPhrase, this), clearSeedWordCache: this.clearSeedWordCache.bind(this), - resetAccount: this.resetAccount.bind(this), + resetAccount: nodeify(this.resetAccount, this), importAccountWithStrategy: this.importAccountWithStrategy.bind(this), // vault management @@ -426,14 +428,14 @@ module.exports = class MetamaskController extends EventEmitter { /** * Creates a new Vault(?) and create a new keychain(?) - * + * * A vault is ... - * + * * A keychain is ... - * + * * * @param {} password - * + * * @returns {} vault */ async createNewVaultAndKeychain (password) { @@ -479,9 +481,9 @@ module.exports = class MetamaskController extends EventEmitter { /** * Retrieves the first Identiy from the passed Vault and selects the related address - * + * * An Identity is ... - * + * * @param {} vault */ selectFirstIdentity (vault) { @@ -495,8 +497,8 @@ module.exports = class MetamaskController extends EventEmitter { // /** - * Adds a new account to ... - * + * Adds a new account to ... + * * @returns {} keyState */ async addNewAccount () { @@ -522,10 +524,10 @@ module.exports = class MetamaskController extends EventEmitter { /** * Adds the current vault's seed words to the UI's state tree. - * + * * Used when creating a first vault, to allow confirmation. * Also used when revealing the seed words in the confirmation view. - */ + */ placeSeedWords (cb) { this.verifySeedPhrase() @@ -540,7 +542,7 @@ module.exports = class MetamaskController extends EventEmitter { /** * Verifies the validity of the current vault's seed phrase. - * + * * Validity: seed phrase restores the accounts belonging to the current vault. * * Called when the first account is created and on unlocking the vault. @@ -571,27 +573,32 @@ module.exports = class MetamaskController extends EventEmitter { /** * Remove the primary account seed phrase from the UI's state tree. - * + * * The seed phrase remains available in the background process. - * + * */ clearSeedWordCache (cb) { this.configManager.setSeedWords(null) cb(null, this.preferencesController.getSelectedAddress()) } - + /** * ? */ - resetAccount (cb) { + async resetAccount (cb) { const selectedAddress = this.preferencesController.getSelectedAddress() this.txController.wipeTransactions(selectedAddress) - cb(null, selectedAddress) + + const networkController = this.networkController + const oldType = networkController.getProviderConfig().type + await networkController.setProviderType(oldType, true) + + return selectedAddress } /** * Imports an account ... ? - * + * * @param {} strategy * @param {} args * @param {} cb @@ -634,9 +641,9 @@ module.exports = class MetamaskController extends EventEmitter { } // Prefixed Style Message Signing Methods: - + /** - * + * * @param {} msgParams * @param {} cb */ @@ -655,7 +662,7 @@ module.exports = class MetamaskController extends EventEmitter { } }) } - + /** * @param {} msgParams */ @@ -676,7 +683,7 @@ module.exports = class MetamaskController extends EventEmitter { return this.getState() }) } - + /** * @param {} msgParams */ @@ -697,13 +704,13 @@ module.exports = class MetamaskController extends EventEmitter { return this.getState() }) } - + // --------------------------------------------------------------------------- // Account Restauration /** * ? - * + * * @param {} migratorOutput */ restoreOldVaultAccounts (migratorOutput) { @@ -714,7 +721,7 @@ module.exports = class MetamaskController extends EventEmitter { /** * ? - * + * * @param {} migratorOutput */ restoreOldLostAccounts (migratorOutput) { @@ -728,9 +735,9 @@ module.exports = class MetamaskController extends EventEmitter { /** * Import (lost) Accounts - * + * * @param {Object} {lostAccounts} @Array accounts <{ address, privateKey }> - * + * * Uses the array's private keys to create a new Simple Key Pair keychain * and add it to the keyring controller. */ @@ -823,7 +830,7 @@ module.exports = class MetamaskController extends EventEmitter { if (cb && typeof cb === 'function') { cb(null, this.getState()) } - } + } cancelPersonalMessage (msgId, cb) { const messageManager = this.personalMessageManager @@ -978,7 +985,7 @@ module.exports = class MetamaskController extends EventEmitter { const percentileNum = percentile(50, lowestPrices) const percentileNumBn = new BN(percentileNum) return '0x' + percentileNumBn.mul(GWEI_BN).toString(16) - } + } //============================================================================= // CONFIG @@ -1029,6 +1036,15 @@ module.exports = class MetamaskController extends EventEmitter { } } + setCurrentLocale (key, cb) { + try { + this.preferencesController.setCurrentLocale(key) + cb(null) + } catch (err) { + cb(err) + } + } + recordFirstTimeInfo (initState) { if (!('firstTimeInfo' in initState)) { initState.firstTimeInfo = { diff --git a/app/scripts/migrations/023.js b/app/scripts/migrations/023.js new file mode 100644 index 000000000..bce0a5bea --- /dev/null +++ b/app/scripts/migrations/023.js @@ -0,0 +1,50 @@ + +const version = 23 + +/* + +This migration removes transactions that are no longer usefull down to 40 total + +*/ + +const clone = require('clone') + +module.exports = { + version, + + migrate: function (originalVersionedData) { + const versionedData = clone(originalVersionedData) + versionedData.meta.version = version + try { + const state = versionedData.data + const newState = transformState(state) + versionedData.data = newState + } catch (err) { + console.warn(`MetaMask Migration #${version}` + err.stack) + } + return Promise.resolve(versionedData) + }, +} + +function transformState (state) { + const newState = state + const transactions = newState.TransactionController.transactions + + if (transactions.length <= 40) return newState + + let reverseTxList = transactions.reverse() + let stripping = true + while (reverseTxList.length > 40 && stripping) { + let txIndex = reverseTxList.findIndex((txMeta) => { + return (txMeta.status === 'failed' || + txMeta.status === 'rejected' || + txMeta.status === 'confirmed' || + txMeta.status === 'dropped') + }) + if (txIndex < 0) stripping = false + else reverseTxList.splice(txIndex, 1) + } + + newState.TransactionController.transactions = reverseTxList.reverse() + return newState +} diff --git a/app/scripts/migrations/index.js b/app/scripts/migrations/index.js index a0cf5f4d4..811e06b6b 100644 --- a/app/scripts/migrations/index.js +++ b/app/scripts/migrations/index.js @@ -32,4 +32,6 @@ module.exports = [ require('./019'), require('./020'), require('./021'), + require('./022'), + require('./023'), ] diff --git a/app/scripts/popup.js b/app/scripts/popup.js index e78981f06..13c7ac5ec 100644 --- a/app/scripts/popup.js +++ b/app/scripts/popup.js @@ -10,69 +10,75 @@ const NotificationManager = require('./lib/notification-manager') const notificationManager = new NotificationManager() const setupRaven = require('./lib/setupRaven') -// create platform global -global.platform = new ExtensionPlatform() - -// setup sentry error reporting -const release = global.platform.getVersion() -setupRaven({ release }) - -// inject css -// const css = MetaMaskUiCss() -// injectCss(css) - -// identify window type (popup, notification) -const windowType = isPopupOrNotification() -global.METAMASK_UI_TYPE = windowType -closePopupIfOpen(windowType) - -// setup stream to background -const extensionPort = extension.runtime.connect({ name: windowType }) -const connectionStream = new PortStream(extensionPort) - -// start ui -const container = document.getElementById('app-content') -startPopup({ container, connectionStream }, (err, store) => { - if (err) return displayCriticalError(err) - - // Code commented out until we begin auto adding users to NewUI - // const { isMascara, identities = {}, featureFlags = {} } = store.getState().metamask - // const firstTime = Object.keys(identities).length === 0 - const { isMascara, featureFlags = {} } = store.getState().metamask - let betaUIState = featureFlags.betaUI - - // Code commented out until we begin auto adding users to NewUI - // const useBetaCss = isMascara || firstTime || betaUIState - const useBetaCss = isMascara || betaUIState - - let css = useBetaCss ? NewMetaMaskUiCss() : OldMetaMaskUiCss() - let deleteInjectedCss = injectCss(css) - let newBetaUIState - - store.subscribe(() => { - const state = store.getState() - newBetaUIState = state.metamask.featureFlags.betaUI - if (newBetaUIState !== betaUIState) { - deleteInjectedCss() - betaUIState = newBetaUIState - css = betaUIState ? NewMetaMaskUiCss() : OldMetaMaskUiCss() - deleteInjectedCss = injectCss(css) - } - if (state.appState.shouldClose) notificationManager.closePopup() +start().catch(log.error) + +async function start() { + + // create platform global + global.platform = new ExtensionPlatform() + + // setup sentry error reporting + const release = global.platform.getVersion() + setupRaven({ release }) + + // inject css + // const css = MetaMaskUiCss() + // injectCss(css) + + // identify window type (popup, notification) + const windowType = isPopupOrNotification() + global.METAMASK_UI_TYPE = windowType + closePopupIfOpen(windowType) + + // setup stream to background + const extensionPort = extension.runtime.connect({ name: windowType }) + const connectionStream = new PortStream(extensionPort) + + // start ui + const container = document.getElementById('app-content') + startPopup({ container, connectionStream }, (err, store) => { + if (err) return displayCriticalError(err) + + // Code commented out until we begin auto adding users to NewUI + // const { isMascara, identities = {}, featureFlags = {} } = store.getState().metamask + // const firstTime = Object.keys(identities).length === 0 + const { isMascara, featureFlags = {} } = store.getState().metamask + let betaUIState = featureFlags.betaUI + + // Code commented out until we begin auto adding users to NewUI + // const useBetaCss = isMascara || firstTime || betaUIState + const useBetaCss = isMascara || betaUIState + + let css = useBetaCss ? NewMetaMaskUiCss() : OldMetaMaskUiCss() + let deleteInjectedCss = injectCss(css) + let newBetaUIState + + store.subscribe(() => { + const state = store.getState() + newBetaUIState = state.metamask.featureFlags.betaUI + if (newBetaUIState !== betaUIState) { + deleteInjectedCss() + betaUIState = newBetaUIState + css = betaUIState ? NewMetaMaskUiCss() : OldMetaMaskUiCss() + deleteInjectedCss = injectCss(css) + } + if (state.appState.shouldClose) notificationManager.closePopup() + }) }) -}) -function closePopupIfOpen (windowType) { - if (windowType !== 'notification') { - // should close only chrome popup - notificationManager.closePopup() + function closePopupIfOpen (windowType) { + if (windowType !== 'notification') { + // should close only chrome popup + notificationManager.closePopup() + } + } + + function displayCriticalError (err) { + container.innerHTML = '<div class="critical-error">The MetaMask app failed to load: please open and close MetaMask again to restart.</div>' + container.style.height = '80px' + log.error(err.stack) + throw err } -} -function displayCriticalError (err) { - container.innerHTML = '<div class="critical-error">The MetaMask app failed to load: please open and close MetaMask again to restart.</div>' - container.style.height = '80px' - log.error(err.stack) - throw err } |