diff options
author | Dan Finlay <542863+danfinlay@users.noreply.github.com> | 2018-04-24 05:49:01 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-04-24 05:49:01 +0800 |
commit | 9679cdae02e0ad645ced1a8627ada68456dcbbdb (patch) | |
tree | 33bc3c617f4e1779c54f456e7b494163ac79fe90 /app/scripts | |
parent | 74c419f9b65841c2966d1fe3b7414bf11e09e0d8 (diff) | |
parent | 327ec03d6f5219bb42efabeb02536bb6f6781f76 (diff) | |
download | tangerine-wallet-browser-9679cdae02e0ad645ced1a8627ada68456dcbbdb.tar tangerine-wallet-browser-9679cdae02e0ad645ced1a8627ada68456dcbbdb.tar.gz tangerine-wallet-browser-9679cdae02e0ad645ced1a8627ada68456dcbbdb.tar.bz2 tangerine-wallet-browser-9679cdae02e0ad645ced1a8627ada68456dcbbdb.tar.lz tangerine-wallet-browser-9679cdae02e0ad645ced1a8627ada68456dcbbdb.tar.xz tangerine-wallet-browser-9679cdae02e0ad645ced1a8627ada68456dcbbdb.tar.zst tangerine-wallet-browser-9679cdae02e0ad645ced1a8627ada68456dcbbdb.zip |
Merge pull request #4041 from MetaMask/DocumentBackground
Document Background Script
Diffstat (limited to 'app/scripts')
-rw-r--r-- | app/scripts/background.js | 129 |
1 files changed, 127 insertions, 2 deletions
diff --git a/app/scripts/background.js b/app/scripts/background.js index 6550e8944..38b871bb5 100644 --- a/app/scripts/background.js +++ b/app/scripts/background.js @@ -1,3 +1,7 @@ +/** + * @file The entry point for the web extension singleton process. + */ + const urlUtil = require('url') const endOfStream = require('end-of-stream') const pump = require('pump') @@ -61,6 +65,90 @@ initialize().catch(log.error) // setup metamask mesh testing container setupMetamaskMeshMetrics() +/** + * An object representing a transaction, in whatever state it is in. + * @typedef TransactionMeta + * + * @property {number} id - An internally unique tx identifier. + * @property {number} time - Time the tx was first suggested, in unix epoch time (ms). + * @property {string} status - The current transaction status (unapproved, signed, submitted, dropped, failed, rejected), as defined in `tx-state-manager.js`. + * @property {string} metamaskNetworkId - The transaction's network ID, used for EIP-155 compliance. + * @property {boolean} loadingDefaults - TODO: Document + * @property {Object} txParams - The tx params as passed to the network provider. + * @property {Object[]} history - A history of mutations to this TransactionMeta object. + * @property {boolean} gasPriceSpecified - True if the suggesting dapp specified a gas price, prevents auto-estimation. + * @property {boolean} gasLimitSpecified - True if the suggesting dapp specified a gas limit, prevents auto-estimation. + * @property {string} estimatedGas - A hex string represented the estimated gas limit required to complete the transaction. + * @property {string} origin - A string representing the interface that suggested the transaction. + * @property {Object} nonceDetails - A metadata object containing information used to derive the suggested nonce, useful for debugging nonce issues. + * @property {string} rawTx - A hex string of the final signed transaction, ready to submit to the network. + * @property {string} hash - A hex string of the transaction hash, used to identify the transaction on the network. + * @property {number} submittedTime - The time the transaction was submitted to the network, in Unix epoch time (ms). + */ + +/** + * The data emitted from the MetaMaskController.store EventEmitter, also used to initialize the MetaMaskController. Available in UI on React state as state.metamask. + * @typedef MetaMaskState + * @property {boolean} isInitialized - Whether the first vault has been created. + * @property {boolean} isUnlocked - Whether the vault is currently decrypted and accounts are available for selection. + * @property {boolean} isAccountMenuOpen - Represents whether the main account selection UI is currently displayed. + * @property {boolean} isMascara - True if the current context is the extensionless MetaMascara project. + * @property {boolean} isPopup - Returns true if the current view is an externally-triggered notification. + * @property {string} rpcTarget - DEPRECATED - The URL of the current RPC provider. + * @property {Object} identities - An object matching lower-case hex addresses to Identity objects with "address" and "name" (nickname) keys. + * @property {Object} unapprovedTxs - An object mapping transaction hashes to unapproved transactions. + * @property {boolean} noActiveNotices - False if there are notices the user should confirm before using the application. + * @property {Array} frequentRpcList - A list of frequently used RPCs, including custom user-provided ones. + * @property {Array} addressBook - A list of previously sent to addresses. + * @property {address} selectedTokenAddress - Used to indicate if a token is globally selected. Should be deprecated in favor of UI-centric token selection. + * @property {Object} tokenExchangeRates - Info about current token prices. + * @property {Array} tokens - Tokens held by the current user, including their balances. + * @property {Object} send - TODO: Document + * @property {Object} coinOptions - TODO: Document + * @property {boolean} useBlockie - Indicates preferred user identicon format. True for blockie, false for Jazzicon. + * @property {Object} featureFlags - An object for optional feature flags. + * @property {string} networkEndpointType - TODO: Document + * @property {boolean} isRevealingSeedWords - True if seed words are currently being recovered, and should be shown to user. + * @property {boolean} welcomeScreen - True if welcome screen should be shown. + * @property {string} currentLocale - A locale string matching the user's preferred display language. + * @property {Object} provider - The current selected network provider. + * @property {string} provider.rpcTarget - The address for the RPC API, if using an RPC API. + * @property {string} provider.type - An identifier for the type of network selected, allows MetaMask to use custom provider strategies for known networks. + * @property {string} network - A stringified number of the current network ID. + * @property {Object} accounts - An object mapping lower-case hex addresses to objects with "balance" and "address" keys, both storing hex string values. + * @property {hex} currentBlockGasLimit - The most recently seen block gas limit, in a lower case hex prefixed string. + * @property {TransactionMeta[]} selectedAddressTxList - An array of transactions associated with the currently selected account. + * @property {Object} unapprovedMsgs - An object of messages associated with the currently selected account, mapping a unique ID to the options. + * @property {number} unapprovedMsgCount - The number of messages in unapprovedMsgs. + * @property {Object} unapprovedPersonalMsgs - An object of messages associated with the currently selected account, mapping a unique ID to the options. + * @property {number} unapprovedPersonalMsgCount - The number of messages in unapprovedPersonalMsgs. + * @property {Object} unapprovedTypedMsgs - An object of messages associated with the currently selected account, mapping a unique ID to the options. + * @property {number} unapprovedTypedMsgCount - The number of messages in unapprovedTypedMsgs. + * @property {string[]} keyringTypes - An array of unique keyring identifying strings, representing available strategies for creating accounts. + * @property {Keyring[]} keyrings - An array of keyring descriptions, summarizing the accounts that are available for use, and what keyrings they belong to. + * @property {Object} computedBalances - Maps accounts to their balances, accounting for balance changes from pending transactions. + * @property {string} currentAccountTab - A view identifying string for displaying the current displayed view, allows user to have a preferred tab in the old UI (between tokens and history). + * @property {string} selectedAddress - A lower case hex string of the currently selected address. + * @property {string} currentCurrency - A string identifying the user's preferred display currency, for use in showing conversion rates. + * @property {number} conversionRate - A number representing the current exchange rate from the user's preferred currency to Ether. + * @property {number} conversionDate - A unix epoch date (ms) for the time the current conversion rate was last retrieved. + * @property {Object} infuraNetworkStatus - An object of infura network status checks. + * @property {Block[]} recentBlocks - An array of recent blocks, used to calculate an effective but cheap gas price. + * @property {Array} shapeShiftTxList - An array of objects describing shapeshift exchange attempts. + * @property {Array} lostAccounts - TODO: Remove this feature. A leftover from the version-3 migration where our seed-phrase library changed to fix a bug where some accounts were mis-generated, but we recovered the old accounts as "lost" instead of losing them. + * @property {boolean} forgottenPassword - Returns true if the user has initiated the password recovery screen, is recovering from seed phrase. + */ + +/** + * @typedef VersionedData + * @property {MetaMaskState} data - The data emitted from MetaMask controller, or used to initialize it. + * @property {Number} version - The latest migration version that has been run. + */ + +/** + * Initializes the MetaMask controller, and sets up all platform configuration. + * @returns {Promise} Setup complete. + */ async function initialize () { const initState = await loadStateFromPersistence() const initLangCode = await getFirstPreferredLangCode() @@ -72,6 +160,11 @@ async function initialize () { // State and Persistence // +/** + * Loads any stored data, prioritizing the latest storage strategy. + * Migrates that data schema in case it was last loaded on an older version. + * @returns {Promise<MetaMaskState>} Last data emitted from previous instance of MetaMask. + */ async function loadStateFromPersistence () { // migrations const migrator = new Migrator({ migrations }) @@ -134,6 +227,16 @@ async function loadStateFromPersistence () { return versionedData.data } +/** + * Initializes the MetaMask Controller with any initial state and default language. + * Configures platform-specific error reporting strategy. + * Streams emitted state updates to platform-specific storage strategy. + * Creates platform listeners for new Dapps/Contexts, and sets up their data connections to the controller. + * + * @param {Object} initState - The initial state to start the controller with, matches the state that is emitted from the controller. + * @param {String} initLangCode - The region code for the language preferred by the current user. + * @returns {Promise} After setup is complete. + */ function setupController (initState, initLangCode) { // // MetaMask Controller @@ -172,6 +275,11 @@ function setupController (initState, initLangCode) { } ) + /** + * Assigns the given state to the versioned object (with metadata), and returns that. + * @param {Object} state - The state object as emitted by the MetaMaskController. + * @returns {VersionedData} The state object wrapped in an object that includes a metadata key. + */ function versionifyData (state) { versionedData.data = state return versionedData @@ -208,6 +316,18 @@ function setupController (initState, initLangCode) { return popupIsOpen || Boolean(Object.keys(openMetamaskTabsIDs).length) || notificationIsOpen } + /** + * A runtime.Port object, as provided by the browser: + * @link https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/Port + * @typedef Port + * @type Object + */ + + /** + * Connects a Port to the MetaMask controller via a multiplexed duplex stream. + * This method identifies trusted (MetaMask) interfaces, and connects them differently from untrusted (web pages). + * @param {Port} remotePort - The port provided by a new context. + */ function connectRemote (remotePort) { const processName = remotePort.name const isMetaMaskInternalProcess = metamaskInternalProcessHash[processName] @@ -261,7 +381,10 @@ function setupController (initState, initLangCode) { controller.messageManager.on('updateBadge', updateBadge) controller.personalMessageManager.on('updateBadge', updateBadge) - // plugin badge text + /** + * Updates the Web Extension's "badge" number, on the little fox in the toolbar. + * The number reflects the current number of pending transactions or message signatures needing user approval. + */ function updateBadge () { var label = '' var unapprovedTxCount = controller.txController.getUnapprovedTxCount() @@ -283,7 +406,9 @@ function setupController (initState, initLangCode) { // Etc... // -// popup trigger +/** + * Opens the browser popup for user confirmation + */ function triggerUi () { extension.tabs.query({ active: true }, tabs => { const currentlyActiveMetamaskTab = Boolean(tabs.find(tab => openMetamaskTabsIDs[tab.id])) |