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

Add JSDoc ESLint rules (#12112)

ESLint rules have been added to enforce our JSDoc conventions. These
rules were introduced by updating `@metamask/eslint-config` to v9.

Some of the rules have been disabled because the effort to fix all lint
errors was too high. It might be easiest to enable these rules one
directory at a time, or one rule at a time.

Most of the changes in this PR were a result of running
`yarn lint:fix`. There were a handful of manual changes that seemed
obvious and simple to make. Anything beyond that and the rule was left
disabled.
This commit is contained in:
Mark Stacey 2022-01-07 12:27:33 -03:30 committed by GitHub
parent e333eb4628
commit 3732c5f71e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
119 changed files with 931 additions and 585 deletions

View File

@ -41,7 +41,7 @@ module.exports = {
extends: ['@metamask/eslint-config', '@metamask/eslint-config-nodejs'],
plugins: ['@babel', 'import'],
plugins: ['@babel', 'import', 'jsdoc'],
globals: {
document: 'readonly',
@ -83,6 +83,10 @@ module.exports = {
'node/no-process-env': 'off',
// Allow tag `jest-environment` to work around Jest bug
// See: https://github.com/facebook/jest/issues/7780
'jsdoc/check-tag-names': ['error', { definedTags: ['jest-environment'] }],
// TODO: remove this override
'padding-line-between-statements': [
'error',
@ -108,6 +112,15 @@ module.exports = {
'node/no-sync': 'off',
'node/no-unpublished-import': 'off',
'node/no-unpublished-require': 'off',
'jsdoc/match-description': 'off',
'jsdoc/require-description': 'off',
'jsdoc/require-jsdoc': 'off',
'jsdoc/require-param-description': 'off',
'jsdoc/require-param-type': 'off',
'jsdoc/require-returns-description': 'off',
'jsdoc/require-returns-type': 'off',
'jsdoc/require-returns': 'off',
'jsdoc/valid-types': 'off',
},
overrides: [
{
@ -241,6 +254,9 @@ module.exports = {
],
settings: {
jsdoc: {
mode: 'typescript',
},
react: {
// If this is set to 'detect', ESLint will import React in order to find
// its version. Because we run ESLint in the build system under LavaMoat,

View File

@ -74,6 +74,7 @@ initialize().catch(log.error);
/**
* 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.
@ -119,11 +120,12 @@ initialize().catch(log.error);
/**
* @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.
* @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() {
@ -140,6 +142,7 @@ async function initialize() {
/**
* 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() {
@ -251,6 +254,7 @@ 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.
*/
@ -327,6 +331,7 @@ function setupController(initState, initLangCode) {
/**
* A runtime.Port object, as provided by the browser:
*
* @see https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/runtime/Port
* @typedef Port
* @type Object
@ -335,6 +340,7 @@ function setupController(initState, initLangCode) {
/**
* 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) {

View File

@ -35,7 +35,6 @@ const defaultState = {
*/
export default class AlertController {
/**
* @constructor
* @param {AlertControllerOptions} [opts] - Controller configuration parameters
*/
constructor(opts = {}) {
@ -73,6 +72,7 @@ export default class AlertController {
/**
* Sets the "switch to connected" alert as shown for the given origin
*
* @param {string} origin - The origin the alert has been shown for
*/
setUnconnectedAccountAlertShown(origin) {

View File

@ -5,7 +5,6 @@ import { MINUTE } from '../../../shared/constants/time';
export default class AppStateController extends EventEmitter {
/**
* @constructor
* @param {Object} opts
*/
constructor(opts = {}) {
@ -110,6 +109,7 @@ export default class AppStateController extends EventEmitter {
/**
* Sets the default home tab
*
* @param {string} [defaultHomeActiveTabName] - the tab name
*/
setDefaultHomeActiveTabName(defaultHomeActiveTabName) {
@ -128,8 +128,7 @@ export default class AppStateController extends EventEmitter {
}
/**
* Record that the user has been shown the recovery phrase reminder
* @returns {void}
* Record that the user has been shown the recovery phrase reminder.
*/
setRecoveryPhraseReminderHasBeenShown() {
this.store.updateState({
@ -139,8 +138,8 @@ export default class AppStateController extends EventEmitter {
/**
* Record the timestamp of the last time the user has seen the recovery phrase reminder
* @param {number} lastShown - timestamp when user was last shown the reminder
* @returns {void}
*
* @param {number} lastShown - timestamp when user was last shown the reminder.
*/
setRecoveryPhraseReminderLastShown(lastShown) {
this.store.updateState({
@ -149,8 +148,7 @@ export default class AppStateController extends EventEmitter {
}
/**
* Sets the last active time to the current time
* @returns {void}
* Sets the last active time to the current time.
*/
setLastActiveTime() {
this._resetTimer();
@ -158,9 +156,9 @@ export default class AppStateController extends EventEmitter {
/**
* Sets the inactive timeout for the app
* @param {number} timeoutMinutes - the inactive timeout in minutes
* @returns {void}
*
* @private
* @param {number} timeoutMinutes - The inactive timeout in minutes.
*/
_setInactiveTimeout(timeoutMinutes) {
this.store.updateState({
@ -176,7 +174,6 @@ export default class AppStateController extends EventEmitter {
* If the {@code timeoutMinutes} state is falsy (i.e., zero) then a new
* timer will not be created.
*
* @returns {void}
* @private
*/
_resetTimer() {
@ -198,7 +195,9 @@ export default class AppStateController extends EventEmitter {
/**
* Sets the current browser and OS environment
* @returns {void}
*
* @param os
* @param browser
*/
setBrowserEnvironment(os, browser) {
this.store.updateState({ browserEnvironment: { os, browser } });
@ -206,7 +205,9 @@ export default class AppStateController extends EventEmitter {
/**
* Adds a pollingToken for a given environmentType
* @returns {void}
*
* @param pollingToken
* @param pollingTokenType
*/
addPollingToken(pollingToken, pollingTokenType) {
const prevState = this.store.getState()[pollingTokenType];
@ -217,7 +218,9 @@ export default class AppStateController extends EventEmitter {
/**
* removes a pollingToken for a given environmentType
* @returns {void}
*
* @param pollingToken
* @param pollingTokenType
*/
removePollingToken(pollingToken, pollingTokenType) {
const prevState = this.store.getState()[pollingTokenType];
@ -228,7 +231,6 @@ export default class AppStateController extends EventEmitter {
/**
* clears all pollingTokens
* @returns {void}
*/
clearPollingTokens() {
this.store.updateState({
@ -240,7 +242,8 @@ export default class AppStateController extends EventEmitter {
/**
* Sets whether the testnet dismissal link should be shown in the network dropdown
* @returns {void}
*
* @param showTestnetMessageInDropdown
*/
setShowTestnetMessageInDropdown(showTestnetMessageInDropdown) {
this.store.updateState({ showTestnetMessageInDropdown });
@ -248,7 +251,8 @@ export default class AppStateController extends EventEmitter {
/**
* Sets a property indicating the model of the user's Trezor hardware wallet
* @returns {void}
*
* @param trezorModel - The Trezor model.
*/
setTrezorModel(trezorModel) {
this.store.updateState({ trezorModel });
@ -256,6 +260,8 @@ export default class AppStateController extends EventEmitter {
/**
* A setter for the `collectiblesDetectionNoticeDismissed` property
*
* @param collectiblesDetectionNoticeDismissed
*/
setCollectiblesDetectionNoticeDismissed(
collectiblesDetectionNoticeDismissed,

View File

@ -34,6 +34,7 @@ export default class CachedBalancesController {
* if balances in the passed accounts are truthy.
*
* @param {Object} obj - The the recently updated accounts object for the current chain
* @param obj.accounts
* @returns {Promise<void>}
*/
async updateCachedBalances({ accounts }) {
@ -80,7 +81,6 @@ export default class CachedBalancesController {
* selections.
*
* @private
*
*/
_registerUpdates() {
const update = this.updateCachedBalances.bind(this);

View File

@ -18,6 +18,12 @@ export default class DetectTokensController {
* Creates a DetectTokensController
*
* @param {Object} [config] - Options to configure controller
* @param config.interval
* @param config.preferences
* @param config.network
* @param config.keyringMemStore
* @param config.tokenList
* @param config.tokensController
*/
constructor({
interval = DEFAULT_INTERVAL,
@ -152,7 +158,7 @@ export default class DetectTokensController {
/* eslint-disable accessor-pairs */
/**
* @type {Number}
* @type {number}
*/
set interval(interval) {
this._handle && clearInterval(this._handle);
@ -177,6 +183,7 @@ export default class DetectTokensController {
/**
* In setter when isUnlocked is updated to true, detectNewTokens and restart polling
*
* @type {Object}
*/
set keyringMemStore(keyringMemStore) {
@ -206,6 +213,7 @@ export default class DetectTokensController {
/**
* Internal isActive state
*
* @type {Object}
*/
get isActive() {

View File

@ -157,10 +157,10 @@ export default class IncomingTransactionsController {
* from, fetches the transactions and then saves them and the next block
* number to begin fetching from in state. Block numbers and transactions are
* stored per chainId.
*
* @private
* @param {string} address - address to lookup transactions for
* @param {number} [newBlockNumberDec] - block number to begin fetching from
* @returns {void}
*/
async _update(address, newBlockNumberDec) {
const chainId = this.getCurrentChainId();
@ -259,6 +259,7 @@ export default class IncomingTransactionsController {
/**
* Transmutes a EtherscanTransaction into a TransactionMeta
*
* @param {EtherscanTransaction} etherscanTransaction - the transaction to normalize
* @param {string} chainId - The chainId of the current network
* @returns {TransactionMeta}
@ -307,13 +308,12 @@ export default class IncomingTransactionsController {
* is called with and invokes the comparator with both the cached, previous,
* value and the current value. If specified, the initialValue will be passed
* in as the previous value on the first invocation of the returned method.
* @template A
* @params {A=} type of compared value
* @param {(prevValue: A, nextValue: A) => void} comparator - method to compare
* previous and next values.
* @param {A} [initialValue] - initial value to supply to prevValue
* on first call of the method.
* @returns {void}
*
* @template A - The type of the compared value.
* @param {(prevValue: A, nextValue: A) => void} comparator - A method to compare
* the previous and next values.
* @param {A} [initialValue] - The initial value to supply to prevValue
* on first call of the method.
*/
function previousValueComparator(comparator, initialValue) {
let first = true;

View File

@ -103,12 +103,13 @@ function getMockBlockTracker() {
/**
* Returns a transaction object matching the expected format returned
* by the Etherscan API
*
* @param {Object} [params] - options bag
* @param {string} [params.toAddress] - The hex-prefixed address of the recipient
* @param {number} [params.blockNumber] - The block number for the transaction
* @param {boolean} [params.useEIP1559] - Use EIP-1559 gas fields
* @param
* @returns {EtherscanTransaction}
* @param params.hash
* @returns {EtherscanTransaction}
*/
const getFakeEtherscanTransaction = ({
toAddress = MOCK_SELECTED_ADDRESS,

View File

@ -40,19 +40,21 @@ const exceptionsToFilter = {
export default class MetaMetricsController {
/**
* @param {Object} segment - an instance of analytics-node for tracking
* @param {object} options
* @param {Object} options.segment - an instance of analytics-node for tracking
* events that conform to the new MetaMetrics tracking plan.
* @param {Object} preferencesStore - The preferences controller store, used
* @param {Object} options.preferencesStore - The preferences controller store, used
* to access and subscribe to preferences that will be attached to events
* @param {function} onNetworkDidChange - Used to attach a listener to the
* @param {Function} options.onNetworkDidChange - Used to attach a listener to the
* networkDidChange event emitted by the networkController
* @param {function} getCurrentChainId - Gets the current chain id from the
* @param {Function} options.getCurrentChainId - Gets the current chain id from the
* network controller
* @param {function} getNetworkIdentifier - Gets the current network
* @param {Function} options.getNetworkIdentifier - Gets the current network
* identifier from the network controller
* @param {string} version - The version of the extension
* @param {string} environment - The environment the extension is running in
* @param {MetaMetricsControllerState} initState - State to initialized with
* @param {string} options.version - The version of the extension
* @param {string} options.environment - The environment the extension is running in
* @param {MetaMetricsControllerState} options.initState - State to initialized with
* @param options.captureException
*/
constructor({
segment,
@ -132,6 +134,7 @@ export default class MetaMetricsController {
/**
* Build the context object to attach to page and track events.
*
* @private
* @param {Pick<MetaMetricsContext, 'referrer'>} [referrer] - dapp origin that initialized
* the notification window.
@ -154,11 +157,12 @@ export default class MetaMetricsController {
/**
* Build's the event payload, processing all fields into a format that can be
* fed to Segment's track method
*
* @private
* @param {
* Omit<MetaMetricsEventPayload, 'sensitiveProperties'>
* } rawPayload - raw payload provided to trackEvent
* @returns {SegmentEventPayload} - formatted event payload for segment
* @returns {SegmentEventPayload} formatted event payload for segment
*/
_buildEventPayload(rawPayload) {
const {
@ -199,6 +203,7 @@ export default class MetaMetricsController {
* Perform validation on the payload and update the id type to use before
* sending to Segment. Also examines the options to route and handle the
* event appropriately.
*
* @private
* @param {SegmentEventPayload} payload - properties to attach to event
* @param {MetaMetricsEventOptions} [options] - options for routing and
@ -273,6 +278,7 @@ export default class MetaMetricsController {
/**
* track a page view with Segment
*
* @param {MetaMetricsPagePayload} payload - details of the page viewed
* @param {MetaMetricsPageOptions} [options] - options for handling the page
* view
@ -311,6 +317,7 @@ export default class MetaMetricsController {
/**
* submits a metametrics event, not waiting for it to complete or allowing its error to bubble up
*
* @param {MetaMetricsEventPayload} payload - details of the event
* @param {MetaMetricsEventOptions} [options] - options for handling/routing the event
*/
@ -327,6 +334,7 @@ export default class MetaMetricsController {
* routing the event to the appropriate segment source. Will split events
* with sensitiveProperties into two events, tracking the sensitiveProperties
* with the anonymousId only.
*
* @param {MetaMetricsEventPayload} payload - details of the event
* @param {MetaMetricsEventOptions} [options] - options for handling/routing the event
* @returns {Promise<void>}
@ -375,6 +383,7 @@ export default class MetaMetricsController {
/**
* validates a metametrics event
*
* @param {MetaMetricsEventPayload} payload - details of the event
*/
validatePayload(payload) {

View File

@ -110,8 +110,7 @@ export default class NetworkController extends EventEmitter {
* Sets the Infura project ID
*
* @param {string} projectId - The Infura project ID
* @throws {Error} if the project ID is not a valid string
* @return {void}
* @throws {Error} If the project ID is not a valid string.
*/
setInfuraProjectId(projectId) {
if (!projectId || typeof projectId !== 'string') {
@ -137,6 +136,7 @@ export default class NetworkController extends EventEmitter {
/**
* Method to return the latest block for the current network
*
* @returns {Object} Block header
*/
getLatestBlock() {
@ -158,6 +158,7 @@ export default class NetworkController extends EventEmitter {
/**
* Method to check if the block header contains fields that indicate EIP 1559
* support (baseFeePerGas).
*
* @returns {Promise<boolean>} true if current network supports EIP 1559
*/
async getEIP1559Compatibility() {
@ -189,6 +190,7 @@ export default class NetworkController extends EventEmitter {
/**
* Set EIP support indication in the networkDetails store
*
* @param {number} EIPNumber - The number of the EIP to mark support for
* @param {boolean} isSupported - True if the EIP is supported
*/
@ -310,6 +312,8 @@ export default class NetworkController extends EventEmitter {
/**
* Sets the provider config and switches the network.
*
* @param config
*/
setProviderConfig(config) {
this.previousProviderStore.updateState(this.getProviderConfig());

View File

@ -3,8 +3,8 @@ import log from 'loglevel';
/**
* @typedef {Object} InitState
* @property {Boolean} seedPhraseBackedUp Indicates whether the user has completed the seed phrase backup challenge
* @property {Boolean} completedOnboarding Indicates whether the user has completed the onboarding flow
* @property {boolean} seedPhraseBackedUp Indicates whether the user has completed the seed phrase backup challenge
* @property {boolean} completedOnboarding Indicates whether the user has completed the onboarding flow
*/
/**
@ -20,7 +20,7 @@ export default class OnboardingController {
/**
* Creates a new controller instance
*
* @param {OnboardingOptions} [opts] Controller configuration parameters
* @param {OnboardingOptions} [opts] - Controller configuration parameters
*/
constructor(opts = {}) {
const initialTransientState = {
@ -57,7 +57,6 @@ export default class OnboardingController {
* Setter for the `firstTimeFlowType` property
*
* @param {string} type - Indicates the type of first time flow - create or import - the user wishes to follow
*
*/
setFirstTimeFlowType(type) {
this.store.updateState({ firstTimeFlowType: type });

View File

@ -27,7 +27,6 @@ export default class PreferencesController {
* @property {Object} store.knownMethodData Contains all data methods known by the user
* @property {string} store.currentLocale The preferred language locale key
* @property {string} store.selectedAddress A hex string that matches the currently selected address in the app
*
*/
constructor(opts = {}) {
const initState = {
@ -89,6 +88,7 @@ export default class PreferencesController {
/**
* Sets the {@code forgottenPassword} state property
*
* @param {boolean} forgottenPassword - whether or not the user has forgotten their password
*/
setPasswordForgotten(forgottenPassword) {
@ -99,7 +99,6 @@ export default class PreferencesController {
* Setter for the `useBlockie` property
*
* @param {boolean} val - Whether or not the user prefers blockie indicators
*
*/
setUseBlockie(val) {
this.store.updateState({ useBlockie: val });
@ -109,7 +108,6 @@ export default class PreferencesController {
* Setter for the `useNonceField` property
*
* @param {boolean} val - Whether or not the user prefers to set nonce
*
*/
setUseNonceField(val) {
this.store.updateState({ useNonceField: val });
@ -119,7 +117,6 @@ export default class PreferencesController {
* Setter for the `usePhishDetect` property
*
* @param {boolean} val - Whether or not the user prefers phishing domain protection
*
*/
setUsePhishDetect(val) {
this.store.updateState({ usePhishDetect: val });
@ -129,7 +126,6 @@ export default class PreferencesController {
* Setter for the `useTokenDetection` property
*
* @param {boolean} val - Whether or not the user prefers to use the static token list or dynamic token list from the API
*
*/
setUseTokenDetection(val) {
this.store.updateState({ useTokenDetection: val });
@ -139,7 +135,6 @@ export default class PreferencesController {
* Setter for the `useCollectibleDetection` property
*
* @param {boolean} val - Whether or not the user prefers to autodetect collectibles.
*
*/
setUseCollectibleDetection(val) {
const { openSeaEnabled } = this.store.getState();
@ -155,7 +150,6 @@ export default class PreferencesController {
* Setter for the `openSeaEnabled` property
*
* @param {boolean} val - Whether or not the user prefers to use the OpenSea API for collectibles data.
*
*/
setOpenSeaEnabled(val) {
this.store.updateState({ openSeaEnabled: val });
@ -168,7 +162,6 @@ export default class PreferencesController {
* Setter for the `advancedGasFee` property
*
* @param {object} val - holds the maxBaseFee and PriorityFee that the user set as default advanced settings.
*
*/
setAdvancedGasFee(val) {
this.store.updateState({ advancedGasFee: val });
@ -190,7 +183,6 @@ export default class PreferencesController {
* Setter for the `currentLocale` property
*
* @param {string} key - he preferred language locale key
*
*/
setCurrentLocale(key) {
const textDirection = ['ar', 'dv', 'fa', 'he', 'ku'].includes(key)
@ -208,7 +200,6 @@ export default class PreferencesController {
* not included in addresses array
*
* @param {string[]} addresses - An array of hex addresses
*
*/
setAddresses(addresses) {
const oldIdentities = this.store.getState().identities;
@ -250,7 +241,6 @@ export default class PreferencesController {
* Adds addresses to the identities object without removing identities
*
* @param {string[]} addresses - An array of hex addresses
*
*/
addAddresses(addresses) {
const { identities } = this.store.getState();
@ -315,7 +305,6 @@ export default class PreferencesController {
* Setter for the `selectedAddress` property
*
* @param {string} _address - A new hex address for an account
*
*/
setSelectedAddress(_address) {
const address = normalizeAddress(_address);
@ -334,7 +323,6 @@ export default class PreferencesController {
* Getter for the `selectedAddress` property
*
* @returns {string} The hex address for the currently selected account
*
*/
getSelectedAddress() {
return this.store.getState().selectedAddress;
@ -342,6 +330,7 @@ export default class PreferencesController {
/**
* Sets a custom label for an account
*
* @param {string} account - the account to set a label for
* @param {string} label - the custom label for the account
* @returns {Promise<string>}
@ -369,7 +358,6 @@ export default class PreferencesController {
* @param {string} [newRpcDetails.ticker] - Optional ticker symbol of the selected network.
* @param {string} [newRpcDetails.nickname] - Optional nickname of the selected network.
* @param {Object} [newRpcDetails.rpcPrefs] - Optional RPC preferences, such as the block explorer URL
*
*/
async updateRpc(newRpcDetails) {
const rpcList = this.getFrequentRpcListDetail();
@ -445,7 +433,6 @@ export default class PreferencesController {
* @param {string} [ticker] - Ticker symbol of the selected network.
* @param {string} [nickname] - Nickname of the selected network.
* @param {Object} [rpcPrefs] - Optional RPC preferences, such as the block explorer URL
*
*/
addToFrequentRpcList(
rpcUrl,
@ -475,8 +462,7 @@ export default class PreferencesController {
* Removes custom RPC url from state.
*
* @param {string} url - The RPC url to remove from frequentRpcList.
* @returns {Promise<array>} Promise resolving to updated frequentRpcList.
*
* @returns {Promise<Array>} Promise resolving to updated frequentRpcList.
*/
removeFromFrequentRpcList(url) {
const rpcList = this.getFrequentRpcListDetail();
@ -493,8 +479,7 @@ export default class PreferencesController {
/**
* Getter for the `frequentRpcListDetail` property.
*
* @returns {array<array>} An array of rpc urls.
*
* @returns {Array<Array>} An array of rpc urls.
*/
getFrequentRpcListDetail() {
return this.store.getState().frequentRpcListDetail;
@ -506,7 +491,6 @@ export default class PreferencesController {
* @param {string} feature - A key that corresponds to a UI feature.
* @param {boolean} activated - Indicates whether or not the UI feature should be displayed
* @returns {Promise<object>} Promises a new object; the updated featureFlags object.
*
*/
setFeatureFlag(feature, activated) {
const currentFeatureFlags = this.store.getState().featureFlags;
@ -523,6 +507,7 @@ export default class PreferencesController {
/**
* Updates the `preferences` property, which is an object. These are user-controlled features
* found in the settings page.
*
* @param {string} preference - The preference to enable or disable.
* @param {boolean} value - Indicates whether or not the preference should be enabled or disabled.
* @returns {Promise<object>} Promises a new object; the updated preferences object.
@ -540,6 +525,7 @@ export default class PreferencesController {
/**
* A getter for the `preferences` property
*
* @returns {Object} A key-boolean map of user-selected preferences.
*/
getPreferences() {
@ -548,6 +534,7 @@ export default class PreferencesController {
/**
* A getter for the `ipfsGateway` property
*
* @returns {string} The current IPFS gateway domain
*/
getIpfsGateway() {
@ -556,6 +543,7 @@ export default class PreferencesController {
/**
* A setter for the `ipfsGateway` property
*
* @param {string} domain - The new IPFS gateway domain
* @returns {Promise<string>} A promise of the update IPFS gateway domain
*/
@ -565,7 +553,8 @@ export default class PreferencesController {
}
/**
* A setter for the `useWebHid` property
* A setter for the `ledgerTransportType` property.
*
* @param {string} ledgerTransportType - Either 'ledgerLive', 'webhid' or 'u2f'
* @returns {string} The transport type that was set.
*/
@ -575,8 +564,9 @@ export default class PreferencesController {
}
/**
* A getter for the `ledgerTransportType` property
* @returns {boolean} User preference of using WebHid to connect Ledger
* A getter for the `ledgerTransportType` property.
*
* @returns {string} The current preferred Ledger transport type.
*/
getLedgerTransportPreference() {
return this.store.getState().ledgerTransportType;
@ -584,8 +574,8 @@ export default class PreferencesController {
/**
* A setter for the user preference to dismiss the seed phrase backup reminder
* @param {bool} dismissBackupReminder- User preference for dismissing the back up reminder
* @returns {void}
*
* @param {bool} dismissSeedBackUpReminder - User preference for dismissing the back up reminder.
*/
async setDismissSeedBackUpReminder(dismissSeedBackUpReminder) {
await this.store.updateState({
@ -609,8 +599,8 @@ export default class PreferencesController {
/**
*
* A setter for the `infuraBlocked` property
* @param {boolean} isBlocked - Bool indicating whether Infura is blocked
*
* @param {boolean} isBlocked - Bool indicating whether Infura is blocked
*/
_setInfuraBlocked(isBlocked) {
const { infuraBlocked } = this.store.getState();

View File

@ -845,7 +845,7 @@ export default class SwapsController {
/**
* Calculates the median overallValueOfQuote of a sample of quotes.
*
* @param {Array} quotes - A sample of quote objects with overallValueOfQuote, ethFee, metaMaskFeeInEth, and ethValueOfTokens properties
* @param {Array} _quotes - A sample of quote objects with overallValueOfQuote, ethFee, metaMaskFeeInEth, and ethValueOfTokens properties
* @returns {Object} An object with the ethValueOfTokens, ethFee, and metaMaskFeeInEth of the quote with the median overallValueOfQuote
*/
function getMedianEthValueQuote(_quotes) {

View File

@ -72,31 +72,31 @@ export const TRANSACTION_EVENTS = {
*/
/**
Transaction Controller is an aggregate of sub-controllers and trackers
composing them in a way to be exposed to the metamask controller
<br>- txStateManager
responsible for the state of a transaction and
storing the transaction
<br>- pendingTxTracker
watching blocks for transactions to be include
and emitting confirmed events
<br>- txGasUtil
gas calculations and safety buffering
<br>- nonceTracker
calculating nonces
@class
@param {Object} opts
@param {Object} opts.initState - initial transaction list default is an empty array
@param {Object} opts.networkStore - an observable store for network number
@param {Object} opts.blockTracker - An instance of eth-blocktracker
@param {Object} opts.provider - A network provider.
@param {Function} opts.signTransaction - function the signs an @ethereumjs/tx
@param {Object} opts.getPermittedAccounts - get accounts that an origin has permissions for
@param {Function} opts.signTransaction - ethTx signer that returns a rawTx
@param {number} [opts.txHistoryLimit] - number *optional* for limiting how many transactions are in state
@param {Object} opts.preferencesStore
*/
* Transaction Controller is an aggregate of sub-controllers and trackers
* composing them in a way to be exposed to the metamask controller
*
* - `txStateManager
* responsible for the state of a transaction and
* storing the transaction
* - pendingTxTracker
* watching blocks for transactions to be include
* and emitting confirmed events
* - txGasUtil
* gas calculations and safety buffering
* - nonceTracker
* calculating nonces
*
* @param {Object} opts
* @param {Object} opts.initState - initial transaction list default is an empty array
* @param {Object} opts.networkStore - an observable store for network number
* @param {Object} opts.blockTracker - An instance of eth-blocktracker
* @param {Object} opts.provider - A network provider.
* @param {Function} opts.signTransaction - function the signs an @ethereumjs/tx
* @param {Object} opts.getPermittedAccounts - get accounts that an origin has permissions for
* @param {Function} opts.signTransaction - ethTx signer that returns a rawTx
* @param {number} [opts.txHistoryLimit] - number *optional* for limiting how many transactions are in state
* @param {Object} opts.preferencesStore
*/
export default class TransactionController extends EventEmitter {
constructor(opts) {
@ -199,11 +199,13 @@ export default class TransactionController extends EventEmitter {
}
/**
* @ethereumjs/tx uses @ethereumjs/common as a configuration tool for
* `@ethereumjs/tx` uses `@ethereumjs/common` as a configuration tool for
* specifying which chain, network, hardfork and EIPs to support for
* a transaction. By referencing this configuration, and analyzing the fields
* specified in txParams, @ethereumjs/tx is able to determine which EIP-2718
* specified in txParams, `@ethereumjs/tx` is able to determine which EIP-2718
* transaction type to use.
*
* @param fromAddress
* @returns {Common} common configuration object
*/
async getCommonConfiguration(fromAddress) {
@ -251,9 +253,11 @@ export default class TransactionController extends EventEmitter {
}
/**
Adds a tx to the txlist
@emits ${txMeta.id}:unapproved
*/
* Adds a tx to the txlist
*
* @param txMeta
* @fires ${txMeta.id}:unapproved
*/
addTransaction(txMeta) {
this.txStateManager.addTransaction(txMeta);
this.emit(`${txMeta.id}:unapproved`, txMeta);
@ -261,9 +265,10 @@ export default class TransactionController extends EventEmitter {
}
/**
Wipes the transactions for a given account
@param {string} address - hex string of the from address for txs being removed
*/
* Wipes the transactions for a given account
*
* @param {string} address - hex string of the from address for txs being removed
*/
wipeTransactions(address) {
this.txStateManager.wipeTransactions(address);
}
@ -327,6 +332,8 @@ export default class TransactionController extends EventEmitter {
* Validates and generates a txMeta with defaults and puts it in txStateManager
* store.
*
* @param txParams
* @param origin
* @returns {txMeta}
*/
async addUnapprovedTransaction(txParams, origin) {
@ -337,11 +344,11 @@ export default class TransactionController extends EventEmitter {
txUtils.validateTxParams(normalizedTxParams, eip1559Compatibility);
/**
`generateTxMeta` adds the default txMeta properties to the passed object.
These include the tx's `id`. As we use the id for determining order of
txes in the tx-state-manager, it is necessary to call the asynchronous
method `this._determineTransactionType` after `generateTxMeta`.
*/
* `generateTxMeta` adds the default txMeta properties to the passed object.
* These include the tx's `id`. As we use the id for determining order of
* txes in the tx-state-manager, it is necessary to call the asynchronous
* method `this._determineTransactionType` after `generateTxMeta`.
*/
let txMeta = this.txStateManager.generateTxMeta({
txParams: normalizedTxParams,
origin,
@ -406,7 +413,9 @@ export default class TransactionController extends EventEmitter {
/**
* Adds the tx gas defaults: gas && gasPrice
*
* @param {Object} txMeta - the txMeta object
* @param getCodeResponse
* @returns {Promise<object>} resolves with txMeta
*/
async addTxGasDefaults(txMeta, getCodeResponse) {
@ -525,7 +534,9 @@ export default class TransactionController extends EventEmitter {
/**
* Gets default gas fees, or returns `undefined` if gas fees are already set
*
* @param {Object} txMeta - The txMeta object
* @param eip1559Compatibility
* @returns {Promise<string|undefined>} The default gas price
*/
async _getDefaultGasFees(txMeta, eip1559Compatibility) {
@ -583,6 +594,7 @@ export default class TransactionController extends EventEmitter {
/**
* Gets default gas limit, or debug information about why gas estimate failed.
*
* @param {Object} txMeta - The txMeta object
* @param {string} getCodeResponse - The transaction category code response, used for debugging purposes
* @returns {Promise<Object>} Object containing the default gas limit, or the simulation failure object
@ -638,6 +650,7 @@ export default class TransactionController extends EventEmitter {
* specified in customGasSettings, or falls back to incrementing by a percent
* which is defined by specifying a numerator. 11 is a 10% bump, 12 would be
* a 20% bump, and so on.
*
* @param {import(
* '../../../../shared/constants/transaction'
* ).TransactionMeta} originalTxMeta - Original transaction to use as base
@ -708,9 +721,12 @@ export default class TransactionController extends EventEmitter {
* Creates a new approved transaction to attempt to cancel a previously submitted transaction. The
* new transaction contains the same nonce as the previous, is a basic ETH transfer of 0x value to
* the sender's address, and has a higher gasPrice than that of the previous transaction.
*
* @param {number} originalTxId - the id of the txMeta that you want to attempt to cancel
* @param {CustomGasSettings} [customGasSettings] - overrides to use for gas
* params instead of allowing this method to generate them
* @param options
* @param options.estimatedBaseFee
* @returns {txMeta}
*/
async createCancelTransaction(
@ -761,9 +777,12 @@ export default class TransactionController extends EventEmitter {
* new transaction contains the same nonce as the previous. By default, the new transaction will use
* the same gas limit and a 10% higher gas price, though it is possible to set a custom value for
* each instead.
*
* @param {number} originalTxId - the id of the txMeta that you want to speed up
* @param {CustomGasSettings} [customGasSettings] - overrides to use for gas
* params instead of allowing this method to generate them
* @param options
* @param options.estimatedBaseFee
* @returns {txMeta}
*/
async createSpeedUpTransaction(
@ -800,9 +819,10 @@ export default class TransactionController extends EventEmitter {
}
/**
updates the txMeta in the txStateManager
@param {Object} txMeta - the updated txMeta
*/
* updates the txMeta in the txStateManager
*
* @param {Object} txMeta - the updated txMeta
*/
async updateTransaction(txMeta) {
this.txStateManager.updateTransaction(
txMeta,
@ -811,9 +831,10 @@ export default class TransactionController extends EventEmitter {
}
/**
updates and approves the transaction
@param {Object} txMeta
*/
* updates and approves the transaction
*
* @param {Object} txMeta
*/
async updateAndApproveTransaction(txMeta) {
this.txStateManager.updateTransaction(
txMeta,
@ -823,13 +844,14 @@ export default class TransactionController extends EventEmitter {
}
/**
sets the tx status to approved
auto fills the nonce
signs the transaction
publishes the transaction
if any of these steps fails the tx status will be set to failed
@param {number} txId - the tx's Id
*/
* sets the tx status to approved
* auto fills the nonce
* signs the transaction
* publishes the transaction
* if any of these steps fails the tx status will be set to failed
*
* @param {number} txId - the tx's Id
*/
async approveTransaction(txId) {
// TODO: Move this safety out of this function.
// Since this transaction is async,
@ -896,10 +918,11 @@ export default class TransactionController extends EventEmitter {
}
/**
adds the chain id and signs the transaction and set the status to signed
@param {number} txId - the tx's Id
@returns {string} rawTx
*/
* adds the chain id and signs the transaction and set the status to signed
*
* @param {number} txId - the tx's Id
* @returns {string} rawTx
*/
async signTransaction(txId) {
const txMeta = this.txStateManager.getTransaction(txId);
// add network/chain id
@ -937,11 +960,12 @@ export default class TransactionController extends EventEmitter {
}
/**
publishes the raw tx and sets the txMeta to submitted
@param {number} txId - the tx's Id
@param {string} rawTx - the hex string of the serialized signed transaction
@returns {Promise<void>}
*/
* publishes the raw tx and sets the txMeta to submitted
*
* @param {number} txId - the tx's Id
* @param {string} rawTx - the hex string of the serialized signed transaction
* @returns {Promise<void>}
*/
async publishTransaction(txId, rawTx) {
const txMeta = this.txStateManager.getTransaction(txId);
txMeta.rawTx = rawTx;
@ -974,7 +998,11 @@ export default class TransactionController extends EventEmitter {
/**
* Sets the status of the transaction to confirmed and sets the status of nonce duplicates as
* dropped if the txParams have data it will fetch the txReceipt
*
* @param {number} txId - The tx's ID
* @param txReceipt
* @param baseFeePerGas
* @param blockTimestamp
* @returns {Promise<void>}
*/
async confirmTransaction(txId, txReceipt, baseFeePerGas, blockTimestamp) {
@ -1057,10 +1085,11 @@ export default class TransactionController extends EventEmitter {
}
/**
Convenience method for the ui thats sets the transaction to rejected
@param {number} txId - the tx's Id
@returns {Promise<void>}
*/
* Convenience method for the ui thats sets the transaction to rejected
*
* @param {number} txId - the tx's Id
* @returns {Promise<void>}
*/
async cancelTransaction(txId) {
const txMeta = this.txStateManager.getTransaction(txId);
this.txStateManager.setTxStatusRejected(txId);
@ -1068,10 +1097,11 @@ export default class TransactionController extends EventEmitter {
}
/**
Sets the txHas on the txMeta
@param {number} txId - the tx's Id
@param {string} txHash - the hash for the txMeta
*/
* Sets the txHas on the txMeta
*
* @param {number} txId - the tx's Id
* @param {string} txHash - the hash for the txMeta
*/
setTxHash(txId, txHash) {
// Add the tx hash to the persisted meta-tx object
const txMeta = this.txStateManager.getTransaction(txId);
@ -1099,13 +1129,17 @@ export default class TransactionController extends EventEmitter {
Object.keys(this.txStateManager.getUnapprovedTxList()).length;
/**
@returns {number} number of transactions that have the status submitted
@param {string} account - hex prefixed account
*/
* @returns {number} number of transactions that have the status submitted
* @param {string} account - hex prefixed account
*/
this.getPendingTxCount = (account) =>
this.txStateManager.getPendingTransactions(account).length;
/** see txStateManager */
/**
* see txStateManager
*
* @param opts
*/
this.getTransactions = (opts) => this.txStateManager.getTransactions(opts);
}
@ -1118,10 +1152,10 @@ export default class TransactionController extends EventEmitter {
}
/**
If transaction controller was rebooted with transactions that are uncompleted
in steps of the transaction signing or user confirmation process it will either
transition txMetas to a failed state or try to redo those tasks.
*/
* If transaction controller was rebooted with transactions that are uncompleted
* in steps of the transaction signing or user confirmation process it will either
* transition txMetas to a failed state or try to redo those tasks.
*/
_onBootCleanUp() {
this.txStateManager
@ -1166,9 +1200,9 @@ export default class TransactionController extends EventEmitter {
}
/**
is called in constructor applies the listeners for pendingTxTracker txStateManager
and blockTracker
*/
* is called in constructor applies the listeners for pendingTxTracker txStateManager
* and blockTracker
*/
_setupListeners() {
this.txStateManager.on(
'tx:status-update',
@ -1236,6 +1270,7 @@ export default class TransactionController extends EventEmitter {
* It will never return TRANSACTION_TYPE_CANCEL or TRANSACTION_TYPE_RETRY as these
* represent specific events that we control from the extension and are added manually
* at transaction creation.
*
* @param {Object} txParams - Parameters for the transaction
* @returns {InferTransactionTypeResult}
*/
@ -1279,11 +1314,11 @@ export default class TransactionController extends EventEmitter {
}
/**
Sets other txMeta statuses to dropped if the txMeta that has been confirmed has other transactions
in the list have the same nonce
@param {number} txId - the txId of the transaction that has been confirmed in a block
*/
* Sets other txMeta statuses to dropped if the txMeta that has been confirmed has other transactions
* in the list have the same nonce
*
* @param {number} txId - the txId of the transaction that has been confirmed in a block
*/
_markNonceDuplicatesDropped(txId) {
// get the confirmed transactions nonce and from address
const txMeta = this.txStateManager.getTransaction(txId);
@ -1342,8 +1377,8 @@ export default class TransactionController extends EventEmitter {
}
/**
Updates the memStore in transaction controller
*/
* Updates the memStore in transaction controller
*/
_updateMemstore() {
const unapprovedTxs = this.txStateManager.getUnapprovedTxList();
const currentNetworkTxList = this.txStateManager.getTransactions({
@ -1404,6 +1439,7 @@ export default class TransactionController extends EventEmitter {
* Extracts relevant properties from a transaction meta
* object and uses them to create and send metrics for various transaction
* events.
*
* @param {Object} txMeta - the txMeta object
* @param {string} event - the name of the transaction event
* @param {Object} extraParams - optional props and values to include in sensitiveProperties

View File

@ -2,10 +2,11 @@ import jsonDiffer from 'fast-json-patch';
import { cloneDeep } from 'lodash';
/**
converts non-initial history entries into diffs
@param {Array} longHistory
@returns {Array}
*/
* converts non-initial history entries into diffs
*
* @param {Array} longHistory
* @returns {Array}
*/
export function migrateFromSnapshotsToDiffs(longHistory) {
return (
longHistory
@ -20,17 +21,18 @@ export function migrateFromSnapshotsToDiffs(longHistory) {
}
/**
Generates an array of history objects sense the previous state.
The object has the keys
op (the operation performed),
path (the key and if a nested object then each key will be separated with a `/`)
value
with the first entry having the note and a timestamp when the change took place
@param {Object} previousState - the previous state of the object
@param {Object} newState - the update object
@param {string} [note] - a optional note for the state change
@returns {Array}
*/
* Generates an array of history objects sense the previous state.
* The object has the keys
* op (the operation performed),
* path (the key and if a nested object then each key will be separated with a `/`)
* value
* with the first entry having the note and a timestamp when the change took place
*
* @param {Object} previousState - the previous state of the object
* @param {Object} newState - the update object
* @param {string} [note] - a optional note for the state change
* @returns {Array}
*/
export function generateHistoryEntry(previousState, newState, note) {
const entry = jsonDiffer.compare(previousState, newState);
// Add a note to the first op, since it breaks if we append it to the entry
@ -44,9 +46,11 @@ export function generateHistoryEntry(previousState, newState, note) {
}
/**
Recovers previous txMeta state obj
@returns {Object}
*/
* Recovers previous txMeta state obj
*
* @param _shortHistory
* @returns {Object}
*/
export function replayHistory(_shortHistory) {
const shortHistory = cloneDeep(_shortHistory);
return shortHistory.reduce(
@ -56,6 +60,7 @@ export function replayHistory(_shortHistory) {
/**
* Snapshot {@code txMeta}
*
* @param {Object} txMeta - the tx metadata object
* @returns {Object} a deep clone without history
*/

View File

@ -31,6 +31,7 @@ export function normalizeAndValidateTxParams(txParams, lowerCase = true) {
/**
* Normalizes the given txParams
*
* @param {Object} txParams - The transaction params
* @param {boolean} [lowerCase] - Whether to lowercase the 'to' address.
* Default: true
@ -50,10 +51,11 @@ export function normalizeTxParams(txParams, lowerCase = true) {
/**
* Given two fields, ensure that the second field is not included in txParams,
* and if it is throw an invalidParams error.
*
* @param {Object} txParams - the transaction parameters object
* @param {string} fieldBeingValidated - the current field being validated
* @param {string} mutuallyExclusiveField - the field to ensure is not provided
* @throws {ethErrors.rpc.invalidParams} - throws if mutuallyExclusiveField is
* @throws {ethErrors.rpc.invalidParams} Throws if mutuallyExclusiveField is
* present in txParams.
*/
function ensureMutuallyExclusiveFieldsNotProvided(
@ -71,9 +73,10 @@ function ensureMutuallyExclusiveFieldsNotProvided(
/**
* Ensures that the provided value for field is a string, throws an
* invalidParams error if field is not a string.
*
* @param {Object} txParams - the transaction parameters object
* @param {string} field - the current field being validated
* @throws {ethErrors.rpc.invalidParams} - throws if field is not a string
* @throws {ethErrors.rpc.invalidParams} Throws if field is not a string
*/
function ensureFieldIsString(txParams, field) {
if (typeof txParams[field] !== 'string') {
@ -87,10 +90,11 @@ function ensureFieldIsString(txParams, field) {
* Ensures that the provided txParams has the proper 'type' specified for the
* given field, if it is provided. If types do not match throws an
* invalidParams error.
*
* @param {Object} txParams - the transaction parameters object
* @param {'gasPrice' | 'maxFeePerGas' | 'maxPriorityFeePerGas'} field - the
* current field being validated
* @throws {ethErrors.rpc.invalidParams} - throws if type does not match the
* @throws {ethErrors.rpc.invalidParams} Throws if type does not match the
* expectations for provided field.
*/
function ensureProperTransactionEnvelopeTypeProvided(txParams, field) {
@ -121,6 +125,7 @@ function ensureProperTransactionEnvelopeTypeProvided(txParams, field) {
/**
* Validates the given tx parameters
*
* @param {Object} txParams - the tx params
* @param {boolean} eip1559Compatibility - whether or not the current network supports EIP-1559 transactions
* @throws {Error} if the tx params contains invalid fields
@ -221,6 +226,7 @@ export function validateTxParams(txParams, eip1559Compatibility = true) {
/**
* Validates the {@code from} field in the given tx params
*
* @param {Object} txParams
* @throws {Error} if the from address isn't valid
*/
@ -237,6 +243,7 @@ export function validateFrom(txParams) {
/**
* Validates the {@code to} field in the given tx params
*
* @param {Object} txParams - the tx params
* @returns {Object} the tx params
* @throws {Error} if the recipient is invalid OR there isn't tx data
@ -259,6 +266,7 @@ export function validateRecipient(txParams) {
/**
* Returns a list of final states
*
* @returns {string[]} the states that can be considered final states
*/
export function getFinalStates() {

View File

@ -4,21 +4,11 @@ import EthQuery from 'ethjs-query';
import { TRANSACTION_STATUSES } from '../../../../shared/constants/transaction';
/**
Event emitter utility class for tracking the transactions as they<br>
go from a pending state to a confirmed (mined in a block) state<br>
<br>
As well as continues broadcast while in the pending state
<br>
@param {Object} config - non optional configuration object consists of:
@param {Object} config.provider - A network provider.
@param {Object} config.nonceTracker - see nonce tracker
@param {Function} config.getPendingTransactions - a function for getting an array of transactions,
@param {Function} config.publishTransaction - a async function for publishing raw transactions,
@class
*/
* Event emitter utility class for tracking the transactions as they
* go from a pending state to a confirmed (mined in a block) state.
*
* As well as continues broadcast while in the pending state.
*/
export default class PendingTransactionTracker extends EventEmitter {
/**
* We wait this many blocks before emitting a 'tx:dropped' event
@ -33,10 +23,21 @@ export default class PendingTransactionTracker extends EventEmitter {
* A map of transaction hashes to the number of blocks we've seen
* since first considering it dropped
*
* @type {Map<String, number>}
* @type {Map<string, number>}
*/
droppedBlocksBufferByHash = new Map();
/**
* @param {Object} config - Configuration.
* @param {Function} config.approveTransaction - Approves a transaction.
* @param {Function} config.confirmTransaction - Set a transaction as confirmed.
* @param {Function} config.getCompletedTransactions - Returns completed transactions.
* @param {Function} config.getPendingTransactions - Returns an array of pending transactions,
* @param {Object} config.nonceTracker - see nonce tracker
* @param {Object} config.provider - A network provider.
* @param {Object} config.query - An EthQuery instance.
* @param {Function} config.publishTransaction - Publishes a raw transaction,
*/
constructor(config) {
super();
this.query = config.query || new EthQuery(config.provider);
@ -49,8 +50,8 @@ export default class PendingTransactionTracker extends EventEmitter {
}
/**
checks the network for signed txs and releases the nonce global lock if it is
*/
* checks the network for signed txs and releases the nonce global lock if it is
*/
async updatePendingTxs() {
// in order to keep the nonceTracker accurate we block it while updating pending transactions
const nonceGlobalLock = await this.nonceTracker.getGlobalLock();
@ -70,8 +71,9 @@ export default class PendingTransactionTracker extends EventEmitter {
/**
* Resubmits each pending transaction
*
* @param {string} blockNumber - the latest block number in hex
* @emits tx:warning
* @fires tx:warning
* @returns {Promise<void>}
*/
async resubmitPendingTxs(blockNumber) {
@ -119,8 +121,8 @@ export default class PendingTransactionTracker extends EventEmitter {
* @param {Object} txMeta - the transaction metadata
* @param {string} latestBlockNumber - the latest block number in hex
* @returns {Promise<string|undefined>} the tx hash if retried
* @emits tx:block-update
* @emits tx:retry
* @fires tx:block-update
* @fires tx:retry
* @private
*/
async _resubmitTx(txMeta, latestBlockNumber) {
@ -156,12 +158,13 @@ export default class PendingTransactionTracker extends EventEmitter {
/**
* Query the network to see if the given {@code txMeta} has been included in a block
*
* @param {Object} txMeta - the transaction metadata
* @returns {Promise<void>}
* @emits tx:confirmed
* @emits tx:dropped
* @emits tx:failed
* @emits tx:warning
* @fires tx:confirmed
* @fires tx:dropped
* @fires tx:failed
* @fires tx:warning
* @private
*/
@ -260,6 +263,7 @@ export default class PendingTransactionTracker extends EventEmitter {
/**
* Checks whether the nonce in the given {@code txMeta} is correct against the local set of transactions
*
* @param {Object} txMeta - the transaction metadata
* @returns {Promise<boolean>}
* @private

View File

@ -7,6 +7,7 @@ import { hexToBn, BnMultiplyByFraction, bnToHex } from '../../lib/util';
/**
* Result of gas analysis, including either a gas estimate for a successful analysis, or
* debug information for a failed analysis.
*
* @typedef {Object} GasAnalysisResult
* @property {string} blockGasLimit - The gas limit of the block used for the analysis
* @property {string} estimatedGasHex - The estimated gas, in hexadecimal
@ -14,11 +15,12 @@ import { hexToBn, BnMultiplyByFraction, bnToHex } from '../../lib/util';
*/
/**
tx-gas-utils are gas utility methods for Transaction manager
its passed ethquery
and used to do things like calculate gas of a tx.
@param {Object} provider - A network provider.
*/
* tx-gas-utils are gas utility methods for Transaction manager
* its passed ethquery
* and used to do things like calculate gas of a tx.
*
* @param {Object} provider - A network provider.
*/
export default class TxGasUtil {
constructor(provider) {
@ -26,9 +28,9 @@ export default class TxGasUtil {
}
/**
@param {Object} txMeta - the txMeta object
@returns {GasAnalysisResult} The result of the gas analysis
*/
* @param {Object} txMeta - the txMeta object
* @returns {GasAnalysisResult} The result of the gas analysis
*/
async analyzeGasUsage(txMeta) {
const block = await this.query.getBlockByNumber('latest', false);
@ -52,10 +54,11 @@ export default class TxGasUtil {
}
/**
Estimates the tx's gas usage
@param {Object} txMeta - the txMeta object
@returns {string} the estimated gas limit as a hex string
*/
* Estimates the tx's gas usage
*
* @param {Object} txMeta - the txMeta object
* @returns {string} the estimated gas limit as a hex string
*/
async estimateTxGas(txMeta) {
const txParams = cloneDeep(txMeta.txParams);
@ -73,12 +76,13 @@ export default class TxGasUtil {
}
/**
Adds a gas buffer with out exceeding the block gas limit
@param {string} initialGasLimitHex - the initial gas limit to add the buffer too
@param {string} blockGasLimitHex - the block gas limit
@returns {string} the buffered gas limit as a hex string
*/
* Adds a gas buffer with out exceeding the block gas limit
*
* @param {string} initialGasLimitHex - the initial gas limit to add the buffer too
* @param {string} blockGasLimitHex - the block gas limit
* @param multiplier
* @returns {string} the buffered gas limit as a hex string
*/
addGasBuffer(initialGasLimitHex, blockGasLimitHex, multiplier = 1.5) {
const initialGasLimitBn = hexToBn(initialGasLimitHex);
const blockGasLimitBn = hexToBn(blockGasLimitHex);

View File

@ -15,6 +15,7 @@ import { getFinalStates, normalizeAndValidateTxParams } from './lib/util';
/**
* TransactionStatuses reimported from the shared transaction constants file
*
* @typedef {import(
* '../../../../shared/constants/transaction'
* ).TransactionStatusString} TransactionStatusString
@ -40,13 +41,13 @@ import { getFinalStates, normalizeAndValidateTxParams } from './lib/util';
* TransactionStateManager is responsible for the state of a transaction and
* storing the transaction. It also has some convenience methods for finding
* subsets of transactions.
*
* @param {Object} opts
* @param {TransactionState} [opts.initState={ transactions: {} }] - initial
* transactions list keyed by id
* @param {number} [opts.txHistoryLimit] - limit for how many finished
* transactions can hang around in state
* @param {Function} opts.getNetwork - return network number
* @class
*/
export default class TransactionStateManager extends EventEmitter {
constructor({ initState, txHistoryLimit, getNetwork, getCurrentChainId }) {
@ -196,6 +197,7 @@ export default class TransactionStateManager extends EventEmitter {
* is in its final state.
* it will also add the key `history` to the txMeta with the snap shot of
* the original object
*
* @param {TransactionMeta} txMeta - The TransactionMeta object to add.
* @returns {TransactionMeta} The same TransactionMeta, but with validated
* txParams and transaction history.
@ -274,6 +276,7 @@ export default class TransactionStateManager extends EventEmitter {
/**
* updates the txMeta in the list and adds a history entry
*
* @param {Object} txMeta - the txMeta to update
* @param {string} [note] - a note about the update for history
*/
@ -307,6 +310,7 @@ export default class TransactionStateManager extends EventEmitter {
* SearchCriteria can search in any key in TxParams or the base
* TransactionMeta. This type represents any key on either of those two
* types.
*
* @typedef {TxParams[keyof TxParams] | TransactionMeta[keyof TransactionMeta]} SearchableKeys
*/
@ -314,6 +318,7 @@ export default class TransactionStateManager extends EventEmitter {
* Predicates can either be strict values, which is shorthand for using
* strict equality, or a method that receives he value of the specified key
* and returns a boolean.
*
* @typedef {(v: unknown) => boolean | unknown} FilterPredicate
*/
@ -336,7 +341,7 @@ export default class TransactionStateManager extends EventEmitter {
* @param {TransactionMeta[]} [opts.initialList] - If provided the filtering
* will occur on the provided list. By default this will be the full list
* from state sorted by time ASC.
* @param {boolean} [opts.filterToCurrentNetwork=true] - Filter transaction
* @param {boolean} [opts.filterToCurrentNetwork] - Filter transaction
* list to only those that occurred on the current chain or network.
* Defaults to true.
* @param {number} [opts.limit] - limit the number of transactions returned
@ -576,27 +581,28 @@ export default class TransactionStateManager extends EventEmitter {
* Updates a transaction's status in state, and then emits events that are
* subscribed to elsewhere. See below for best guesses on where and how these
* events are received.
*
* @param {number} txId - the TransactionMeta Id
* @param {TransactionStatusString} status - the status to set on the
* TransactionMeta
* @emits txMeta.id:txMeta.status - every time a transaction's status changes
* @fires txMeta.id:txMeta.status - every time a transaction's status changes
* we emit the change passing along the id. This does not appear to be used
* outside of this file, which only listens to this to unsubscribe listeners
* of :rejected and :signed statuses when the inverse status changes. Likely
* safe to drop.
* @emits tx:status-update - every time a transaction's status changes we
* @fires tx:status-update - every time a transaction's status changes we
* emit this event and pass txId and status. This event is subscribed to in
* the TransactionController and re-broadcast by the TransactionController.
* It is used internally within the TransactionController to try and update
* pending transactions on each new block (from blockTracker). It's also
* subscribed to in metamask-controller to display a browser notification on
* confirmed or failed transactions.
* @emits txMeta.id:finished - When a transaction moves to a finished state
* @fires txMeta.id:finished - When a transaction moves to a finished state
* this event is emitted, which is used in the TransactionController to pass
* along details of the transaction to the dapp that suggested them. This
* pattern is replicated across all of the message managers and can likely
* be supplemented or replaced by the ApprovalController.
* @emits updateBadge - When the number of transactions changes in state,
* @fires updateBadge - When the number of transactions changes in state,
* the badge in the browser extension bar should be updated to reflect the
* number of pending transactions. This particular emit doesn't appear to
* bubble up anywhere that is actually used. TransactionController emits

View File

@ -15,6 +15,7 @@ export default class ComposableObservableStore extends ObservableStore {
* store, and the value is either an ObserableStore, or a controller that
* extends one of the two base controllers in the `@metamask/controllers`
* package.
*
* @type {Record<string, Object>}
*/
config = {};

View File

@ -44,7 +44,6 @@ import { bnToHex } from './util';
* @property {BlockTracker} _blockTracker A BlockTracker instance. Needed to ensure that accounts and their info updates
* when a new block is created.
* @property {Object} _currentBlockNumber Reference to a property on the _blockTracker: the number (i.e. an id) of the the current block
*
*/
export default class AccountTracker {
/**
@ -96,9 +95,8 @@ export default class AccountTracker {
* Once this AccountTracker's accounts are up to date with those referenced by the passed addresses, each
* of these accounts are given an updated balance via EthQuery.
*
* @param {Array} address - The array of hex addresses for accounts with which this AccountTracker's accounts should be
* @param {Array} addresses - The array of hex addresses for accounts with which this AccountTracker's accounts should be
* in sync
*
*/
syncWithAddresses(addresses) {
const { accounts } = this.store.getState();
@ -127,7 +125,6 @@ export default class AccountTracker {
* given a balance as long this._currentBlockNumber is defined.
*
* @param {Array} addresses - An array of hex addresses of new accounts to track
*
*/
addAccounts(addresses) {
const { accounts } = this.store.getState();
@ -147,8 +144,7 @@ export default class AccountTracker {
/**
* Removes accounts from being tracked
*
* @param {Array} an - array of hex addresses to stop tracking
*
* @param {Array} addresses - An array of hex addresses to stop tracking.
*/
removeAccount(addresses) {
const { accounts } = this.store.getState();
@ -175,7 +171,6 @@ export default class AccountTracker {
* @private
* @param {number} blockNumber - the block number to update to.
* @fires 'block' The updated state, if all account updates are successful
*
*/
async _updateForBlock(blockNumber) {
this._currentBlockNumber = blockNumber;
@ -200,7 +195,6 @@ export default class AccountTracker {
* for all other networks, calls this._updateAccount for each account in this.store
*
* @returns {Promise} after all account balances updated
*
*/
async _updateAccounts() {
const { accounts } = this.store.getState();
@ -247,7 +241,6 @@ export default class AccountTracker {
* @private
* @param {string} address - A hex address of a the account to be updated
* @returns {Promise} after the account balance is updated
*
*/
async _updateAccount(address) {
// query balance
@ -265,6 +258,7 @@ export default class AccountTracker {
/**
* Updates current address balances from balanceChecker deployed contract instance
*
* @param {*} addresses
* @param {*} deployedContractAddress
*/

View File

@ -17,7 +17,8 @@ const fetchWithTimeout = getFetchWithTimeout(SECOND * 30);
/**
* Create a Wyre purchase URL.
* @param {String} address Ethereum destination address
*
* @param {string} address - Ethereum destination address
* @returns String
*/
const createWyrePurchaseUrl = async (address) => {
@ -45,7 +46,8 @@ const createWyrePurchaseUrl = async (address) => {
/**
* Create a Transak Checkout URL.
* API docs here: https://www.notion.so/Query-Parameters-9ec523df3b874ec58cef4fa3a906f238
* @param {String} address Ethereum destination address
*
* @param {string} address - Ethereum destination address
* @returns String
*/
const createTransakUrl = (address) => {
@ -64,9 +66,9 @@ const createTransakUrl = (address) => {
* @param {Object} opts - Options required to determine the correct url
* @param {string} opts.chainId - The chainId for which to return a url
* @param {string} opts.address - The address the bought ETH should be sent to. Only relevant if chainId === '0x1'.
* @param opts.service
* @returns {string|undefined} The url at which the user can access ETH, while in the given chain. If the passed
* chainId does not match any of the specified cases, or if no chainId is given, returns undefined.
*
*/
export default async function getBuyEthUrl({ chainId, address, service }) {
// default service by network if not specified

View File

@ -1,5 +1,6 @@
/**
* Returns error without stack trace for better UI display
*
* @param {Error} err - error
* @returns {Error} Error with clean stack trace.
*/

View File

@ -2,6 +2,7 @@ import log from 'loglevel';
/**
* Returns a middleware that logs RPC activity
*
* @param {{ origin: string }} opts - The middleware options
* @returns {Function}
*/

View File

@ -3,6 +3,7 @@ import extension from 'extensionizer';
/**
* Returns a middleware that intercepts `wallet_registerOnboarding` messages
*
* @param {{ location: string, registerOnboarding: Function }} opts - The middleware options
* @returns {(req: any, res: any, next: Function, end: Function) => void}
*/

View File

@ -1,5 +1,6 @@
/**
* Returns a middleware that appends the DApp origin to request
*
* @param {{ origin: string }} opts - The middleware options
* @returns {Function}
*/

View File

@ -1,5 +1,6 @@
/**
* Returns a middleware that appends the DApp TabId to the request
*
* @param {{ tabId: number }} opts - The middleware options
* @returns {Function}
*/

View File

@ -24,19 +24,14 @@ const hexRe = /^[0-9A-Fa-f]+$/gu;
* @property {string} status Indicates whether the decryption request is 'unapproved', 'approved', 'decrypted' or 'rejected'
* @property {string} type The json-prc decryption method for which a decryption request has been made. A 'Message' will
* always have a 'eth_decrypt' type.
*
*/
export default class DecryptMessageManager extends EventEmitter {
/**
* Controller in charge of managing - storing, adding, removing, updating - DecryptMessage.
*
* @typedef {Object} DecryptMessageManager
* @property {Object} memStore The observable store where DecryptMessage are saved.
* @property {Object} memStore.unapprovedDecryptMsgs A collection of all DecryptMessages in the 'unapproved' state
* @property {number} memStore.unapprovedDecryptMsgCount The count of all DecryptMessages in this.memStore.unapprovedDecryptMsgs
* @property {Array} messages Holds all messages that have been created by this DecryptMessageManager
*
* @param {object} opts - Controller options
* @param {Function} opts.metricEvent - A function for emitting a metric event.
*/
constructor(opts) {
super();
@ -52,7 +47,6 @@ export default class DecryptMessageManager extends EventEmitter {
* A getter for the number of 'unapproved' DecryptMessages in this.messages
*
* @returns {number} The number of 'unapproved' DecryptMessages in this.messages
*
*/
get unapprovedDecryptMsgCount() {
return Object.keys(this.getUnapprovedMsgs()).length;
@ -63,7 +57,6 @@ export default class DecryptMessageManager extends EventEmitter {
*
* @returns {Object} An index of DecryptMessage ids to DecryptMessages, for all 'unapproved' DecryptMessages in
* this.messages
*
*/
getUnapprovedMsgs() {
return this.messages
@ -82,7 +75,6 @@ export default class DecryptMessageManager extends EventEmitter {
* @param {Object} msgParams - The params for the eth_decrypt call to be made after the message is approved.
* @param {Object} [req] - The original request object possibly containing the origin
* @returns {Promise<Buffer>} The raw decrypted message contents
*
*/
addUnapprovedMessageAsync(msgParams, req) {
return new Promise((resolve, reject) => {
@ -127,7 +119,6 @@ export default class DecryptMessageManager extends EventEmitter {
* @param {Object} msgParams - The params for the eth_decryptMsg call to be made after the message is approved.
* @param {Object} [req] - The original request object possibly containing the origin
* @returns {number} The id of the newly created DecryptMessage.
*
*/
addUnapprovedMessage(msgParams, req) {
log.debug(
@ -161,8 +152,7 @@ export default class DecryptMessageManager extends EventEmitter {
* Adds a passed DecryptMessage to this.messages, and calls this._saveMsgList() to save the unapproved DecryptMessages from that
* list to this.memStore.
*
* @param {Message} msg The DecryptMessage to add to this.messages
*
* @param {Message} msg - The DecryptMessage to add to this.messages
*/
addMsg(msg) {
this.messages.push(msg);
@ -172,10 +162,9 @@ export default class DecryptMessageManager extends EventEmitter {
/**
* Returns a specified DecryptMessage.
*
* @param {number} msgId The id of the DecryptMessage to get
* @param {number} msgId - The id of the DecryptMessage to get
* @returns {DecryptMessage|undefined} The DecryptMessage with the id that matches the passed msgId, or undefined
* if no DecryptMessage has that id.
*
*/
getMsg(msgId) {
return this.messages.find((msg) => msg.id === msgId);
@ -185,10 +174,9 @@ export default class DecryptMessageManager extends EventEmitter {
* Approves a DecryptMessage. Sets the message status via a call to this.setMsgStatusApproved, and returns a promise
* with the message params modified for proper decryption.
*
* @param {Object} msgParams The msgParams to be used when eth_decryptMsg is called, plus data added by MetaMask.
* @param {Object} msgParams.metamaskId Added to msgParams for tracking and identification within MetaMask.
* @param {Object} msgParams - The msgParams to be used when eth_decryptMsg is called, plus data added by MetaMask.
* @param {Object} msgParams.metamaskId - Added to msgParams for tracking and identification within MetaMask.
* @returns {Promise<object>} Promises the msgParams object with metamaskId removed.
*
*/
approveMessage(msgParams) {
this.setMsgStatusApproved(msgParams.metamaskId);
@ -198,8 +186,7 @@ export default class DecryptMessageManager extends EventEmitter {
/**
* Sets a DecryptMessage status to 'approved' via a call to this._setMsgStatus.
*
* @param {number} msgId The id of the DecryptMessage to approve.
*
* @param {number} msgId - The id of the DecryptMessage to approve.
*/
setMsgStatusApproved(msgId) {
this._setMsgStatus(msgId, 'approved');
@ -209,9 +196,8 @@ export default class DecryptMessageManager extends EventEmitter {
* Sets a DecryptMessage status to 'decrypted' via a call to this._setMsgStatus and updates that DecryptMessage in
* this.messages by adding the raw decryption data of the decryption request to the DecryptMessage
*
* @param {number} msgId The id of the DecryptMessage to decrypt.
* @param {buffer} rawData The raw data of the message request
*
* @param {number} msgId - The id of the DecryptMessage to decrypt.
* @param {buffer} rawData - The raw data of the message request
*/
setMsgStatusDecrypted(msgId, rawData) {
const msg = this.getMsg(msgId);
@ -223,9 +209,8 @@ export default class DecryptMessageManager extends EventEmitter {
/**
* Removes the metamaskId property from passed msgParams and returns a promise which resolves the updated msgParams
*
* @param {Object} msgParams The msgParams to modify
* @param {Object} msgParams - The msgParams to modify
* @returns {Promise<object>} Promises the msgParams with the metamaskId property removed
*
*/
prepMsgForDecryption(msgParams) {
delete msgParams.metamaskId;
@ -235,8 +220,8 @@ export default class DecryptMessageManager extends EventEmitter {
/**
* Sets a DecryptMessage status to 'rejected' via a call to this._setMsgStatus.
*
* @param {number} msgId The id of the DecryptMessage to reject.
*
* @param {number} msgId - The id of the DecryptMessage to reject.
* @param reason
*/
rejectMsg(msgId, reason = undefined) {
if (reason) {
@ -254,8 +239,8 @@ export default class DecryptMessageManager extends EventEmitter {
/**
* Sets a TypedMessage status to 'errored' via a call to this._setMsgStatus.
*
* @param {number} msgId The id of the TypedMessage to error
*
* @param {number} msgId - The id of the TypedMessage to error
* @param error
*/
errorMessage(msgId, error) {
const msg = this.getMsg(msgId);
@ -276,14 +261,13 @@ export default class DecryptMessageManager extends EventEmitter {
* Updates the status of a DecryptMessage in this.messages via a call to this._updateMsg
*
* @private
* @param {number} msgId The id of the DecryptMessage to update.
* @param {string} status The new status of the DecryptMessage.
* @param {number} msgId - The id of the DecryptMessage to update.
* @param {string} status - The new status of the DecryptMessage.
* @throws A 'DecryptMessageManager - DecryptMessage not found for id: "${msgId}".' if there is no DecryptMessage
* in this.messages with an id equal to the passed msgId
* @fires An event with a name equal to `${msgId}:${status}`. The DecryptMessage is also fired.
* @fires If status is 'rejected' or 'decrypted', an event with a name equal to `${msgId}:finished` is fired along
* with the DecryptMessage
*
*/
_setMsgStatus(msgId, status) {
const msg = this.getMsg(msgId);
@ -311,7 +295,6 @@ export default class DecryptMessageManager extends EventEmitter {
* @private
* @param {DecryptMessage} msg - A DecryptMessage that will replace an existing DecryptMessage (with the same
* id) in this.messages
*
*/
_updateMsg(msg) {
const index = this.messages.findIndex((message) => message.id === msg.id);
@ -326,7 +309,6 @@ export default class DecryptMessageManager extends EventEmitter {
*
* @private
* @fires 'updateBadge'
*
*/
_saveMsgList() {
const unapprovedDecryptMsgs = this.getUnapprovedMsgs();
@ -341,9 +323,8 @@ export default class DecryptMessageManager extends EventEmitter {
/**
* A helper function that converts raw buffer data to a hex, or just returns the data if it is already formatted as a hex.
*
* @param {any} data The buffer data to convert to a hex
* @param {any} data - The buffer data to convert to a hex
* @returns {string} A hex string conversion of the buffer data
*
*/
normalizeMsgData(data) {
try {

View File

@ -20,19 +20,14 @@ import createId from '../../../shared/modules/random-id';
* @property {string} status Indicates whether the request is 'unapproved', 'approved', 'received' or 'rejected'
* @property {string} type The json-prc method for which a request has been made. A 'Message' will
* always have a 'eth_getEncryptionPublicKey' type.
*
*/
export default class EncryptionPublicKeyManager extends EventEmitter {
/**
* Controller in charge of managing - storing, adding, removing, updating - EncryptionPublicKey.
*
* @typedef {Object} EncryptionPublicKeyManager
* @property {Object} memStore The observable store where EncryptionPublicKey are saved with persistance.
* @property {Object} memStore.unapprovedEncryptionPublicKeyMsgs A collection of all EncryptionPublicKeys in the 'unapproved' state
* @property {number} memStore.unapprovedEncryptionPublicKeyMsgCount The count of all EncryptionPublicKeys in this.memStore.unapprobedMsgs
* @property {Array} messages Holds all messages that have been created by this EncryptionPublicKeyManager
*
* @param {object} opts - Controller options
* @param {Function} opts.metricEvent - A function for emitting a metric event.
*/
constructor(opts) {
super();
@ -48,7 +43,6 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* A getter for the number of 'unapproved' EncryptionPublicKeys in this.messages
*
* @returns {number} The number of 'unapproved' EncryptionPublicKeys in this.messages
*
*/
get unapprovedEncryptionPublicKeyMsgCount() {
return Object.keys(this.getUnapprovedMsgs()).length;
@ -59,7 +53,6 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
*
* @returns {Object} An index of EncryptionPublicKey ids to EncryptionPublicKeys, for all 'unapproved' EncryptionPublicKeys in
* this.messages
*
*/
getUnapprovedMsgs() {
return this.messages
@ -78,7 +71,6 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* @param {Object} address - The param for the eth_getEncryptionPublicKey call to be made after the message is approved.
* @param {Object} [req] - The original request object possibly containing the origin
* @returns {Promise<Buffer>} The raw public key contents
*
*/
addUnapprovedMessageAsync(address, req) {
return new Promise((resolve, reject) => {
@ -120,7 +112,6 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* @param {Object} address - The param for the eth_getEncryptionPublicKey call to be made after the message is approved.
* @param {Object} [req] - The original request object possibly containing the origin
* @returns {number} The id of the newly created EncryptionPublicKey.
*
*/
addUnapprovedMessage(address, req) {
log.debug(`EncryptionPublicKeyManager addUnapprovedMessage: address`);
@ -150,8 +141,7 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* Adds a passed EncryptionPublicKey to this.messages, and calls this._saveMsgList() to save the unapproved EncryptionPublicKeys from that
* list to this.memStore.
*
* @param {Message} msg The EncryptionPublicKey to add to this.messages
*
* @param {Message} msg - The EncryptionPublicKey to add to this.messages
*/
addMsg(msg) {
this.messages.push(msg);
@ -161,10 +151,9 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
/**
* Returns a specified EncryptionPublicKey.
*
* @param {number} msgId The id of the EncryptionPublicKey to get
* @param {number} msgId - The id of the EncryptionPublicKey to get
* @returns {EncryptionPublicKey|undefined} The EncryptionPublicKey with the id that matches the passed msgId, or undefined
* if no EncryptionPublicKey has that id.
*
*/
getMsg(msgId) {
return this.messages.find((msg) => msg.id === msgId);
@ -174,10 +163,9 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* Approves a EncryptionPublicKey. Sets the message status via a call to this.setMsgStatusApproved, and returns a promise
* with any the message params modified for proper providing.
*
* @param {Object} msgParams The msgParams to be used when eth_getEncryptionPublicKey is called, plus data added by MetaMask.
* @param {Object} msgParams.metamaskId Added to msgParams for tracking and identification within MetaMask.
* @param {Object} msgParams - The msgParams to be used when eth_getEncryptionPublicKey is called, plus data added by MetaMask.
* @param {Object} msgParams.metamaskId - Added to msgParams for tracking and identification within MetaMask.
* @returns {Promise<object>} Promises the msgParams object with metamaskId removed.
*
*/
approveMessage(msgParams) {
this.setMsgStatusApproved(msgParams.metamaskId);
@ -187,8 +175,7 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
/**
* Sets a EncryptionPublicKey status to 'approved' via a call to this._setMsgStatus.
*
* @param {number} msgId The id of the EncryptionPublicKey to approve.
*
* @param {number} msgId - The id of the EncryptionPublicKey to approve.
*/
setMsgStatusApproved(msgId) {
this._setMsgStatus(msgId, 'approved');
@ -198,9 +185,8 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* Sets a EncryptionPublicKey status to 'received' via a call to this._setMsgStatus and updates that EncryptionPublicKey in
* this.messages by adding the raw data of request to the EncryptionPublicKey
*
* @param {number} msgId The id of the EncryptionPublicKey.
* @param {buffer} rawData The raw data of the message request
*
* @param {number} msgId - The id of the EncryptionPublicKey.
* @param {buffer} rawData - The raw data of the message request
*/
setMsgStatusReceived(msgId, rawData) {
const msg = this.getMsg(msgId);
@ -212,9 +198,8 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
/**
* Removes the metamaskId property from passed msgParams and returns a promise which resolves the updated msgParams
*
* @param {Object} msgParams The msgParams to modify
* @param {Object} msgParams - The msgParams to modify
* @returns {Promise<object>} Promises the msgParams with the metamaskId property removed
*
*/
prepMsgForEncryptionPublicKey(msgParams) {
delete msgParams.metamaskId;
@ -224,8 +209,8 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
/**
* Sets a EncryptionPublicKey status to 'rejected' via a call to this._setMsgStatus.
*
* @param {number} msgId The id of the EncryptionPublicKey to reject.
*
* @param {number} msgId - The id of the EncryptionPublicKey to reject.
* @param reason
*/
rejectMsg(msgId, reason = undefined) {
if (reason) {
@ -243,8 +228,8 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
/**
* Sets a TypedMessage status to 'errored' via a call to this._setMsgStatus.
*
* @param {number} msgId The id of the TypedMessage to error
*
* @param {number} msgId - The id of the TypedMessage to error
* @param error
*/
errorMessage(msgId, error) {
const msg = this.getMsg(msgId);
@ -265,14 +250,13 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* Updates the status of a EncryptionPublicKey in this.messages via a call to this._updateMsg
*
* @private
* @param {number} msgId The id of the EncryptionPublicKey to update.
* @param {string} status The new status of the EncryptionPublicKey.
* @param {number} msgId - The id of the EncryptionPublicKey to update.
* @param {string} status - The new status of the EncryptionPublicKey.
* @throws A 'EncryptionPublicKeyManager - EncryptionPublicKey not found for id: "${msgId}".' if there is no EncryptionPublicKey
* in this.messages with an id equal to the passed msgId
* @fires An event with a name equal to `${msgId}:${status}`. The EncryptionPublicKey is also fired.
* @fires If status is 'rejected' or 'received', an event with a name equal to `${msgId}:finished` is fired along
* with the EncryptionPublicKey
*
*/
_setMsgStatus(msgId, status) {
const msg = this.getMsg(msgId);
@ -296,7 +280,6 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
* @private
* @param {EncryptionPublicKey} msg - A EncryptionPublicKey that will replace an existing EncryptionPublicKey (with the same
* id) in this.messages
*
*/
_updateMsg(msg) {
const index = this.messages.findIndex((message) => message.id === msg.id);
@ -311,7 +294,6 @@ export default class EncryptionPublicKeyManager extends EventEmitter {
*
* @private
* @fires 'updateBadge'
*
*/
_saveMsgList() {
const unapprovedEncryptionPublicKeyMsgs = this.getUnapprovedMsgs();

View File

@ -70,6 +70,7 @@ function hexValueIsEmpty(value) {
/**
* Returns the registry address for the given chain ID
*
* @param {number} chainId - the chain ID
* @returns {string|null} the registry address if known, null otherwise
*/

View File

@ -7,11 +7,9 @@ const errorLabelPrefix = 'Error: ';
*
* @param {string} errorMessage - The error message to parse
* @returns {string} Returns an error message, either the same as was passed, or the ending message portion of an isEthjsRpcError
*
* @example
* // returns 'Transaction Failed: replacement transaction underpriced'
* extractEthjsErrorMessage(`Error: [ethjs-rpc] rpc error with payload {"id":3947817945380,"jsonrpc":"2.0","params":["0xf8eb8208708477359400830398539406012c8cf97bead5deae237070f9587f8e7a266d80b8843d7d3f5a0000000000000000000000000000000000000000000000000000000000081d1a000000000000000000000000000000000000000000000000001ff973cafa800000000000000000000000000000000000000000000000000000038d7ea4c68000000000000000000000000000000000000000000000000000000000000003f48025a04c32a9b630e0d9e7ff361562d850c86b7a884908135956a7e4a336fa0300d19ca06830776423f25218e8d19b267161db526e66895567147015b1f3fc47aef9a3c7"],"method":"eth_sendRawTransaction"} Error: replacement transaction underpriced`)
*
*/
export default function extractEthjsErrorMessage(errorMessage) {
const isEthjsRpcError = errorMessage.includes(ethJsRpcSlug);

View File

@ -20,7 +20,6 @@ allLocales.forEach((locale) => {
* users preferred locales, 'en' is returned.
*
* @returns {Promise<string>} Promises a locale code, either one from the user's preferred list that we have a translation for, or 'en'
*
*/
export default async function getFirstPreferredLangCode() {
let userPreferredLocaleCodes;

View File

@ -19,7 +19,6 @@ import { cloneDeep } from 'lodash';
* @param {Object} obj - The object for which a 'structure' will be returned. Usually a plain object and not a class.
* @returns {Object} The "mapped" version of a deep clone of the passed object, with each non-object property value
* replaced with the javascript type of that value.
*
*/
export default function getObjStructure(obj) {
const structure = cloneDeep(obj);

View File

@ -6,9 +6,6 @@ import { checkForError } from './util';
* A wrapper around the extension's storage local API
*/
export default class ExtensionStore {
/**
* @constructor
*/
constructor() {
this.isSupported = Boolean(extension.storage.local);
if (!this.isSupported) {
@ -18,6 +15,7 @@ export default class ExtensionStore {
/**
* Returns all of the keys currently saved
*
* @returns {Promise<*>}
*/
async get() {
@ -35,6 +33,7 @@ export default class ExtensionStore {
/**
* Sets the key in local state
*
* @param {Object} state - The state to set
* @returns {Promise<void>}
*/
@ -44,6 +43,7 @@ export default class ExtensionStore {
/**
* Returns all of the keys currently saved
*
* @private
* @returns {Object} the key-value map from local storage
*/
@ -63,6 +63,7 @@ export default class ExtensionStore {
/**
* Sets the key in local state
*
* @param {Object} obj - The key to set
* @returns {Promise<void>}
* @private
@ -84,6 +85,7 @@ export default class ExtensionStore {
/**
* Returns whether or not the given object contains no keys
*
* @param {Object} obj - The object to check
* @returns {boolean}
*/

View File

@ -11,7 +11,6 @@ import createId from '../../../shared/modules/random-id';
* an eth_sign call is requested.
*
* @see {@link https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign}
*
* @typedef {Object} Message
* @property {number} id An id to track and identify the message object
* @property {Object} msgParams The parameters to pass to the eth_sign method once the signature request is approved.
@ -21,19 +20,14 @@ import createId from '../../../shared/modules/random-id';
* @property {string} status Indicates whether the signature request is 'unapproved', 'approved', 'signed' or 'rejected'
* @property {string} type The json-prc signing method for which a signature request has been made. A 'Message' with
* always have a 'eth_sign' type.
*
*/
export default class MessageManager extends EventEmitter {
/**
* Controller in charge of managing - storing, adding, removing, updating - Messages.
*
* @typedef {Object} MessageManager
* @property {Object} memStore The observable store where Messages are saved.
* @property {Object} memStore.unapprovedMsgs A collection of all Messages in the 'unapproved' state
* @property {number} memStore.unapprovedMsgCount The count of all Messages in this.memStore.unapprovedMsgs
* @property {Array} messages Holds all messages that have been created by this MessageManager
*
* @param {object} opts - Controller options
* @param {Function} opts.metricsEvent - A function for emitting a metric event.
*/
constructor({ metricsEvent }) {
super();
@ -49,7 +43,6 @@ export default class MessageManager extends EventEmitter {
* A getter for the number of 'unapproved' Messages in this.messages
*
* @returns {number} The number of 'unapproved' Messages in this.messages
*
*/
get unapprovedMsgCount() {
return Object.keys(this.getUnapprovedMsgs()).length;
@ -59,7 +52,6 @@ export default class MessageManager extends EventEmitter {
* A getter for the 'unapproved' Messages in this.messages
*
* @returns {Object} An index of Message ids to Messages, for all 'unapproved' Messages in this.messages
*
*/
getUnapprovedMsgs() {
return this.messages
@ -77,7 +69,6 @@ export default class MessageManager extends EventEmitter {
* @param {Object} msgParams - The params for the eth_sign call to be made after the message is approved.
* @param {Object} [req] - The original request object possibly containing the origin
* @returns {promise} after signature has been
*
*/
async addUnapprovedMessageAsync(msgParams, req) {
const msgId = this.addUnapprovedMessage(msgParams, req);
@ -117,7 +108,6 @@ export default class MessageManager extends EventEmitter {
* @param {Object} msgParams - The params for the eth_sign call to be made after the message is approved.
* @param {Object} [req] - The original request object where the origin may be specified
* @returns {number} The id of the newly created message.
*
*/
addUnapprovedMessage(msgParams, req) {
// add origin from request
@ -147,7 +137,6 @@ export default class MessageManager extends EventEmitter {
* list to this.memStore.
*
* @param {Message} msg - The Message to add to this.messages
*
*/
addMsg(msg) {
this.messages.push(msg);
@ -159,7 +148,6 @@ export default class MessageManager extends EventEmitter {
*
* @param {number} msgId - The id of the Message to get
* @returns {Message|undefined} The Message with the id that matches the passed msgId, or undefined if no Message has that id.
*
*/
getMsg(msgId) {
return this.messages.find((msg) => msg.id === msgId);
@ -170,9 +158,8 @@ export default class MessageManager extends EventEmitter {
* any the message params modified for proper signing.
*
* @param {Object} msgParams - The msgParams to be used when eth_sign is called, plus data added by MetaMask.
* @param {Object} msgParams.metamaskId Added to msgParams for tracking and identification within MetaMask.
* @param {Object} msgParams.metamaskId - Added to msgParams for tracking and identification within MetaMask.
* @returns {Promise<object>} Promises the msgParams object with metamaskId removed.
*
*/
approveMessage(msgParams) {
this.setMsgStatusApproved(msgParams.metamaskId);
@ -183,7 +170,6 @@ export default class MessageManager extends EventEmitter {
* Sets a Message status to 'approved' via a call to this._setMsgStatus.
*
* @param {number} msgId - The id of the Message to approve.
*
*/
setMsgStatusApproved(msgId) {
this._setMsgStatus(msgId, 'approved');
@ -195,7 +181,6 @@ export default class MessageManager extends EventEmitter {
*
* @param {number} msgId - The id of the Message to sign.
* @param {buffer} rawSig - The raw data of the signature request
*
*/
setMsgStatusSigned(msgId, rawSig) {
const msg = this.getMsg(msgId);
@ -209,7 +194,6 @@ export default class MessageManager extends EventEmitter {
*
* @param {Object} msgParams - The msgParams to modify
* @returns {Promise<object>} Promises the msgParams with the metamaskId property removed
*
*/
prepMsgForSigning(msgParams) {
delete msgParams.metamaskId;
@ -220,7 +204,7 @@ export default class MessageManager extends EventEmitter {
* Sets a Message status to 'rejected' via a call to this._setMsgStatus.
*
* @param {number} msgId - The id of the Message to reject.
*
* @param reason
*/
rejectMsg(msgId, reason = undefined) {
if (reason) {
@ -241,7 +225,7 @@ export default class MessageManager extends EventEmitter {
* Sets a Message status to 'errored' via a call to this._setMsgStatus.
*
* @param {number} msgId - The id of the Message to error
*
* @param error
*/
errorMessage(msgId, error) {
const msg = this.getMsg(msgId);
@ -268,7 +252,6 @@ export default class MessageManager extends EventEmitter {
* id equal to the passed msgId
* @fires An event with a name equal to `${msgId}:${status}`. The Message is also fired.
* @fires If status is 'rejected' or 'signed', an event with a name equal to `${msgId}:finished` is fired along with the message
*
*/
_setMsgStatus(msgId, status) {
const msg = this.getMsg(msgId);
@ -288,8 +271,7 @@ export default class MessageManager extends EventEmitter {
* storage via this._saveMsgList
*
* @private
* @param {msg} Message - A Message that will replace an existing Message (with the same id) in this.messages
*
* @param {Message} msg - A Message that will replace an existing Message (with the same id) in this.messages
*/
_updateMsg(msg) {
const index = this.messages.findIndex((message) => message.id === msg.id);
@ -304,7 +286,6 @@ export default class MessageManager extends EventEmitter {
*
* @private
* @fires 'updateBadge'
*
*/
_saveMsgList() {
const unapprovedMsgs = this.getUnapprovedMsgs();
@ -319,7 +300,6 @@ export default class MessageManager extends EventEmitter {
*
* @param {any} data - The buffer data to convert to a hex
* @returns {string} A hex string conversion of the buffer data
*
*/
export function normalizeMsgData(data) {
if (data.slice(0, 2) === '0x') {

View File

@ -14,7 +14,6 @@ import EventEmitter from 'events';
export default class Migrator extends EventEmitter {
/**
* @constructor
* @param {MigratorOptions} opts
*/
constructor(opts = {}) {
@ -71,6 +70,7 @@ export default class Migrator extends EventEmitter {
*
* A migration is considered "pending" if it has a higher
* version number than the current version.
*
* @param {Migration} migration
* @returns {boolean}
*/
@ -81,6 +81,7 @@ export default class Migrator extends EventEmitter {
/**
* Returns the initial state for the migrator
*
* @param {Object} [data] - The data for the initial state
* @returns {{meta: {version: number}, data: any}}
*/

View File

@ -41,6 +41,7 @@ export default class ReadOnlyNetworkStore {
/**
* Returns state
*
* @returns {Promise<object>}
*/
async get() {
@ -52,6 +53,7 @@ export default class ReadOnlyNetworkStore {
/**
* Set state
*
* @param {Object} state - The state to set
* @returns {Promise<void>}
*/

View File

@ -8,14 +8,10 @@ export const NOTIFICATION_MANAGER_EVENTS = {
POPUP_CLOSED: 'onPopupClosed',
};
/**
* A collection of methods for controlling the showing and hiding of the notification popup.
*/
export default class NotificationManager extends EventEmitter {
/**
* A collection of methods for controlling the showing and hiding of the notification popup.
*
* @typedef {Object} NotificationManager
*
*/
constructor() {
super();
this.platform = new ExtensionPlatform();
@ -94,8 +90,6 @@ export default class NotificationManager extends EventEmitter {
* type 'popup')
*
* @private
* @param {Function} cb - A node style callback that to which the found notification window will be passed.
*
*/
async _getPopup() {
const windows = await this.platform.getAllWindows();
@ -107,7 +101,6 @@ export default class NotificationManager extends EventEmitter {
*
* @private
* @param {Array} windows - An array of objects containing data about the open MetaMask extension windows.
*
*/
_getPopupIn(windows) {
return windows

View File

@ -15,7 +15,6 @@ const hexRe = /^[0-9A-Fa-f]+$/gu;
* signature for an personal_sign call is requested.
*
* @see {@link https://web3js.readthedocs.io/en/1.0/web3-eth-personal.html#sign}
*
* @typedef {Object} PersonalMessage
* @property {number} id An id to track and identify the message object
* @property {Object} msgParams The parameters to pass to the personal_sign method once the signature request is
@ -26,19 +25,14 @@ const hexRe = /^[0-9A-Fa-f]+$/gu;
* @property {string} status Indicates whether the signature request is 'unapproved', 'approved', 'signed' or 'rejected'
* @property {string} type The json-prc signing method for which a signature request has been made. A 'Message' will
* always have a 'personal_sign' type.
*
*/
export default class PersonalMessageManager extends EventEmitter {
/**
* Controller in charge of managing - storing, adding, removing, updating - PersonalMessage.
*
* @typedef {Object} PersonalMessageManager
* @property {Object} memStore The observable store where PersonalMessage are saved.
* @property {Object} memStore.unapprovedPersonalMsgs A collection of all PersonalMessages in the 'unapproved' state
* @property {number} memStore.unapprovedPersonalMsgCount The count of all PersonalMessages in this.memStore.unapprobedMsgs
* @property {Array} messages Holds all messages that have been created by this PersonalMessageManager
*
* @param options
* @param options.metricsEvent
*/
constructor({ metricsEvent }) {
super();
@ -54,7 +48,6 @@ export default class PersonalMessageManager extends EventEmitter {
* A getter for the number of 'unapproved' PersonalMessages in this.messages
*
* @returns {number} The number of 'unapproved' PersonalMessages in this.messages
*
*/
get unapprovedPersonalMsgCount() {
return Object.keys(this.getUnapprovedMsgs()).length;
@ -65,7 +58,6 @@ export default class PersonalMessageManager extends EventEmitter {
*
* @returns {Object} An index of PersonalMessage ids to PersonalMessages, for all 'unapproved' PersonalMessages in
* this.messages
*
*/
getUnapprovedMsgs() {
return this.messages
@ -84,7 +76,6 @@ export default class PersonalMessageManager extends EventEmitter {
* @param {Object} msgParams - The params for the eth_sign call to be made after the message is approved.
* @param {Object} [req] - The original request object possibly containing the origin
* @returns {promise} When the message has been signed or rejected
*
*/
addUnapprovedMessageAsync(msgParams, req) {
return new Promise((resolve, reject) => {
@ -131,7 +122,6 @@ export default class PersonalMessageManager extends EventEmitter {
* @param {Object} msgParams - The params for the eth_sign call to be made after the message is approved.
* @param {Object} [req] - The original request object possibly containing the origin
* @returns {number} The id of the newly created PersonalMessage.
*
*/
addUnapprovedMessage(msgParams, req) {
log.debug(
@ -166,7 +156,6 @@ export default class PersonalMessageManager extends EventEmitter {
* list to this.memStore.
*
* @param {Message} msg - The PersonalMessage to add to this.messages
*
*/
addMsg(msg) {
this.messages.push(msg);
@ -179,7 +168,6 @@ export default class PersonalMessageManager extends EventEmitter {
* @param {number} msgId - The id of the PersonalMessage to get
* @returns {PersonalMessage|undefined} The PersonalMessage with the id that matches the passed msgId, or undefined
* if no PersonalMessage has that id.
*
*/
getMsg(msgId) {
return this.messages.find((msg) => msg.id === msgId);
@ -190,9 +178,8 @@ export default class PersonalMessageManager extends EventEmitter {
* with any the message params modified for proper signing.
*
* @param {Object} msgParams - The msgParams to be used when eth_sign is called, plus data added by MetaMask.
* @param {Object} msgParams.metamaskId Added to msgParams for tracking and identification within MetaMask.
* @param {Object} msgParams.metamaskId - Added to msgParams for tracking and identification within MetaMask.
* @returns {Promise<object>} Promises the msgParams object with metamaskId removed.
*
*/
approveMessage(msgParams) {
this.setMsgStatusApproved(msgParams.metamaskId);
@ -203,7 +190,6 @@ export default class PersonalMessageManager extends EventEmitter {
* Sets a PersonalMessage status to 'approved' via a call to this._setMsgStatus.
*
* @param {number} msgId - The id of the PersonalMessage to approve.
*
*/
setMsgStatusApproved(msgId) {
this._setMsgStatus(msgId, 'approved');
@ -215,7 +201,6 @@ export default class PersonalMessageManager extends EventEmitter {
*
* @param {number} msgId - The id of the PersonalMessage to sign.
* @param {buffer} rawSig - The raw data of the signature request
*
*/
setMsgStatusSigned(msgId, rawSig) {
const msg = this.getMsg(msgId);
@ -229,7 +214,6 @@ export default class PersonalMessageManager extends EventEmitter {
*
* @param {Object} msgParams - The msgParams to modify
* @returns {Promise<object>} Promises the msgParams with the metamaskId property removed
*
*/
prepMsgForSigning(msgParams) {
delete msgParams.metamaskId;
@ -240,7 +224,7 @@ export default class PersonalMessageManager extends EventEmitter {
* Sets a PersonalMessage status to 'rejected' via a call to this._setMsgStatus.
*
* @param {number} msgId - The id of the PersonalMessage to reject.
*
* @param reason
*/
rejectMsg(msgId, reason = undefined) {
if (reason) {
@ -261,7 +245,7 @@ export default class PersonalMessageManager extends EventEmitter {
* Sets a Message status to 'errored' via a call to this._setMsgStatus.
*
* @param {number} msgId - The id of the Message to error
*
* @param error
*/
errorMessage(msgId, error) {
const msg = this.getMsg(msgId);
@ -289,7 +273,6 @@ export default class PersonalMessageManager extends EventEmitter {
* @fires An event with a name equal to `${msgId}:${status}`. The PersonalMessage is also fired.
* @fires If status is 'rejected' or 'signed', an event with a name equal to `${msgId}:finished` is fired along
* with the PersonalMessage
*
*/
_setMsgStatus(msgId, status) {
const msg = this.getMsg(msgId);
@ -311,9 +294,8 @@ export default class PersonalMessageManager extends EventEmitter {
* unapprovedPersonalMsgs index to storage via this._saveMsgList
*
* @private
* @param {msg} PersonalMessage - A PersonalMessage that will replace an existing PersonalMessage (with the same
* @param {PersonalMessage} msg - A PersonalMessage that will replace an existing PersonalMessage (with the same
* id) in this.messages
*
*/
_updateMsg(msg) {
const index = this.messages.findIndex((message) => message.id === msg.id);
@ -328,7 +310,6 @@ export default class PersonalMessageManager extends EventEmitter {
*
* @private
* @fires 'updateBadge'
*
*/
_saveMsgList() {
const unapprovedPersonalMsgs = this.getUnapprovedMsgs();
@ -346,7 +327,6 @@ export default class PersonalMessageManager extends EventEmitter {
*
* @param {any} data - The buffer data to convert to a hex
* @returns {string} A hex string conversion of the buffer data
*
*/
normalizeMsgData(data) {
try {

View File

@ -21,7 +21,7 @@ export default requestEthereumAccounts;
/**
*
* @param {import('json-rpc-engine').JsonRpcRequest<unknown>} req - The JSON-RPC request object.
* @param {import('json-rpc-engine').JsonRpcRequest<unknown>} _req - The JSON-RPC request object.
* @param {import('json-rpc-engine').JsonRpcResponse<true>} res - The JSON-RPC response object.
* @param {Function} _next - The json-rpc-engine 'next' callback.
* @param {Function} end - The json-rpc-engine 'end' callback.

View File

@ -13,7 +13,6 @@ const seedPhraseVerifier = {
* @param {Array} createdAccounts - The accounts to restore
* @param {string} seedWords - The seed words to verify
* @returns {Promise<void>} Promises undefined
*
*/
async verifyAccounts(createdAccounts, seedWords) {
if (!createdAccounts || createdAccounts.length < 1) {

View File

@ -29,8 +29,8 @@ const SEGMENT_FLUSH_INTERVAL = SECOND * 5;
* when building the application in test mode to catch event calls and prevent
* them from being sent to segment. It is also used in unit tests to mock and
* spy on the methods to ensure proper behavior
*
* @param {number} flushAt - number of events to queue before sending to segment
* @param {number} flushInterval - ms interval to flush queue and send to segment
* @returns {SegmentInterface}
*/
export const createSegmentMock = (flushAt = SEGMENT_FLUSH_AT) => {
@ -54,6 +54,9 @@ export const createSegmentMock = (flushAt = SEGMENT_FLUSH_AT) => {
/**
* Track an event and add it to the queue. If the queue size reaches the
* flushAt threshold, flush the queue.
*
* @param payload
* @param callback
*/
track(payload, callback = () => undefined) {
segmentMock.queue.push([payload, callback]);

View File

@ -3,6 +3,7 @@ import pump from 'pump';
/**
* Sets up stream multiplexing for the given stream
*
* @param {any} connectionStream - the stream to mux
* @returns {stream.Stream} the multiplexed stream
*/

View File

@ -25,12 +25,15 @@ import { isValidHexAddress } from '../../../shared/modules/hexstring-utils';
* @property {string} status Indicates whether the signature request is 'unapproved', 'approved', 'signed', 'rejected', or 'errored'
* @property {string} type The json-prc signing method for which a signature request has been made. A 'Message' will
* always have a 'eth_signTypedData' type.
*
*/
export default class TypedMessageManager extends EventEmitter {
/**
* Controller in charge of managing - storing, adding, removing, updating - TypedMessage.
*
* @param options
* @param options.getCurrentChainId
* @param options.metricEvents
*/
constructor({ getCurrentChainId, metricEvents }) {
super();
@ -47,7 +50,6 @@ export default class TypedMessageManager extends EventEmitter {
* A getter for the number of 'unapproved' TypedMessages in this.messages
*
* @returns {number} The number of 'unapproved' TypedMessages in this.messages
*
*/
get unapprovedTypedMessagesCount() {
return Object.keys(this.getUnapprovedMsgs()).length;
@ -58,7 +60,6 @@ export default class TypedMessageManager extends EventEmitter {
*
* @returns {Object} An index of TypedMessage ids to TypedMessages, for all 'unapproved' TypedMessages in
* this.messages
*
*/
getUnapprovedMsgs() {
return this.messages
@ -76,8 +77,8 @@ export default class TypedMessageManager extends EventEmitter {
*
* @param {Object} msgParams - The params for the eth_sign call to be made after the message is approved.
* @param {Object} [req] - The original request object possibly containing the origin
* @param version
* @returns {promise} When the message has been signed or rejected
*
*/
addUnapprovedMessageAsync(msgParams, req, version) {
return new Promise((resolve, reject) => {
@ -116,8 +117,8 @@ export default class TypedMessageManager extends EventEmitter {
*
* @param {Object} msgParams - The params for the eth_sign call to be made after the message is approved.
* @param {Object} [req] - The original request object possibly containing the origin
* @param version
* @returns {number} The id of the newly created TypedMessage.
*
*/
addUnapprovedMessage(msgParams, req, version) {
msgParams.version = version;
@ -151,7 +152,6 @@ export default class TypedMessageManager extends EventEmitter {
* Helper method for this.addUnapprovedMessage. Validates that the passed params have the required properties.
*
* @param {Object} params - The params to validate
*
*/
validateParams(params) {
assert.ok(
@ -225,7 +225,6 @@ export default class TypedMessageManager extends EventEmitter {
* list to this.memStore.
*
* @param {Message} msg - The TypedMessage to add to this.messages
*
*/
addMsg(msg) {
this.messages.push(msg);
@ -238,7 +237,6 @@ export default class TypedMessageManager extends EventEmitter {
* @param {number} msgId - The id of the TypedMessage to get
* @returns {TypedMessage|undefined} The TypedMessage with the id that matches the passed msgId, or undefined
* if no TypedMessage has that id.
*
*/
getMsg(msgId) {
return this.messages.find((msg) => msg.id === msgId);
@ -249,9 +247,8 @@ export default class TypedMessageManager extends EventEmitter {
* with any the message params modified for proper signing.
*
* @param {Object} msgParams - The msgParams to be used when eth_sign is called, plus data added by MetaMask.
* @param {Object} msgParams.metamaskId Added to msgParams for tracking and identification within MetaMask.
* @param {Object} msgParams.metamaskId - Added to msgParams for tracking and identification within MetaMask.
* @returns {Promise<object>} Promises the msgParams object with metamaskId removed.
*
*/
approveMessage(msgParams) {
this.setMsgStatusApproved(msgParams.metamaskId);
@ -262,7 +259,6 @@ export default class TypedMessageManager extends EventEmitter {
* Sets a TypedMessage status to 'approved' via a call to this._setMsgStatus.
*
* @param {number} msgId - The id of the TypedMessage to approve.
*
*/
setMsgStatusApproved(msgId) {
this._setMsgStatus(msgId, 'approved');
@ -274,7 +270,6 @@ export default class TypedMessageManager extends EventEmitter {
*
* @param {number} msgId - The id of the TypedMessage to sign.
* @param {buffer} rawSig - The raw data of the signature request
*
*/
setMsgStatusSigned(msgId, rawSig) {
const msg = this.getMsg(msgId);
@ -288,7 +283,6 @@ export default class TypedMessageManager extends EventEmitter {
*
* @param {Object} msgParams - The msgParams to modify
* @returns {Promise<object>} Promises the msgParams with the metamaskId property removed
*
*/
prepMsgForSigning(msgParams) {
delete msgParams.metamaskId;
@ -300,7 +294,7 @@ export default class TypedMessageManager extends EventEmitter {
* Sets a TypedMessage status to 'rejected' via a call to this._setMsgStatus.
*
* @param {number} msgId - The id of the TypedMessage to reject.
*
* @param reason
*/
rejectMsg(msgId, reason = undefined) {
if (reason) {
@ -322,7 +316,7 @@ export default class TypedMessageManager extends EventEmitter {
* Sets a TypedMessage status to 'errored' via a call to this._setMsgStatus.
*
* @param {number} msgId - The id of the TypedMessage to error
*
* @param error
*/
errorMessage(msgId, error) {
const msg = this.getMsg(msgId);
@ -354,7 +348,6 @@ export default class TypedMessageManager extends EventEmitter {
* @fires An event with a name equal to `${msgId}:${status}`. The TypedMessage is also fired.
* @fires If status is 'rejected' or 'signed', an event with a name equal to `${msgId}:finished` is fired along
* with the TypedMessage
*
*/
_setMsgStatus(msgId, status) {
const msg = this.getMsg(msgId);
@ -376,9 +369,8 @@ export default class TypedMessageManager extends EventEmitter {
* unapprovedTypedMsgs index to storage via this._saveMsgList
*
* @private
* @param {msg} TypedMessage - A TypedMessage that will replace an existing TypedMessage (with the same
* @param {TypedMessage} msg - A TypedMessage that will replace an existing TypedMessage (with the same
* id) in this.messages
*
*/
_updateMsg(msg) {
const index = this.messages.findIndex((message) => message.id === msg.id);
@ -393,7 +385,6 @@ export default class TypedMessageManager extends EventEmitter {
*
* @private
* @fires 'updateBadge'
*
*/
_saveMsgList() {
const unapprovedTypedMessages = this.getUnapprovedMsgs();

View File

@ -54,7 +54,6 @@ const getEnvironmentType = (url = window.location.href) =>
* Returns the platform (browser) where the extension is running.
*
* @returns {string} the platform ENUM
*
*/
const getPlatform = () => {
const { navigator } = window;
@ -77,7 +76,6 @@ const getPlatform = () => {
*
* @param {string} inputHex - A number represented as a hex string
* @returns {Object} A BN object
*
*/
function hexToBn(inputHex) {
return new BN(stripHexPrefix(inputHex), 16);
@ -90,7 +88,6 @@ function hexToBn(inputHex) {
* @param {number|string} numerator - The numerator of the fraction multiplier
* @param {number|string} denominator - The denominator of the fraction multiplier
* @returns {BN} The product of the multiplication
*
*/
function BnMultiplyByFraction(targetBN, numerator, denominator) {
const numBN = new BN(numerator);
@ -101,6 +98,7 @@ function BnMultiplyByFraction(targetBN, numerator, denominator) {
/**
* Returns an Error if extension.runtime.lastError is present
* this is a workaround for the non-standard error object that's used
*
* @returns {Error|undefined}
*/
function checkForError() {
@ -142,8 +140,7 @@ const addHexPrefix = (str) => {
* Converts a BN object to a hex string with a '0x' prefix
*
* @param {BN} inputBn - The BN to convert to a hex string
* @returns {string} - A '0x' prefixed hex string
*
* @returns {string} A '0x' prefixed hex string
*/
function bnToHex(inputBn) {
return addHexPrefix(inputBn.toString(16));

View File

@ -116,7 +116,6 @@ export const METAMASK_CONTROLLER_EVENTS = {
export default class MetamaskController extends EventEmitter {
/**
* @constructor
* @param {Object} opts
*/
constructor(opts) {
@ -1440,6 +1439,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Create a new Vault and restore an existent keyring.
*
* @param {string} password
* @param {string} seed
*/
@ -1519,6 +1519,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Get an account balance from the AccountTracker or request it directly from the network.
*
* @param {string} address - The account address
* @param {EthQuery} ethQuery - The EthQuery instance to use when asking the network
*/
@ -1544,6 +1545,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Collects all the information that we want to share
* with the mobile client for syncing purposes
*
* @returns {Promise<Object>} Parts of the state that we want to syncx
*/
async fetchInfoToSync() {
@ -1641,7 +1643,7 @@ export default class MetamaskController extends EventEmitter {
};
}
/*
/**
* Submits the user's password and attempts to unlock the vault.
* Also synchronizes the preferencesController, to ensure its schema
* is up to date with known accounts once the vault is decrypted.
@ -1685,7 +1687,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Submits a user's password to check its validity.
*
* @param {string} password The user's password
* @param {string} password - The user's password
*/
async verifyPassword(password) {
await this.keyringController.verifyPassword(password);
@ -1767,6 +1769,9 @@ export default class MetamaskController extends EventEmitter {
/**
* Fetch account list from a trezor device.
*
* @param deviceName
* @param page
* @param hdPath
* @returns [] accounts
*/
async connectHardware(deviceName, page, hdPath) {
@ -1798,6 +1803,8 @@ export default class MetamaskController extends EventEmitter {
/**
* Check if the device is unlocked
*
* @param deviceName
* @param hdPath
* @returns {Promise<boolean>}
*/
async checkHardwareStatus(deviceName, hdPath) {
@ -1808,6 +1815,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Clear
*
* @param deviceName
* @returns {Promise<boolean>}
*/
async forgetDevice(deviceName) {
@ -1819,8 +1827,8 @@ export default class MetamaskController extends EventEmitter {
/**
* get hardware account label
*
* @return string label
* */
* @returns string label
*/
getAccountLabel(name, index, hdPathDescription) {
return `${name[0].toUpperCase()}${name.slice(1)} ${
@ -1831,6 +1839,10 @@ export default class MetamaskController extends EventEmitter {
/**
* Imports an account from a Trezor or Ledger device.
*
* @param index
* @param deviceName
* @param hdPath
* @param hdPathDescription
* @returns {} keyState
*/
async unlockHardwareWalletAccount(
@ -1993,7 +2005,6 @@ export default class MetamaskController extends EventEmitter {
* Removes an account from state / storage.
*
* @param {string[]} address - A hex address
*
*/
async removeAccount(address) {
// Remove all associated permissions
@ -2015,7 +2026,6 @@ export default class MetamaskController extends EventEmitter {
*
* @param {string} strategy - A unique identifier for an account import strategy.
* @param {any} args - The data required by that strategy to import an account.
* @param {Function} cb - A callback function called with a state update on success.
*/
async importAccountWithStrategy(strategy, args) {
const privateKey = await accountImporter.importAccount(strategy, args);
@ -2039,8 +2049,8 @@ export default class MetamaskController extends EventEmitter {
* this wrapper needs to exist so we can provide a reference to
* "newUnapprovedTransaction" before "txController" is instantiated
*
* @param {Object} msgParams - The params passed to eth_sign.
* @param {Object} req - (optional) the original request, containing the origin
* @param {Object} txParams - The transaction parameters.
* @param {Object} [req] - The original request, containing the origin.
*/
async newUnapprovedTransaction(txParams, req) {
return await this.txController.newUnapprovedTransaction(txParams, req);
@ -2055,7 +2065,7 @@ export default class MetamaskController extends EventEmitter {
* information.
*
* @param {Object} msgParams - The params passed to eth_sign.
* @param {Function} cb - The callback function called with the signature.
* @param {Object} [req] - The original request, containing the origin.
*/
async newUnsignedMessage(msgParams, req) {
const data = normalizeMsgData(msgParams.data);
@ -2121,8 +2131,7 @@ export default class MetamaskController extends EventEmitter {
* We currently define our eth_sign and personal_sign mostly for legacy Dapps.
*
* @param {Object} msgParams - The params of the message to sign & return to the Dapp.
* @param {Function} cb - The callback function called with the signature.
* Passed back to the requesting Dapp.
* @param {Object} [req] - The original request, containing the origin.
*/
async newUnsignedPersonalMessage(msgParams, req) {
const promise = this.personalMessageManager.addUnapprovedMessageAsync(
@ -2166,6 +2175,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Used to cancel a personal_sign type message.
*
* @param {string} msgId - The ID of the message to cancel.
*/
cancelPersonalMessage(msgId) {
@ -2254,6 +2264,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Used to cancel a eth_decrypt type message.
*
* @param {string} msgId - The ID of the message to cancel.
*/
cancelDecryptMessage(msgId) {
@ -2355,6 +2366,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Used to cancel a eth_getEncryptionPublicKey type message.
*
* @param {string} msgId - The ID of the message to cancel.
*/
cancelEncryptionPublicKey(msgId) {
@ -2369,7 +2381,8 @@ export default class MetamaskController extends EventEmitter {
* Called when a dapp uses the eth_signTypedData method, per EIP 712.
*
* @param {Object} msgParams - The params passed to eth_signTypedData.
* @param {Function} cb - The callback function, called with the signature.
* @param {Object} [req] - The original request, containing the origin.
* @param version
*/
newUnsignedTypedMessage(msgParams, req, version) {
const promise = this.typedMessageManager.addUnapprovedMessageAsync(
@ -2421,6 +2434,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Used to cancel a eth_signTypedData type message.
*
* @param {string} msgId - The ID of the message to cancel.
*/
cancelTypedMessage(msgId) {
@ -2443,12 +2457,14 @@ export default class MetamaskController extends EventEmitter {
/**
* Allows a user to attempt to cancel a previously submitted transaction
* by creating a new transaction.
*
* @param {number} originalTxId - the id of the txMeta that you want to
* attempt to cancel
* @param {import(
* './controllers/transactions'
* ).CustomGasSettings} [customGasSettings] - overrides to use for gas params
* instead of allowing this method to generate them
* @param newTxMetaProps
* @returns {Object} MetaMask state
*/
async createCancelTransaction(
@ -2468,12 +2484,14 @@ export default class MetamaskController extends EventEmitter {
/**
* Allows a user to attempt to speed up a previously submitted transaction
* by creating a new transaction.
*
* @param {number} originalTxId - the id of the txMeta that you want to
* attempt to speed up
* @param {import(
* './controllers/transactions'
* ).CustomGasSettings} [customGasSettings] - overrides to use for gas params
* instead of allowing this method to generate them
* @param newTxMetaProps
* @returns {Object} MetaMask state
*/
async createSpeedUpTransaction(
@ -2511,7 +2529,6 @@ export default class MetamaskController extends EventEmitter {
/**
* Allows a user to begin the seed phrase recovery process.
* @param {Function} cb - A callback function called when complete.
*/
markPasswordForgotten() {
this.preferencesController.setPasswordForgotten(true);
@ -2520,7 +2537,6 @@ export default class MetamaskController extends EventEmitter {
/**
* Allows a user to end the seed phrase recovery process.
* @param {Function} cb - A callback function called when complete.
*/
unMarkPasswordForgotten() {
this.preferencesController.setPasswordForgotten(false);
@ -2533,13 +2549,16 @@ export default class MetamaskController extends EventEmitter {
/**
* A runtime.MessageSender object, as provided by the browser:
*
* @see https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/MessageSender
* @typedef {Object} MessageSender
* @property {string} - The URL of the page or frame hosting the script that sent the message.
*/
/**
* Used to create a multiplexed stream for connecting to an untrusted context
* like a Dapp or other extension.
*
* @param {*} connectionStream - The Duplex stream to connect to.
* @param {MessageSender} sender - The sender of the messages on this stream
*/
@ -2598,6 +2617,7 @@ export default class MetamaskController extends EventEmitter {
/**
* A method for providing our API over a stream using JSON-RPC.
*
* @param {*} outStream - The stream to provide our API over.
*/
setupControllerConnection(outStream) {
@ -2633,6 +2653,7 @@ export default class MetamaskController extends EventEmitter {
/**
* A method for serving our ethereum provider over a given stream.
*
* @param {*} outStream - The stream to provide over.
* @param {MessageSender} sender - The sender of the messages on this stream
* @param {boolean} isInternal - True if this is a connection with an internal process
@ -2690,7 +2711,7 @@ export default class MetamaskController extends EventEmitter {
* @param {string} options.location - The full URL of the sender
* @param {string} options.subjectType - The type of the sender subject.
* @param {tabId} [options.tabId] - The tab ID of the sender - if the sender is within a tab
**/
*/
setupProviderEngine({ origin, location, subjectType, tabId }) {
// setup json rpc engine stack
const engine = new JsonRpcEngine();
@ -2951,6 +2972,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Handle a KeyringController update
*
* @param {Object} state - the KC state
* @returns {Promise<void>}
* @private
@ -3016,6 +3038,8 @@ export default class MetamaskController extends EventEmitter {
* - Ensure isClientOpenAndUnlocked is updated
* - Notifies all connections with the new provider network state
* - The external providers handle diffing the state
*
* @param newState
*/
_onStateUpdate(newState) {
this.isClientOpenAndUnlocked = newState.isUnlocked && this._isClientOpen;
@ -3029,6 +3053,7 @@ export default class MetamaskController extends EventEmitter {
/**
* A method for emitting the full MetaMask state to all registered listeners.
*
* @private
*/
privateSendUpdate() {
@ -3048,6 +3073,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Returns the nonce that will be associated with a transaction once approved
*
* @param {string} address - The hex string address for the transaction
* @returns {Promise<number>}
*/
@ -3064,6 +3090,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Returns the next nonce according to the nonce-tracker
*
* @param {string} address - The hex string address for the transaction
* @returns {Promise<number>}
*/
@ -3120,13 +3147,14 @@ export default class MetamaskController extends EventEmitter {
/**
* A method for selecting a custom URL for an ethereum RPC provider and updating it
*
* @param {string} rpcUrl - A URL for a valid Ethereum RPC API.
* @param {string} chainId - The chainId of the selected network.
* @param {string} ticker - The ticker symbol of the selected network.
* @param {string} [nickname] - Nickname of the selected network.
* @param {Object} [rpcPrefs] - RPC preferences.
* @param {string} [rpcPrefs.blockExplorerUrl] - URL of block explorer for the chain.
* @returns {Promise<String>} - The RPC Target URL confirmed.
* @returns {Promise<string>} The RPC Target URL confirmed.
*/
async updateAndSetCustomRpc(
rpcUrl,
@ -3154,11 +3182,13 @@ export default class MetamaskController extends EventEmitter {
/**
* A method for selecting a custom URL for an ethereum RPC provider.
*
* @param {string} rpcUrl - A URL for a valid Ethereum RPC API.
* @param {string} chainId - The chainId of the selected network.
* @param {string} ticker - The ticker symbol of the selected network.
* @param {string} nickname - Optional nickname of the selected network.
* @returns {Promise<String>} The RPC Target URL confirmed.
* @param rpcPrefs
* @returns {Promise<string>} The RPC Target URL confirmed.
*/
async setCustomRpc(
rpcUrl,
@ -3201,6 +3231,7 @@ export default class MetamaskController extends EventEmitter {
/**
* A method for deleting a selected custom URL.
*
* @param {string} rpcUrl - A RPC URL to delete.
*/
async delCustomRpc(rpcUrl) {
@ -3232,7 +3263,8 @@ export default class MetamaskController extends EventEmitter {
/**
* Sets the Ledger Live preference to use for Ledger hardware wallet support
* @param {bool} bool - the value representing if the users wants to use Ledger Live
*
* @param {string} transportType - The Ledger transport type.
*/
async setLedgerTransportPreference(transportType) {
const currentValue = this.preferencesController.getLedgerTransportPreference();
@ -3255,6 +3287,7 @@ export default class MetamaskController extends EventEmitter {
/**
* A method for initializing storage the first time.
*
* @param {Object} initState - The default state to initialize with.
* @private
*/
@ -3272,6 +3305,7 @@ export default class MetamaskController extends EventEmitter {
/* eslint-disable accessor-pairs */
/**
* A method for recording whether the MetaMask user interface is open or not.
*
* @param {boolean} open
*/
set isClientOpen(open) {
@ -3296,6 +3330,8 @@ export default class MetamaskController extends EventEmitter {
/**
* A method that is called by the background when a particular environment type is closed (fullscreen, popup, notification).
* Currently used to stop polling in the gasFeeController for only that environement type
*
* @param environmentType
*/
onEnvironmentTypeClosed(environmentType) {
const appStatePollingTokenType =
@ -3314,6 +3350,7 @@ export default class MetamaskController extends EventEmitter {
/**
* Adds a domain to the PhishingController safelist
*
* @param {string} hostname - the domain to safelist
*/
safelistPhishingDomain(hostname) {

View File

@ -138,7 +138,9 @@ function transformState(state = {}) {
/**
* Merges the two given keys for the given address book in place.
*
* @returns {void}
* @param addressBook
* @param networkKey
* @param chainIdKey
*/
function mergeAddressBookKeys(addressBook, networkKey, chainIdKey) {
const networkKeyEntries = addressBook[networkKey] || {};
@ -179,7 +181,8 @@ function mergeAddressBookKeys(addressBook, networkKey, chainIdKey) {
* Updates the chainId key values to the given chainId in place for all values
* of the given networkEntries object.
*
* @returns {void}
* @param networkEntries
* @param chainId
*/
function updateChainIds(networkEntries, chainId) {
Object.values(networkEntries).forEach((entry) => {
@ -193,6 +196,8 @@ function updateChainIds(networkEntries, chainId) {
* Merges the two given, non-empty arrays of token objects and returns a new
* array.
*
* @param localhostTokens
* @param rpcTokens
* @returns {Array<Object>}
*/
function mergeTokenArrays(localhostTokens, rpcTokens) {

View File

@ -41,6 +41,7 @@ require('eslint');
require('eslint-config-prettier');
require('eslint-import-resolver-node');
require('eslint-plugin-import');
require('eslint-plugin-jsdoc');
require('eslint-plugin-node');
require('eslint-plugin-prettier');
require('eslint-plugin-react');
@ -223,7 +224,7 @@ function parseArgv() {
/**
* Gets the files to be ignored by the current build, if any.
*
* @param {string} buildType - The type of the current build.
* @param {string} currentBuildType - The type of the current build.
* @returns {string[] | null} The array of files to be ignored by the current
* build, or `null` if no files are to be ignored.
*/

View File

@ -117,7 +117,7 @@ function getInfuraProjectId({ buildType, environment, testing }) {
*
* @param {object} options - The Segment write key options.
* @param {BuildType} options.buildType - The current build type.
* @param {keyof ENVIRONMENT} options.enviroment - The current build environment.
* @param {keyof ENVIRONMENT} options.environment - The current build environment.
* @returns {string} The Segment write key.
*/
function getSegmentWriteKey({ buildType, environment }) {

View File

@ -102,8 +102,13 @@ function createRemoveFencedCodeTransform(
// To apply our code fencing transform, we concatenate all buffers and convert
// them to a single string, then apply the actual transform function on that
// string.
/**
* @returns {Transform}
* Returns a transform stream that removes fenced code from JavaScript files. For non-JavaScript
* files, a pass-through stream is returned.
*
* @param filePath - The file path to transform.
* @returns {Transform} The transform stream.
*/
return function removeFencedCodeTransform(filePath) {
if (!['.js', '.cjs', '.mjs'].includes(path.extname(filePath))) {

View File

@ -19,7 +19,6 @@ const BuildType = {
* has a prerelease component, it is assumed to have the format "<build type>.<build version",
* where the build version is a positive integer.
*
* @param {string} currentVersion - The current version.
* @param {string[]} platforms - A list of browsers to generate versions for.
* @returns {Object} An object with the browser as the key and the browser-specific version object
* as the value. For example, the version `9.6.0-beta.1` would return the object

View File

@ -74,6 +74,9 @@ function urlForStoryFile(filename, artifactBase) {
* See:
* https://gist.github.com/davidjrice/9d2af51100e41c6c4b4a
* https://github.com/ComponentDriven/csf/blame/7ac941eee85816a4c567ca85460731acb5360f50/src/index.ts
*
* @param {string} string - The string to sanitize.
* @returns The sanitized string.
*/
function sanitize(string) {
return (

View File

@ -18,6 +18,7 @@ function defaultOnError(error) {
/**
* This function handles requests for the mock Segment server
*
* @typedef {(request: IncomingMessage, response: ServerResponse, metricEvents: Array<Object>) => void} MockSegmentRequestHandler
*/
@ -27,7 +28,7 @@ function defaultOnError(error) {
* to every request. The only function this serves is to spy on requests sent to
* this server, and to parse the request payloads as Segment batch events.
*
* @param {MockSegmentRequestHandler} onRequest- A callback for each request the server receives.
* @param {MockSegmentRequestHandler} onRequest - A callback for each request the server receives.
* @param {(error: Error) => void} [onError] - A callback for server error events
*/
function createSegmentServer(onRequest, onError = defaultOnError) {

View File

@ -2,7 +2,7 @@
* Parse a string as a port number. Non-integers or invalid ports will
* result in an error being thrown.
*
* @param {String} portString - The string to parse as a port number
* @param {string} portString - The string to parse as a port number
* @returns {number} The parsed port number
*/
function parsePort(portString) {

View File

@ -11,7 +11,7 @@
* @param {string} args.rejectionMessage - The message for the rejected promise
* this function will return in the event of failure. (Default: "Retry limit
* reached")
* @param {function} functionToRetry - The function that is run and tested for
* @param {Function} functionToRetry - The function that is run and tested for
* failure.
* @returns {Promise<null | Error>} a promise that either resolves to null if
* the function is successful or is rejected with rejectionMessage otherwise.

View File

@ -3629,11 +3629,6 @@
"lower-case": true
}
},
"no-case": {
"packages": {
"lower-case": true
}
},
"node-forge": {
"globals": {
"Blob": true,

View File

@ -3629,11 +3629,6 @@
"lower-case": true
}
},
"no-case": {
"packages": {
"lower-case": true
}
},
"node-forge": {
"globals": {
"Blob": true,

View File

@ -3629,11 +3629,6 @@
"lower-case": true
}
},
"no-case": {
"packages": {
"lower-case": true
}
},
"node-forge": {
"globals": {
"Blob": true,

View File

@ -21,6 +21,7 @@
"eslint": true,
"eslint-config-prettier": true,
"eslint-plugin-import": true,
"eslint-plugin-jsdoc": true,
"eslint-plugin-node": true,
"eslint-plugin-prettier": true,
"eslint-plugin-react": true,

View File

@ -825,6 +825,13 @@
"console.log": true
}
},
"@es-joy/jsdoccomment": {
"packages": {
"comment-parser": true,
"esquery": true,
"jsdoc-type-pratt-parser": true
}
},
"@eslint/eslintrc": {
"builtin": {
"assert": true,
@ -2010,6 +2017,19 @@
"typescript": true
}
},
"eslint-plugin-jsdoc": {
"packages": {
"@es-joy/jsdoccomment": true,
"comment-parser": true,
"debug": true,
"eslint": true,
"jsdoc-type-pratt-parser": true,
"lodash": true,
"regextras": true,
"semver": true,
"spdx-expression-parse": true
}
},
"eslint-plugin-node": {
"builtin": {
"fs.readFileSync": true,
@ -3052,6 +3072,11 @@
"esprima": true
}
},
"jsdoc-type-pratt-parser": {
"globals": {
"define": true
}
},
"jsesc": {
"globals": {
"Buffer.isBuffer": true
@ -4076,6 +4101,11 @@
"unicode-match-property-value-ecmascript": true
}
},
"regextras": {
"globals": {
"define": true
}
},
"regjsgen": {
"globals": {
"define": true
@ -4461,6 +4491,10 @@
"console.log": true,
"process.argv.slice": true,
"process.exit": true
},
"packages": {
"spdx-exceptions": true,
"spdx-license-ids": true
}
},
"specificity": {

View File

@ -232,10 +232,10 @@
"@lavamoat/allow-scripts": "^1.0.6",
"@lavamoat/lavapack": "^2.0.4",
"@metamask/auto-changelog": "^2.1.0",
"@metamask/eslint-config": "^8.0.0",
"@metamask/eslint-config-jest": "^8.0.0",
"@metamask/eslint-config-mocha": "^8.0.0",
"@metamask/eslint-config-nodejs": "^8.0.0",
"@metamask/eslint-config": "^9.0.0",
"@metamask/eslint-config-jest": "^9.0.0",
"@metamask/eslint-config-mocha": "^9.0.0",
"@metamask/eslint-config-nodejs": "^9.0.0",
"@metamask/forwarder": "^1.1.0",
"@metamask/test-dapp": "^4.0.1",
"@sentry/cli": "^1.58.0",
@ -280,6 +280,7 @@
"eslint-import-resolver-node": "^0.3.4",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jest": "^24.3.4",
"eslint-plugin-jsdoc": "^37.0.3",
"eslint-plugin-mocha": "^8.1.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^3.3.1",

View File

@ -4,6 +4,7 @@
* notification - When the extension opens due to interaction with a Web3 enabled website
* fullscreen - When the user clicks 'expand view' to open the extension in a new tab
* background - The background process that powers the extension
*
* @typedef {'popup' | 'notification' | 'fullscreen' | 'background'} EnvironmentType
*/
export const ENVIRONMENT_TYPE_POPUP = 'popup';

View File

@ -8,6 +8,7 @@
* Used to attach context of where the user was at in the application when the
* event was triggered. Also included as full details of the current page in
* page events.
*
* @typedef {Object} MetaMetricsPageObject
* @property {string} [path] - the path of the current page (e.g /home)
* @property {string} [title] - the title of the current page (e.g 'home')
@ -16,6 +17,7 @@
/**
* For metamask, this is the dapp that triggered an interaction
*
* @typedef {Object} MetaMetricsReferrerObject
* @property {string} [url] - the origin of the dapp issuing the
* notification
@ -28,8 +30,9 @@
* defined on every event. This is confirmed in the getTrackMetaMetricsEvent
* function, but still provides the consumer a way to override these values if
* necessary.
*
* @typedef {Object} MetaMetricsContext
* @property {Object} app
* @property {Object} app - Application metadata.
* @property {string} app.name - the name of the application tracking the event
* @property {string} app.version - the version of the application
* @property {string} userAgent - the useragent string of the user
@ -41,20 +44,20 @@
/**
* @typedef {Object} MetaMetricsEventPayload
* @property {string} event - event name to track
* @property {string} category - category to associate event to
* @property {string} event - event name to track
* @property {string} category - category to associate event to
* @property {string} [environmentType] - The type of environment this event
* occurred in. Defaults to the background process type
* @property {object} [properties] - object of custom values to track, keys
* @property {object} [properties] - object of custom values to track, keys
* in this object must be in snake_case
* @property {object} [sensitiveProperties] - Object of sensitive values to
* @property {object} [sensitiveProperties] - Object of sensitive values to
* track. Keys in this object must be in snake_case. These properties will be
* sent in an additional event that excludes the user's metaMetricsId
* @property {number} [revenue] - amount of currency that event creates in
* @property {number} [revenue] - amount of currency that event creates in
* revenue for MetaMask
* @property {string} [currency] - ISO 4127 format currency for events with
* @property {string} [currency] - ISO 4127 format currency for events with
* revenue, defaults to US dollars
* @property {number} [value] - Abstract business "value" attributable to
* @property {number} [value] - Abstract business "value" attributable to
* customers who trigger this event
* @property {MetaMetricsPageObject} [page] - the page/route that the event
* occurred on
@ -70,7 +73,7 @@
* tracking the event must be known before UI transition or update
* @property {boolean} [excludeMetaMetricsId] - whether to exclude the user's
* metametrics id for anonymity
* @property {string} [metaMetricsId] - an override for the metaMetricsId in
* @property {string} [metaMetricsId] - an override for the metaMetricsId in
* the event one is created as part of an asynchronous workflow, such as
* awaiting the result of the metametrics opt-in function that generates the
* user's metametrics id
@ -81,6 +84,7 @@
/**
* Represents the shape of data sent to the segment.track method.
*
* @typedef {Object} SegmentEventPayload
* @property {string} [userId] - The metametrics id for the user
* @property {string} [anonymousId] - An anonymousId that is used to track
@ -117,6 +121,7 @@ export const METAMETRICS_ANONYMOUS_ID = '0x0000000000000000';
/**
* This object is used to identify events that are triggered by the background
* process.
*
* @type {MetaMetricsPageObject}
*/
export const METAMETRICS_BACKGROUND_PAGE_OBJECT = {

View File

@ -2,7 +2,7 @@ import contractMap from '@metamask/contract-metadata';
/**
* A normalized list of addresses exported as part of the contractMap in
* @metamask/contract-metadata. Used primarily to validate if manually entered
* `@metamask/contract-metadata`. Used primarily to validate if manually entered
* contract addresses do not match one of our listed tokens
*/
export const LISTED_CONTRACT_ADDRESSES = Object.keys(

View File

@ -2,6 +2,7 @@ import { MESSAGE_TYPE } from './app';
/**
* Transaction Type is a MetaMask construct used internally
*
* @typedef {Object} TransactionTypes
* @property {'transfer'} TOKEN_METHOD_TRANSFER - A token transaction where the user
* is sending tokens that they own to another address
@ -35,6 +36,7 @@ import { MESSAGE_TYPE } from './app';
/**
* This type will work anywhere you expect a string that can be one of the
* above transaction types.
*
* @typedef {TransactionTypes[keyof TransactionTypes]} TransactionTypeString
*/
@ -65,6 +67,7 @@ export const TRANSACTION_TYPES = {
* typed envelope being 'legacy' and describing the shape of the base
* transaction params that were hitherto the only transaction type sent on
* Ethereum.
*
* @typedef {Object} TransactionEnvelopeTypes
* @property {'0x0'} LEGACY - A legacy transaction, the very first type.
* @property {'0x1'} ACCESS_LIST - EIP-2930 defined the access list transaction
@ -90,6 +93,7 @@ export const TRANSACTION_ENVELOPE_TYPES = {
/**
* Transaction Status is a mix of Ethereum and MetaMask terminology, used internally
* for transaction processing.
*
* @typedef {Object} TransactionStatuses
* @property {'unapproved'} UNAPPROVED - A new transaction that the user has not
* approved or rejected
@ -108,6 +112,7 @@ export const TRANSACTION_ENVELOPE_TYPES = {
/**
* This type will work anywhere you expect a string that can be one of the
* above transaction statuses.
*
* @typedef {TransactionStatuses[keyof TransactionStatuses]} TransactionStatusString
*/
@ -128,6 +133,7 @@ export const TRANSACTION_STATUSES = {
/**
* Transaction Group Status is a MetaMask construct to track the status of groups
* of transactions.
*
* @typedef {Object} TransactionGroupStatuses
* @property {'cancelled'} CANCELLED - A cancel type transaction in the group was
* confirmed
@ -147,6 +153,7 @@ export const TRANSACTION_GROUP_STATUSES = {
/**
* Transaction Group Category is a MetaMask construct to categorize the intent
* of a group of transactions for purposes of displaying in the UI
*
* @typedef {Object} TransactionGroupCategories
* @property {'send'} SEND - Transaction group representing ether being sent from
* the user.
@ -199,8 +206,8 @@ export const TRANSACTION_GROUP_CATEGORIES = {
/**
* An object representing a transaction, in whatever state it is in.
* @typedef {Object} TransactionMeta
*
* @typedef {Object} TransactionMeta
* @property {string} [blockNumber] - The block number this transaction was
* included in. Currently only present on incoming transactions!
* @property {number} id - An internally unique tx identifier.

View File

@ -5,6 +5,7 @@ import { toBuffer as ethUtilToBuffer, isHexString } from 'ethereumjs-util';
* additionally handling non hex strings. This is a failsafe as in most cases
* we should be primarily dealing with hex prefixed strings with this utility
* but we do not want to break the extension for users.
*
* @param {import('ethereumjs-util').ToBufferInputTypes | string} input
* @returns {Buffer}
*/

View File

@ -1,4 +1,5 @@
/* Currency Conversion Utility
/**
* Currency Conversion Utility
* This utility function can be used for converting currency related values within metamask.
* The caller should be able to pass it a value, along with information about the value's
* numeric base, denomination and currency, and the desired numeric base, denomination and
@ -59,16 +60,19 @@ const isValidBase = (base) => {
/**
* Defines the base type of numeric value
*
* @typedef {('hex' | 'dec' | 'BN')} NumericBase
*/
/**
* Defines which type of denomination a value is in
*
* @typedef {('WEI' | 'GWEI' | 'ETH')} EthDenomination
*/
/**
* Utility method to convert a value between denominations, formats and currencies.
*
* @param {Object} input
* @param {string | BigNumber} input.value
* @param {NumericBase} input.fromNumericBase

View File

@ -19,7 +19,7 @@ import {
* gas used. maxFeePerGas is introduced in EIP 1559 and represents the max
* total a user will pay per gas. Actual cost is determined by baseFeePerGas
* on the block + maxPriorityFeePerGas. Value is hex string
* @returns {string} - The maximum total cost of transaction in hex wei string
* @returns {string} The maximum total cost of transaction in hex wei string
*/
export function getMaximumGasTotalInHexWei({
gasLimit = '0x0',
@ -67,7 +67,7 @@ export function getMaximumGasTotalInHexWei({
* pay a miner to include this transaction.
* @param {string} [options.baseFeePerGas] - The estimated block baseFeePerGas
* that will be burned. Introduced in EIP 1559. Value in hex wei.
* @returns {string} - The minimum total cost of transaction in hex wei string
* @returns {string} The minimum total cost of transaction in hex wei string
*/
export function getMinimumGasTotalInHexWei({
gasLimit = '0x0',

View File

@ -21,6 +21,7 @@ export function isBurnAddress(address) {
* meet the length requirement of a hex address, but are not prefixed with `0x`
* Finally, if the mixedCaseUseChecksum flag is true and a mixed case string is
* provided this method will validate it has the proper checksum formatting.
*
* @param {string} possibleAddress - Input parameter to check against
* @param {Object} [options] - options bag
* @param {boolean} [options.allowNonPrefixed] - If true will first ensure '0x'

View File

@ -10,6 +10,7 @@ export function transactionMatchesNetwork(transaction, chainId, networkId) {
/**
* Determines if the maxFeePerGas and maxPriorityFeePerGas fields are supplied
* and valid inputs. This will return false for non hex string inputs.
*
* @param {import("../constants/transaction").TransactionMeta} transaction -
* the transaction to check
* @returns {boolean} true if transaction uses valid EIP1559 fields
@ -25,6 +26,7 @@ export function isEIP1559Transaction(transaction) {
* Determine if the maxFeePerGas and maxPriorityFeePerGas fields are not
* supplied and that the gasPrice field is valid if it is provided. This will
* return false if gasPrice is a non hex string.
*
* @param {import("../constants/transaction").TransactionMeta} transaction -
* the transaction to check
* @returns {boolean} true if transaction uses valid Legacy fields OR lacks
@ -41,6 +43,7 @@ export function isLegacyTransaction(transaction) {
/**
* Determine if a transactions gas fees in txParams match those in its dappSuggestedGasFees property
*
* @param {import("../constants/transaction").TransactionMeta} transaction -
* the transaction to check
* @returns {boolean} true if both the txParams and dappSuggestedGasFees are objects with truthy gas fee properties,

View File

@ -37,7 +37,6 @@ class ChromeDriver {
}
/**
* @constructor
* @param {!ThenableWebDriver} driver - a {@code WebDriver} instance
*/
constructor(driver) {
@ -46,6 +45,7 @@ class ChromeDriver {
/**
* Returns the extension ID for the given extension name
*
* @param {string} extensionName - the extension name
* @returns {Promise<string|undefined>} the extension ID
*/

View File

@ -6,7 +6,9 @@ const cssToXPath = require('css-to-xpath');
/**
* Temporary workaround to patch selenium's element handle API with methods
* that match the playwright API for Elements
*
* @param {Object} element - Selenium Element
* @param driver
* @returns {Object} modified Selenium Element
*/
function wrapElementWithAPI(element, driver) {
@ -37,6 +39,7 @@ class Driver {
/**
* @param {!ThenableWebDriver} driver - A {@code WebDriver} instance
* @param {string} browser - The type of browser this driver is controlling
* @param extensionUrl
* @param {number} timeout
*/
constructor(driver, browser, extensionUrl, timeout = 10000) {
@ -315,6 +318,7 @@ class Driver {
/**
* Closes all windows except those in the given list of exceptions
*
* @param {Array<string>} exceptions - The list of window handle exceptions
* @param {Array} [windowHandles] - The full list of window handles
* @returns {Promise<void>}

View File

@ -8,6 +8,7 @@ const { version } = require('../../../package.json');
/**
* The prefix for temporary Firefox profiles. All Firefox profiles used for e2e tests
* will be created as random directories inside this.
*
* @type {string}
*/
const TEMP_PROFILE_PATH_PREFIX = path.join(os.tmpdir(), 'MetaMask-Fx-Profile');
@ -18,7 +19,10 @@ const TEMP_PROFILE_PATH_PREFIX = path.join(os.tmpdir(), 'MetaMask-Fx-Profile');
class FirefoxDriver {
/**
* Builds a {@link FirefoxDriver} instance
*
* @param {Object} options - the options for the build
* @param options.responsive
* @param options.port
* @returns {Promise<{driver: !ThenableWebDriver, extensionUrl: string, extensionId: string}>}
*/
static async build({ responsive, port }) {
@ -51,7 +55,6 @@ class FirefoxDriver {
}
/**
* @constructor
* @param {!ThenableWebDriver} driver - a {@code WebDriver} instance
*/
constructor(driver) {
@ -60,6 +63,7 @@ class FirefoxDriver {
/**
* Installs the extension at the given path
*
* @param {string} addonPath - the path to the unpacked extension or XPI
* @returns {Promise<string>} the extension ID
*/
@ -69,6 +73,7 @@ class FirefoxDriver {
/**
* Returns the Internal UUID for the given extension
*
* @returns {Promise<string>} the Internal UUID for the given extension
*/
async getInternalId() {

View File

@ -20,6 +20,10 @@ import MetaMaskTemplateRenderer, {
* from being performance hogs. We could further limit this, and also attenuate
* the safeComponentList for what kind of components we allow these special
* trees to contain.
*
* @param options
* @param options.translationKey
* @param options.variables
*/
export default function MetaMaskTranslation({ translationKey, variables }) {
const t = useI18nContext();

View File

@ -273,6 +273,7 @@ function filterSortedActivities(activities) {
/**
* Combines the histories of an array of transactions into a single array.
*
* @param {Array} transactions - Array of txMeta transaction objects.
* @returns {Array}
*/

View File

@ -87,6 +87,7 @@ export default class Tabs extends Component {
/**
* Returns the index of the child with the given name
*
* @param {string} name - the name to search for
* @returns {number} the index of the child with the given name
* @private

View File

@ -57,6 +57,7 @@ const PATHS_TO_CHECK = Object.keys(PATH_NAME_MAP);
/**
* Returns the current page if it matches out route map, as well as the origin
* if there is a confirmation that was triggered by a dapp
*
* @returns {{
* page?: MetaMetricsPageObject
* referrer?: MetaMetricsReferrerObject

View File

@ -312,6 +312,8 @@ export function getUnapprovedTxs(state) {
/**
* Function returns true if network details are fetched and it is found to not support EIP-1559
*
* @param state
*/
export function isNotEIP1559Network(state) {
return state.metamask.networkDetails?.EIPS[1559] === false;
@ -319,6 +321,8 @@ export function isNotEIP1559Network(state) {
/**
* Function returns true if network details are fetched and it is found to support EIP-1559
*
* @param state
*/
export function isEIP1559Network(state) {
return state.metamask.networkDetails?.EIPS[1559] === true;

View File

@ -382,6 +382,7 @@ export const computeEstimatedGasLimit = createAsyncThunk(
* duck (here) we would use getGasPriceInHexWei to get back to hexWei. Now that
* we receive a GWEI estimate from the controller, we still need to do this
* weird conversion to get the proper rounding.
*
* @param {T} gasPriceEstimate
* @returns
*/
@ -631,6 +632,9 @@ const slice = createSlice({
/**
* update current amount.value in state and run post update validation of
* the amount field and the send state. Recomputes the draftTransaction
*
* @param state
* @param action
*/
updateSendAmount: (state, action) => {
state.amount.value = addHexPrefix(action.payload);
@ -650,6 +654,8 @@ const slice = createSlice({
* computes the maximum amount of asset that can be sent and then calls
* the updateSendAmount action above with the computed value, which will
* revalidate the field and form and recomputes the draftTransaction
*
* @param state
*/
updateAmountToMax: (state) => {
let amount = '0x0';
@ -684,6 +690,9 @@ const slice = createSlice({
* native asset. When sending ERC20 assets, this is unnecessary because the
* hex data used in the transaction will be that for interacting with the
* ERC20 contract
*
* @param state
* @param action
*/
updateUserInputHexData: (state, action) => {
state.draftTransaction.userInputHexData = action.payload;
@ -696,6 +705,9 @@ const slice = createSlice({
* then pulling the details of the previously submitted transaction from
* the action payload. It also computes a new draftTransaction that will be
* used when updating the transaction in the provider
*
* @param state
* @param action
*/
editTransaction: (state, action) => {
state.stage = SEND_STAGES.EDIT;
@ -717,6 +729,8 @@ const slice = createSlice({
* sending the native token. ERC20 assets max amount is unaffected by
* gasTotal so does not need to be recomputed. Finally, validates the gas
* field and send state, then updates the draft transaction.
*
* @param state
*/
calculateGasTotal: (state) => {
// use maxFeePerGas as the multiplier if working with a FEE_MARKET transaction
@ -743,6 +757,9 @@ const slice = createSlice({
},
/**
* sets the provided gasLimit in state and then recomputes the gasTotal.
*
* @param state
* @param action
*/
updateGasLimit: (state, action) => {
state.gas.gasLimit = addHexPrefix(action.payload);
@ -751,6 +768,9 @@ const slice = createSlice({
/**
* Sets the appropriate gas fees in state and determines and sets the
* appropriate transactionType based on gas fee fields received.
*
* @param state
* @param action
*/
updateGasFees: (state, action) => {
if (
@ -784,6 +804,9 @@ const slice = createSlice({
},
/**
* Sets the appropriate gas fees in state after receiving new estimates.
*
* @param state
* @param action
*/
updateGasFeeEstimates: (state, action) => {
const { gasFeeEstimates, gasEstimateType } = action.payload;
@ -832,6 +855,9 @@ const slice = createSlice({
/**
* sets the amount mode to the provided value as long as it is one of the
* supported modes (MAX|INPUT)
*
* @param state
* @param action
*/
updateAmountMode: (state, action) => {
if (Object.values(AMOUNT_MODES).includes(action.payload)) {
@ -1290,7 +1316,6 @@ export { useDefaultGas, useCustomGas, updateGasLimit };
*
* @deprecated - don't extend the usage of this temporary method
* @param {string} gasPrice - new gas price in hex wei
* @returns {void}
*/
export function updateGasPrice(gasPrice) {
return (dispatch) => {
@ -1320,8 +1345,8 @@ export function resetSendState() {
* Updates the amount the user intends to send and performs side effects.
* 1. If the current mode is MAX change to INPUT
* 2. If sending a token, recompute the gasLimit estimate
*
* @param {string} amount - hex string representing value
* @returns {void}
*/
export function updateSendAmount(amount) {
return async (dispatch, getState) => {
@ -1334,18 +1359,24 @@ export function updateSendAmount(amount) {
};
}
/**
* Defines the shape for the details input parameter for updateSendAsset
*
* @typedef {Object} TokenDetails
* @property {string} address - The contract address for the ERC20 token.
* @property {string} decimals - The number of token decimals.
* @property {string} symbol - The asset symbol to display.
*/
/**
* updates the asset to send to one of NATIVE or TOKEN and ensures that the
* asset balance is set. If sending a TOKEN also updates the asset details
* object with the appropriate ERC20 details including address, symbol and
* decimals.
*
* @param {Object} payload - action payload
* @param {string} payload.type - type of asset to send
* @param {Object} [payload.details] - ERC20 details if sending TOKEN asset
* @param {string} [payload.details.address] - contract address for ERC20
* @param {string} [payload.details.decimals] - Number of token decimals
* @param {string} [payload.details.symbol] - asset symbol to display
* @returns {void}
* @param {TokenDetails} [payload.details] - ERC20 details if sending TOKEN asset
*/
export function updateSendAsset({ type, details }) {
return async (dispatch, getState) => {
@ -1396,8 +1427,8 @@ const debouncedValidateRecipientUserInput = debounce((dispatch, payload) => {
* Once the field is updated, the field will be validated using a debounced
* version of the validateRecipientUserInput action. This way validation only
* occurs once the user has stopped typing.
*
* @param {string} userInput - the value that the user is typing into the field
* @returns {void}
*/
export function updateRecipientUserInput(userInput) {
return async (dispatch, getState) => {
@ -1438,11 +1469,11 @@ export function useMyAccountsForRecipientSearch() {
* a nickname for the passed address has already been saved. This ensures the
* (temporary) send state recipient nickname is consistent with the address book
* nickname which has already been persisted to state.
*
* @param {Object} recipient - Recipient information
* @param {string} recipient.address - hex address to send the transaction to
* @param {string} [recipient.nickname] - Alias for the address to display
* to the user
* @returns {void}
*/
export function updateRecipient({ address, nickname }) {
return async (dispatch, getState) => {
@ -1460,8 +1491,7 @@ export function updateRecipient({ address, nickname }) {
}
/**
* Clears out the recipient user input, ENS resolution and recipient validation
* @returns {void}
* Clears out the recipient user input, ENS resolution and recipient validation.
*/
export function resetRecipientInput() {
return async (dispatch) => {
@ -1479,8 +1509,8 @@ export function resetRecipientInput() {
* recomputing estimated gasLimit. When sending a ERC20 asset this is not done
* because the data sent in the transaction will be determined by the asset,
* recipient and value, NOT what the user has supplied.
* @param {string} hexData - hex encoded string representing transaction data
* @returns {void}
*
* @param {string} hexData - hex encoded string representing transaction data.
*/
export function updateSendHexData(hexData) {
return async (dispatch, getState) => {
@ -1497,7 +1527,6 @@ export function updateSendHexData(hexData) {
* As a result, the amount.value will change to either '0x0' when moving from
* MAX to INPUT, or to the maximum allowable amount based on current asset when
* moving from INPUT to MAX.
* @returns {void}
*/
export function toggleSendMaxMode() {
return async (dispatch, getState) => {
@ -1520,7 +1549,6 @@ export function toggleSendMaxMode() {
* will create the transaction in state (by way of the various global provider
* constructs) which will eventually (and fairly quickly from user perspective)
* result in a confirmation window being displayed for the transaction.
* @returns {void}
*/
export function signTransaction() {
return async (dispatch, getState) => {

View File

@ -25,7 +25,8 @@ export const gasEstimateGreaterThanGasUsedPlusTenPercent = (
* by 1.10 to get bare minimum new gas fee.
*
* @param {string | undefined} hexStringValue - hex value in wei to be incremented
* @returns {string | undefined} - hex value in WEI 10% higher than the param.
* @param conversionOptions
* @returns {string | undefined} hex value in WEI 10% higher than the param.
*/
export function addTenPercent(hexStringValue, conversionOptions = {}) {
if (hexStringValue === undefined) {
@ -47,7 +48,7 @@ export function addTenPercent(hexStringValue, conversionOptions = {}) {
* by 1.10 to get bare minimum new gas fee.
*
* @param {string | undefined} hexStringValue - hex value in wei to be incremented
* @returns {string | undefined} - hex value in WEI 10% higher than the param.
* @returns {string | undefined} hex value in WEI 10% higher than the param.
*/
export function addTenPercentAndRound(hexStringValue) {
return addTenPercent(hexStringValue, { numberOfDecimals: 0 });

View File

@ -14,6 +14,7 @@ const missingSubstitutionErrors = {};
/**
* Returns a localized message for the given key
*
* @param {string} localeCode - The code for the current locale
* @param {Object} localeMessages - The map of messages for the current locale
* @param {string} key - The message key

View File

@ -1,7 +1,8 @@
/**
* Switch the CSS stylesheet used between 'rtl' and 'ltr'
*
* @param {('ltr' | 'rtl' | 'auto')} direction - Text direction, either left-to-right (ltr) or right-to-left (rtl)
* @return {Promise<void>}
* @returns {Promise<void>}
*/
const switchDirection = async (direction) => {
if (direction === 'auto') {

View File

@ -30,6 +30,7 @@ const hstInterface = new ethers.utils.Interface(abi);
*/
/**
* @param data
* @returns {EthersContractCall | undefined}
*/
export function getTokenData(data) {
@ -61,6 +62,7 @@ let registry;
/**
* Attempts to return the method data from the MethodRegistry library, the message registry library and the token abi, in that order of preference
*
* @param {string} fourBytePrefix - The prefix from the method code associated with the data
* @returns {Object}
*/
@ -168,6 +170,7 @@ export function isLegacyTransaction(txParams) {
/**
* Returns a status key for a transaction. Requires parsing the txMeta.txReceipt on top of
* txMeta.status because txMeta.status does not reflect on-chain errors.
*
* @param {Object} transaction - The txMeta object of a transaction.
* @param {Object} transaction.txReceipt - The transaction receipt.
* @returns {string}
@ -198,7 +201,8 @@ export function getStatusKey(transaction) {
* Returns a title for the given transaction category.
*
* This will throw an error if the transaction category is unrecognized and no default is provided.
* @param {function} t - The translation function
*
* @param {Function} t - The translation function
* @param {TRANSACTION_TYPES[keyof TRANSACTION_TYPES]} type - The transaction type constant
* @param {string} nativeCurrency - The native currency of the currently selected network
* @returns {string} The transaction category title

View File

@ -45,6 +45,7 @@ export function formatDateWithYearContext(
}
/**
* Determines if the provided chainId is a default MetaMask chain
*
* @param {string} chainId - chainId to check
*/
export function isDefaultMetaMaskChain(chainId) {
@ -341,6 +342,8 @@ export function toPrecisionWithoutTrailingZeros(n, precision) {
/**
* Given and object where all values are strings, returns the same object with all values
* now prefixed with '0x'
*
* @param obj
*/
export function addHexPrefixToObjectValues(obj) {
return Object.keys(obj).reduce((newObj, key) => {
@ -352,12 +355,14 @@ export function addHexPrefixToObjectValues(obj) {
* Given the standard set of information about a transaction, returns a transaction properly formatted for
* publishing via JSON RPC and web3
*
* @param {boolean} [sendToken] - Indicates whether or not the transaciton is a token transaction
* @param {string} data - A hex string containing the data to include in the transaction
* @param {string} to - A hex address of the tx recipient address
* @param {string} from - A hex address of the tx sender address
* @param {string} gas - A hex representation of the gas value for the transaction
* @param {string} gasPrice - A hex representation of the gas price for the transaction
* @param {object} options
* @param {boolean} [options.sendToken] - Indicates whether or not the transaciton is a token transaction
* @param {string} options.data - A hex string containing the data to include in the transaction
* @param {string} options.to - A hex address of the tx recipient address
* @param options.amount
* @param {string} options.from - A hex address of the tx sender address
* @param {string} options.gas - A hex representation of the gas value for the transaction
* @param {string} options.gasPrice - A hex representation of the gas price for the transaction
* @returns {Object} An object ready for submission to the blockchain, with all values appropriately hex prefixed
*/
export function constructTxParams({

View File

@ -33,12 +33,24 @@ import { useUserPreferencedCurrency } from '../useUserPreferencedCurrency';
* current network transaction volume increases. Expressed in the network's native currency.
* @property {string} [estimatedMinimumNative] - the maximum amount estimated to be paid if the
* current network transaction volume increases. Expressed in the network's native currency.
* @property {string} [estimatedMinimumNative] - the maximum amount estimated to be paid if the
* current network transaction volume increases. Expressed in the network's native currency.
* @property {HexWeiString} [estimatedBaseFee] - estimatedBaseFee from fee-market gasFeeEstimates
* in HexWei.
* @property {HexWeiString} [minimumCostInHexWei] - the minimum amount this transaction will cost.
*/
/**
* @param options
* @param options.editGasMode
* @param options.gasEstimateType
* @param options.gasFeeEstimates
* @param options.gasLimit
* @param options.gasPrice
* @param options.maxFeePerGas
* @param options.maxPriorityFeePerGas
* @param options.minimumGasLimit
* @param options.transaction
* @returns {GasEstimatesReturnType} The gas estimates.
*/
export function useGasEstimates({
editGasMode,
gasEstimateType,

View File

@ -163,6 +163,21 @@ const hasBalanceError = (minimumCostInHexWei, transaction, ethBalance) => {
* @property {boolean} [estimatesUnavailableWarning] - true if supportsEIP1559 is true and
* estimate is not of type fee-market.
*/
/**
* @param options
* @param options.gasEstimateType
* @param options.gasFeeEstimates
* @param options.isGasEstimatesLoading
* @param options.gasLimit
* @param options.gasPrice
* @param options.maxPriorityFeePerGas
* @param options.maxFeePerGas
* @param options.minimumCostInHexWei
* @param options.minimumGasLimit
* @param options.transaction
* @returns {GasFeeErrorsReturnType}
*/
export function useGasFeeErrors({
gasEstimateType,
gasFeeEstimates,

View File

@ -77,11 +77,15 @@ import { useTransactionFunctions } from './useTransactionFunctions';
* Uses gasFeeEstimates and state to keep track of user gas fee inputs.
* Will update the gas fee state when estimates update if the user has not yet
* modified the fields.
* @param {EstimateLevel} defaultEstimateToUse - which estimate
*
* @param {EstimateLevel} [defaultEstimateToUse] - which estimate
* level to default the 'estimateToUse' state variable to.
* @param {object} [transaction]
* @param {string} [minimumGasLimit]
* @param {EDIT_GAS_MODES[keyof EDIT_GAS_MODES]} editGasMode
* @returns {GasFeeInputReturnType & import(
* './useGasFeeEstimates'
* ).GasEstimates} - gas fee input state and the GasFeeEstimates object
* ).GasEstimates} gas fee input state and the GasFeeEstimates object
*/
export function useGasFeeInputs(
defaultEstimateToUse = GAS_RECOMMENDATIONS.MEDIUM,

View File

@ -26,6 +26,15 @@ function getGasPriceEstimate(gasFeeEstimates, gasEstimateType, estimateToUse) {
* @property {(boolean) => true} setGasPriceHasBeenManuallySet - state setter method to update gasPriceHasBeenManuallySet
* field gasPriceHasBeenManuallySet is used in gasPrice calculations.
*/
/**
* @param options
* @param options.estimateToUse
* @param options.gasEstimateType
* @param options.gasFeeEstimates
* @param options.transaction
* @returns {GasPriceInputsReturnType}
*/
export function useGasPriceInput({
estimateToUse,
gasEstimateType,

View File

@ -30,8 +30,18 @@ const getMaxFeePerGasFromTransaction = (transaction) => {
* update the maxFeePerGas.
* @property {string} [maxFeePerGasFiat] - the maxFeePerGas converted to the
* user's preferred currency.
* @property {(DecGweiString) => void} setMaxFeePerGas - state setter
* method to update the setMaxFeePerGas.
*/
/**
* @param options
* @param options.supportsEIP1559V2
* @param options.estimateToUse
* @param options.gasEstimateType
* @param options.gasFeeEstimates
* @param options.gasLimit
* @param options.gasPrice
* @param options.transaction
* @returns {MaxFeePerGasInputReturnType}
*/
export function useMaxFeePerGasInput({
estimateToUse,

View File

@ -33,6 +33,17 @@ const getMaxPriorityFeePerGasFromTransaction = (transaction) => {
* @property {(DecGweiString) => void} setMaxPriorityFeePerGas - state setter
* method to update the maxPriorityFeePerGas.
*/
/**
* @param options
* @param options.supportsEIP1559V2
* @param options.estimateToUse
* @param options.gasEstimateType
* @param options.gasFeeEstimates
* @param options.gasLimit
* @param options.transaction
* @returns {MaxPriorityFeePerGasInputReturnType}
*/
export function useMaxPriorityFeePerGasInput({
estimateToUse,
gasEstimateType,

View File

@ -6,8 +6,8 @@ import { useCallback, useState } from 'react';
*
* Provides a reusable hook that, given a transactionGroup, will manage
* the process of editing gas for approvals
* @param {Object} transactionGroup
* @return {[boolean, Function]}
*
* @returns {[boolean, Function]}
*/
export function useApproveTransaction() {
const [showCustomizeGasPopover, setShowCustomizeGasPopover] = useState(false);

View File

@ -7,8 +7,7 @@ import { useTimeout } from './useTimeout';
* useCopyToClipboard
*
* @param {number} [delay=3000] - delay in ms
*
* @return {[boolean, Function]}
* @returns {[boolean, Function]}
*/
const DEFAULT_DELAY = SECOND * 3;

View File

@ -14,20 +14,22 @@ import { conversionUtil } from '../../shared/modules/conversion.utils';
/**
* Defines the shape of the options parameter for useCurrencyDisplay
*
* @typedef {Object} UseCurrencyOptions
* @property {string} [displayValue] - When present is used in lieu of formatting the inputValue
* @property {string} [prefix] - String to prepend to the final result
* @property {string} [displayValue] - When present is used in lieu of formatting the inputValue
* @property {string} [prefix] - String to prepend to the final result
* @property {number} [numberOfDecimals] - Number of significant decimals to display
* @property {string} [denomination] - Denomination (wei, gwei) to convert to for display
* @property {string} [currency] - Currency type to convert to. Will override nativeCurrency
* @property {string} [denomination] - Denomination (wei, gwei) to convert to for display
* @property {string} [currency] - Currency type to convert to. Will override nativeCurrency
*/
/**
* Defines the return shape of the second value in the tuple
*
* @typedef {Object} CurrencyDisplayParts
* @property {string} [prefix] - string to prepend to the value for display
* @property {string} value - string representing the value, formatted for display
* @property {string} [suffix] - string to append to the value for display
* @property {string} [prefix] - string to prepend to the value for display
* @property {string} value - string representing the value, formatted for display
* @property {string} [suffix] - string to append to the value for display
*/
/**
@ -36,9 +38,10 @@ import { conversionUtil } from '../../shared/modules/conversion.utils';
* Given a hexadecimal encoded value string and an object of parameters used for formatting the
* display, produce both a fully formed string and the pieces of that string used for displaying
* the currency to the user
* @param {string} inputValue - The value to format for display
* @param {UseCurrencyOptions} opts - An object for options to format the inputValue
* @return {[string, CurrencyDisplayParts]}
*
* @param {string} inputValue - The value to format for display
* @param {UseCurrencyOptions} opts - An object for options to format the inputValue
* @returns {[string, CurrencyDisplayParts]}
*/
export function useCurrencyDisplay(
inputValue,

View File

@ -14,6 +14,7 @@ import {
* Will return the default token object for the current chain when the
* user is viewing either the primary, unfiltered, activity list or the
* default token asset page.
*
* @returns {import('./useTokenDisplayValue').Token}
*/
export function useCurrentAsset() {

View File

@ -8,12 +8,12 @@ import { getConversionRate } from '../ducks/metamask/metamask';
/**
* Get an Eth amount converted to fiat and formatted for display
*
* @param {string} [tokenAmount] - The eth amount to convert
* @param {string} [ethAmount] - The eth amount to convert
* @param {Object} [overrides] - A configuration object that allows the called to explicitly
* ensure fiat is shown even if the property is not set in state.
* @param {boolean} [overrides.showFiat] - If truthy, ensures the fiat value is shown even if the showFiat value from state is falsey
* @param {boolean} hideCurrencySymbol Indicates whether the returned formatted amount should include the trailing currency symbol
* @return {string} - The formatted token amount in the user's chosen fiat currency
* @param {boolean} hideCurrencySymbol - Indicates whether the returned formatted amount should include the trailing currency symbol
* @returns {string} The formatted token amount in the user's chosen fiat currency
*/
export function useEthFiatAmount(
ethAmount,

View File

@ -160,6 +160,21 @@ const getBalanceError = (minimumCostInHexWei, transaction, ethBalance) => {
* @property {boolean} [estimatesUnavailableWarning] - true if supportsEIP1559 is true and
* estimate is not of type fee-market.
*/
/**
* @param options
* @param options.transaction
* @param options.gasEstimateType
* @param options.gasFeeEstimates
* @param options.gasLimit
* @param options.gasPriceToUse
* @param options.isGasEstimatesLoading
* @param options.maxPriorityFeePerGasToUse
* @param options.maxFeePerGasToUse
* @param options.minimumCostInHexWei
* @param options.minimumGasLimit
* @returns {GasFeeErrorsReturnType}
*/
export function useGasFeeErrors({
transaction,
gasEstimateType,

View File

@ -28,7 +28,7 @@ import { useSafeGasEstimatePolling } from './useSafeGasEstimatePolling';
* GasFeeController that it is done requiring new gas estimates. Also checks
* the returned gas estimate for validity on the current network.
*
* @returns {GasFeeEstimates} - GasFeeEstimates object
* @returns {GasFeeEstimates} GasFeeEstimates object
*/
export function useGasFeeEstimates() {
const gasEstimateType = useSelector(getGasEstimateType);

View File

@ -6,7 +6,8 @@ import { I18nContext } from '../contexts/i18n';
*
* A time saving shortcut to using useContext + I18ncontext in many
* different places.
* @return {Function} I18n function from contexts/I18n.js
*
* @returns {Function} I18n function from contexts/I18n.js
*/
export function useI18nContext() {
return useContext(I18nContext);

View File

@ -12,7 +12,7 @@ import { useGasFeeEstimates } from './useGasFeeEstimates';
*
* @param {string} originalFee - hexWei vale of the original fee (maxFee or maxPriority)
* @param {string} currentEstimate - decGwei value of the current medium gasFee estimate (maxFee or maxPriorityfee)
* @returns {string} - hexWei value of the higher of the two inputs.
* @returns {string} hexWei value of the higher of the two inputs.
*/
function getHighestIncrementedFee(originalFee, currentEstimate) {
const buffedOriginalHexWei = addTenPercent(originalFee);
@ -32,10 +32,11 @@ function getHighestIncrementedFee(originalFee, currentEstimate) {
* discarded by the network to avoid DoS attacks. This hook returns an object
* that either has gasPrice or maxFeePerGas/maxPriorityFeePerGas specified. In
* addition the gasLimit will also be included.
*
* @param {} transaction
* @returns {import(
* '../../app/scripts/controllers/transactions'
* ).CustomGasSettings} - Gas settings for cancellations/speed ups
* ).CustomGasSettings} Gas settings for cancellations/speed ups
*/
export function useIncrementedGasFees(transaction) {
const { gasFeeEstimates = {} } = useGasFeeEstimates();

View File

@ -13,8 +13,9 @@ import { getKnownMethodData } from '../selectors/selectors';
* if the data is in the store and returning it directly. While using this hook
* in multiple places in a tree for the same data will create extra event ticks and
* hit the action more frequently, it should only ever result in a single store update
*
* @param {string} data - the transaction data to find method data for
* @return {Object} contract method data
* @returns {Object} contract method data
*/
export function useMethodData(data) {
const dispatch = useDispatch();

Some files were not shown because too many files have changed in this diff Show More