diff --git a/package.json b/package.json index c19eb01076..282f2d9fa9 100644 --- a/package.json +++ b/package.json @@ -70,10 +70,10 @@ "devDependencies": { "@lavamoat/allow-scripts": "^1.0.6", "@metamask/auto-changelog": "^2.5.0", - "@metamask/eslint-config": "^8.0.0", - "@metamask/eslint-config-jest": "^8.0.0", - "@metamask/eslint-config-nodejs": "^8.0.0", - "@metamask/eslint-config-typescript": "^8.0.0", + "@metamask/eslint-config": "^9.0.0", + "@metamask/eslint-config-jest": "^9.0.0", + "@metamask/eslint-config-nodejs": "^9.0.0", + "@metamask/eslint-config-typescript": "^9.0.1", "@types/jest": "^26.0.22", "@types/node": "^14.14.31", "@types/punycode": "^2.1.0", @@ -86,6 +86,7 @@ "eslint-import-resolver-typescript": "^2.4.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jest": "^24.1.5", + "eslint-plugin-jsdoc": "^36.1.0", "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^3.3.1", "ethjs-provider-http": "^0.1.6", diff --git a/src/BaseController.ts b/src/BaseController.ts index 1fbe25438c..f17c4e0b45 100644 --- a/src/BaseController.ts +++ b/src/BaseController.ts @@ -7,7 +7,6 @@ export type Listener = (state: T) => void; * @type BaseConfig * * Base controller configuration - * * @property disabled - Determines if this controller is enabled */ export interface BaseConfig { @@ -18,7 +17,6 @@ export interface BaseConfig { * @type BaseState * * Base state representation - * * @property name - Unique name for this controller */ export interface BaseState { @@ -63,8 +61,8 @@ export class BaseController { * Creates a BaseController instance. Both initial state and initial * configuration options are merged with defaults upon initialization. * - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor(config: Partial = {} as C, state: Partial = {} as S) { // Use assign since generics can't be spread: https://git.io/vpRhY @@ -77,7 +75,7 @@ export class BaseController { * variable on this instance and triggers any defined setters. This * also sets initial state and triggers any listeners. * - * @returns - This controller instance + * @returns This controller instance. */ protected initialize() { this.internalState = this.defaultState; @@ -88,29 +86,29 @@ export class BaseController { } /** - * Retrieves current controller configuration options + * Retrieves current controller configuration options. * - * @returns - Current configuration + * @returns The current configuration. */ get config() { return this.internalConfig; } /** - * Retrieves current controller state + * Retrieves current controller state. * - * @returns - Current state + * @returns The current state. */ get state() { return this.internalState; } /** - * Updates controller configuration + * Updates controller configuration. * - * @param config - New configuration options - * @param overwrite - Overwrite config instead of merging - * @param fullUpdate - Boolean that defines if the update is partial or not + * @param config - New configuration options. + * @param overwrite - Overwrite config instead of merging. + * @param fullUpdate - Boolean that defines if the update is partial or not. */ configure(config: Partial, overwrite = false, fullUpdate = true) { if (fullUpdate) { @@ -135,7 +133,7 @@ export class BaseController { } /** - * Notifies all subscribed listeners of current state + * Notifies all subscribed listeners of current state. */ notify() { if (this.disabled) { @@ -148,19 +146,19 @@ export class BaseController { } /** - * Adds new listener to be notified of state changes + * Adds new listener to be notified of state changes. * - * @param listener - Callback triggered when state changes + * @param listener - The callback triggered when state changes. */ subscribe(listener: Listener) { this.internalListeners.push(listener); } /** - * Removes existing listener from receiving state changes + * Removes existing listener from receiving state changes. * - * @param listener - Callback to remove - * @returns - True if a listener is found and unsubscribed + * @param listener - The callback to remove. + * @returns `true` if a listener is found and unsubscribed. */ unsubscribe(listener: Listener) { const index = this.internalListeners.findIndex((cb) => listener === cb); @@ -169,10 +167,10 @@ export class BaseController { } /** - * Updates controller state + * Updates controller state. * - * @param state - New state - * @param overwrite - Overwrite state instead of merging + * @param state - The new state. + * @param overwrite - Overwrite state instead of merging. */ update(state: Partial, overwrite = false) { this.internalState = overwrite diff --git a/src/BaseControllerV2.test.ts b/src/BaseControllerV2.test.ts index d165d4f7b7..2c2eea7175 100644 --- a/src/BaseControllerV2.test.ts +++ b/src/BaseControllerV2.test.ts @@ -41,6 +41,12 @@ type CountMessenger = RestrictedControllerMessenger< never >; +/** + * Constructs a restricted controller messenger for the Count controller. + * + * @param controllerMessenger - The controller messenger. + * @returns A restricted controller messenger for the Count controller. + */ function getCountMessenger( controllerMessenger?: ControllerMessenger< CountControllerAction, diff --git a/src/BaseControllerV2.ts b/src/BaseControllerV2.ts index 876ac66c68..26fe4b0a20 100644 --- a/src/BaseControllerV2.ts +++ b/src/BaseControllerV2.ts @@ -18,9 +18,9 @@ enablePatches(); * the new state along with a set of patches describing the changes since the * last update. * - * @param state - The new controller state + * @param state - The new controller state. * @param patches - A list of patches describing any changes (see here for more - * information: https://immerjs.github.io/immer/docs/patches) + * information: https://immerjs.github.io/immer/docs/patches) */ export type Listener = (state: T, patches: Patch[]) => void; @@ -30,8 +30,8 @@ export type Listener = (state: T, patches: Patch[]) => void; * This function will accept one piece of the controller state (one property), * and will return some derivation of that state. * - * @param value - A piece of controller state - * @returns Something derived from controller state + * @param value - A piece of controller state. + * @returns Something derived from controller state. */ export type StateDeriver = (value: T) => Json; @@ -49,12 +49,12 @@ export type StateMetadata> = { * Metadata for a single state property * * @property persist - Indicates whether this property should be persisted - * (`true` for persistent, `false` for transient), or is set to a function - * that derives the persistent state from the state. + * (`true` for persistent, `false` for transient), or is set to a function + * that derives the persistent state from the state. * @property anonymous - Indicates whether this property is already anonymous, - * (`true` for anonymous, `false` if it has potential to be personally - * identifiable), or is set to a function that returns an anonymized - * representation of this state. + * (`true` for anonymous, `false` if it has potential to be personally + * identifiable), or is set to a function that returns an anonymized + * representation of this state. */ export interface StatePropertyMetadata { persist: boolean | StateDeriver; @@ -101,12 +101,12 @@ export class BaseController< /** * Creates a BaseController instance. * - * @param options - * @param options.messenger - Controller messaging system + * @param options - Controller options. + * @param options.messenger - Controller messaging system. * @param options.metadata - State metadata, describing how to "anonymize" the state, and which - * parts should be persisted. - * @param options.name - The name of the controller, used as a namespace for events and actions - * @param options.state - Initial controller state + * parts should be persisted. + * @param options.name - The name of the controller, used as a namespace for events and actions. + * @param options.state - Initial controller state. */ constructor({ messenger, @@ -131,9 +131,9 @@ export class BaseController< } /** - * Retrieves current controller state + * Retrieves current controller state. * - * @returns - Current state + * @returns The current state. */ get state() { return this.internalState; @@ -152,7 +152,7 @@ export class BaseController< * applied to the controller state. * * @param callback - Callback for updating state, passed a draft state - * object. Return a new state object or mutate the draft to update state. + * object. Return a new state object or mutate the draft to update state. */ protected update(callback: (state: Draft) => void | S) { // We run into ts2589, "infinite type depth", if we don't cast @@ -193,10 +193,10 @@ export class BaseController< * By "anonymized" we mean that it should not contain any information that could be personally * identifiable. * - * @param state - The controller state + * @param state - The controller state. * @param metadata - The controller state metadata, which describes how to derive the - * anonymized state - * @returns The anonymized controller state + * anonymized state. + * @returns The anonymized controller state. */ export function getAnonymizedState>( state: S, @@ -206,11 +206,11 @@ export function getAnonymizedState>( } /** - * Returns the subset of state that should be persisted + * Returns the subset of state that should be persisted. * - * @param state - The controller state - * @param metadata - The controller state metadata, which describes which pieces of state should be persisted - * @returns The subset of controller state that should be persisted + * @param state - The controller state. + * @param metadata - The controller state metadata, which describes which pieces of state should be persisted. + * @returns The subset of controller state that should be persisted. */ export function getPersistentState>( state: S, @@ -219,6 +219,14 @@ export function getPersistentState>( return deriveStateFromMetadata(state, metadata, 'persist'); } +/** + * Use the metadata to derive state according to the given metadata property. + * + * @param state - The full controller state. + * @param metadata - The controller metadata. + * @param metadataProperty - The metadata property to use to derive state. + * @returns The metadata-derived controller state. + */ function deriveStateFromMetadata>( state: S, metadata: StateMetadata, diff --git a/src/ComposableController.ts b/src/ComposableController.ts index 70fe0a2aca..8b1664df5e 100644 --- a/src/ComposableController.ts +++ b/src/ComposableController.ts @@ -35,10 +35,10 @@ export class ComposableController extends BaseController { name = 'ComposableController'; /** - * Creates a ComposableController instance + * Creates a ComposableController instance. * - * @param controllers - Map of names to controller instances - * @param messenger - The controller messaging system, used for communicating with BaseControllerV2 controllers + * @param controllers - Map of names to controller instances. + * @param messenger - The controller messaging system, used for communicating with BaseControllerV2 controllers. */ constructor( controllers: ControllerList, @@ -86,7 +86,7 @@ export class ComposableController extends BaseController { * of controller name. Instead, all child controller state is merged * together into a single, flat object. * - * @returns - Merged state representation of all child controllers + * @returns Merged state representation of all child controllers. */ get flatState() { let flatState = {}; diff --git a/src/ControllerMessenger.ts b/src/ControllerMessenger.ts index 00235111de..9b403689d0 100644 --- a/src/ControllerMessenger.ts +++ b/src/ControllerMessenger.ts @@ -75,8 +75,8 @@ type NarrowToAllowed = T extends { * and events. * * @template N - The namespace for this messenger. Typically this is the name of the controller or - * module that this messenger has been created for. The authority to publish events and register - * actions under this namespace is granted to this restricted messenger instance. + * module that this messenger has been created for. The authority to publish events and register + * actions under this namespace is granted to this restricted messenger instance. * @template Action - A type union of all Action types. * @template Event - A type union of all Event types. * @template AllowedAction - A type union of the 'type' string for any allowed actions. @@ -108,15 +108,15 @@ export class RestrictedControllerMessenger< * namespace. Ownership allows registering actions and publishing events, as well as * unregistering actions and clearing event subscriptions. * - * @param options + * @param options - The controller options. * @param options.controllerMessenger - The controller messenger instance that is being wrapped. * @param options.name - The name of the thing this messenger will be handed to (e.g. the - * controller name). This grants "ownership" of actions and events under this namespace to the - * restricted controller messenger returned. + * controller name). This grants "ownership" of actions and events under this namespace to the + * restricted controller messenger returned. * @param options.allowedActions - The list of actions that this restricted controller messenger - * should be alowed to call. + * should be alowed to call. * @param options.allowedEvents - The list of events that this restricted controller messenger - * should be allowed to subscribe to. + * should be allowed to subscribe to. */ constructor({ controllerMessenger, @@ -142,9 +142,9 @@ export class RestrictedControllerMessenger< * * The action type this handler is registered under *must* be in the current namespace. * - * @param actionType - The action type. This is a unqiue identifier for this action. - * @param handler- The action handler. This function gets called when the `call` method is - * invoked with the given action type. + * @param action - The action type. This is a unqiue identifier for this action. + * @param handler - The action handler. This function gets called when the `call` method is + * invoked with the given action type. * @throws Will throw when a handler has been registered for this action type already. * @template T - A type union of Action type strings that are namespaced by N. */ @@ -168,7 +168,7 @@ export class RestrictedControllerMessenger< * * The action type being unregistered *must* be in the current namespace. * - * @param actionType - The action type. This is a unqiue identifier for this action. + * @param action - The action type. This is a unqiue identifier for this action. * @template T - A type union of Action type strings that are namespaced by N. */ unregisterActionHandler>(action: T) { @@ -189,11 +189,12 @@ export class RestrictedControllerMessenger< * * The action type being called must be on the action allowlist. * - * @param actionType - The action type. This is a unqiue identifier for this action. + * @param action - The action type. This is a unqiue identifier for this action. * @param params - The action parameters. These must match the type of the parameters of the - * registered action handler. + * registered action handler. * @throws Will throw when no handler has been registered for the given type. * @template T - A type union of allowed Action type strings. + * @returns The action return value. */ call( action: T, @@ -215,9 +216,9 @@ export class RestrictedControllerMessenger< * * The event type being published *must* be in the current namespace. * - * @param eventType - The event type. This is a unique identifier for this event. + * @param event - The event type. This is a unique identifier for this event. * @param payload - The event payload. The type of the parameters for each event handler must - * match the type of this payload. + * match the type of this payload. * @template E - A type union of Event type strings that are namespaced by N. */ publish>( @@ -242,7 +243,7 @@ export class RestrictedControllerMessenger< * * @param eventType - The event type. This is a unique identifier for this event. * @param handler - The event handler. The type of the parameters for this event handler must - * match the type of the payload for this event type. + * match the type of the payload for this event type. * @template E - A type union of Event type strings. */ subscribe( @@ -300,7 +301,7 @@ export class RestrictedControllerMessenger< * * The event type being unsubscribed to must be on the event allowlist. * - * @param eventType - The event type. This is a unique identifier for this event. + * @param event - The event type. This is a unique identifier for this event. * @param handler - The event handler to unregister. * @throws Will throw when the given event handler is not registered for this event. * @template T - A type union of allowed Event type strings. @@ -325,7 +326,7 @@ export class RestrictedControllerMessenger< * * The event type being cleared *must* be in the current namespace. * - * @param eventType - The event type. This is a unique identifier for this event. + * @param event - The event type. This is a unique identifier for this event. * @template E - A type union of Event type strings that are namespaced by N. */ clearEventSubscriptions>(event: E) { @@ -371,8 +372,8 @@ export class ControllerMessenger< * This will make the registered function available to call via the `call` method. * * @param actionType - The action type. This is a unqiue identifier for this action. - * @param handler- The action handler. This function gets called when the `call` method is - * invoked with the given action type. + * @param handler - The action handler. This function gets called when the `call` method is + * invoked with the given action type. * @throws Will throw when a handler has been registered for this action type already. * @template T - A type union of Action type strings. */ @@ -417,9 +418,10 @@ export class ControllerMessenger< * * @param actionType - The action type. This is a unqiue identifier for this action. * @param params - The action parameters. These must match the type of the parameters of the - * registered action handler. + * registered action handler. * @throws Will throw when no handler has been registered for the given type. * @template T - A type union of Action type strings. + * @returns The action return value. */ call( actionType: T, @@ -439,7 +441,7 @@ export class ControllerMessenger< * * @param eventType - The event type. This is a unique identifier for this event. * @param payload - The event payload. The type of the parameters for each event handler must - * match the type of this payload. + * match the type of this payload. * @template E - A type union of Event type strings. */ publish( @@ -472,7 +474,7 @@ export class ControllerMessenger< * * @param eventType - The event type. This is a unique identifier for this event. * @param handler - The event handler. The type of the parameters for this event handler must - * match the type of the payload for this event type. + * match the type of the payload for this event type. * @template E - A type union of Event type strings. */ subscribe( @@ -575,19 +577,20 @@ export class ControllerMessenger< * that namespace. Ownership allows registering actions and publishing events, as well as * unregistering actions and clearing event subscriptions. * - * @param options + * @param options - Controller messenger options. * @param options.name - The name of the thing this messenger will be handed to (e.g. the - * controller name). This grants "ownership" of actions and events under this namespace to the - * restricted controller messenger returned. + * controller name). This grants "ownership" of actions and events under this namespace to the + * restricted controller messenger returned. * @param options.allowedActions - The list of actions that this restricted controller messenger - * should be alowed to call. + * should be alowed to call. * @param options.allowedEvents - The list of events that this restricted controller messenger - * should be allowed to subscribe to. + * should be allowed to subscribe to. * @template N - The namespace for this messenger. Typically this is the name of the controller or - * module that this messenger has been created for. The authority to publish events and register - * actions under this namespace is granted to this restricted messenger instance. + * module that this messenger has been created for. The authority to publish events and register + * actions under this namespace is granted to this restricted messenger instance. * @template AllowedAction - A type union of the 'type' string for any allowed actions. * @template AllowedEvent - A type union of the 'type' string for any allowed events. + * @returns The restricted controller messenger. */ getRestricted< N extends string, diff --git a/src/apis/crypto-compare.ts b/src/apis/crypto-compare.ts index 7576a3deed..0266bd24e6 100644 --- a/src/apis/crypto-compare.ts +++ b/src/apis/crypto-compare.ts @@ -1,5 +1,16 @@ import { handleFetch } from '../util'; +/** + * Get the CryptoCompare API URL for getting the conversion rate from the given native currency to + * the given currency. Optionally, the conversion rate from the native currency to USD can also be + * included in the response. + * + * @param currentCurrency - The currency to get a conversion rate for. + * @param nativeCurrency - The native currency to convert from. + * @param includeUSDRate - Whether or not the native currency to USD conversion rate should be + * included in the response as well. + * @returns The API URL for getting the conversion rate. + */ function getPricingURL( currentCurrency: string, nativeCurrency: string, @@ -13,12 +24,12 @@ function getPricingURL( } /** - * Fetches the exchange rate for a given currency + * Fetches the exchange rate for a given currency. * - * @param currency - ISO 4217 currency code - * @param nativeCurrency - Symbol for base asset - * @param includeUSDRate - Whether to add the USD rate to the fetch - * @returns - Promise resolving to exchange rate for given currency + * @param currency - ISO 4217 currency code. + * @param nativeCurrency - Symbol for base asset. + * @param includeUSDRate - Whether to add the USD rate to the fetch. + * @returns Promise resolving to exchange rate for given currency. */ export async function fetchExchangeRate( currency: string, @@ -32,7 +43,7 @@ export async function fetchExchangeRate( getPricingURL(currency, nativeCurrency, includeUSDRate), ); - /* + /* Example expected error response (if pair is not found) { Response: "Error", diff --git a/src/apis/token-service.ts b/src/apis/token-service.ts index 9129cddbca..34ae20c3e9 100644 --- a/src/apis/token-service.ts +++ b/src/apis/token-service.ts @@ -2,10 +2,23 @@ import { timeoutFetch } from '../util'; const END_POINT = 'https://token-api.metaswap.codefi.network'; +/** + * Get the tokens URL for a specific network. + * + * @param chainId - The chain ID of the network the tokens requested are on. + * @returns The tokens URL. + */ function getTokensURL(chainId: string) { return `${END_POINT}/tokens/${chainId}`; } +/** + * Get the token metadata URL for the given network and token. + * + * @param chainId - The chain ID of the network the token is on. + * @param tokenAddress - The token address. + * @returns The token metadata URL. + */ function getTokenMetadataURL(chainId: string, tokenAddress: string) { return `${END_POINT}/token/${chainId}?address=${tokenAddress}`; } @@ -15,9 +28,12 @@ function getTokenMetadataURL(chainId: string, tokenAddress: string) { const timeout = 10000; /** - * Fetches the list of token metadata for a given network chainId + * Fetch the list of token metadata for a given network. This request is cancellable using the + * abort signal passed in. * - * @returns - Promise resolving token List + * @param chainId - The chain ID of the network the requested tokens are on. + * @param abortSignal - The abort signal used to cancel the request if necessary. + * @returns The token list, or `undefined` if the request was cancelled. */ export async function fetchTokenList( chainId: string, @@ -32,9 +48,13 @@ export async function fetchTokenList( } /** - * Fetch metadata for the token address provided for a given network chainId + * Fetch metadata for the token address provided for a given network. This request is cancellable + * using the abort signal passed in. * - * @return Promise resolving token metadata for the tokenAddress provided + * @param chainId - The chain ID of the network the token is on. + * @param tokenAddress - The address of the token to fetch metadata for. + * @param abortSignal - The abort signal used to cancel the request if necessary. + * @returns The token metadata, or `undefined` if the request was cancelled. */ export async function fetchTokenMetadata( chainId: string, @@ -50,9 +70,11 @@ export async function fetchTokenMetadata( } /** - * Perform fetch request against the api + * Perform fetch request against the api. * - * @return Promise resolving request response + * @param apiURL - The URL of the API to fetch. + * @param abortSignal - The abort signal used to cancel the request if necessary. + * @returns Promise resolving request response. */ async function queryApi( apiURL: string, @@ -79,9 +101,11 @@ async function queryApi( } /** - * Parse response + * Parse an API response and return the response JSON data. * - * @return Promise resolving request response json value + * @param apiResponse - The API response to parse. + * @returns The response JSON data. + * @throws Will throw if the response includes an error. */ async function parseJsonResponse(apiResponse: Response): Promise { const responseObj = await apiResponse.json(); diff --git a/src/approval/ApprovalController.test.js b/src/approval/ApprovalController.test.js index e0d8319591..6120c41281 100644 --- a/src/approval/ApprovalController.test.js +++ b/src/approval/ApprovalController.test.js @@ -2,6 +2,11 @@ const { errorCodes } = require('eth-rpc-errors'); const { ControllerMessenger } = require('../ControllerMessenger'); const { ApprovalController } = require('./ApprovalController'); +/** + * Constructs a restricted controller messenger. + * + * @returns {object} A restricted controller messenger. + */ function getRestrictedMessenger() { const controllerMessenger = new ControllerMessenger(); const messenger = controllerMessenger.getRestricted({ @@ -170,22 +175,47 @@ describe('ApprovalController: Input Validation', () => { // helpers +/** + * Get an invalid ID error. + * + * @returns {Error} An invalid ID error. + */ function getInvalidIdError() { return getError('Must specify non-empty string id.', errorCodes.rpc.internal); } +/** + * Get an invalid ID type error. + * + * @returns {Error} An invalid ID type error. + */ function getInvalidHasIdError() { return getError('May not specify non-string id.'); } +/** + * Get an invalid origin type error. + * + * @returns {Error} The invalid origin type error. + */ function getInvalidHasOriginError() { return getError('May not specify non-string origin.'); } +/** + * Get an invalid type error. + * + * @returns {Error} The invalid type error. + */ function getInvalidHasTypeError() { return getError('May not specify non-string type.'); } +/** + * Get an invalid origin error. + * + * @returns {Error} The invalid origin error. + */ function getInvalidOriginError() { return getError( 'Must specify non-empty string origin.', @@ -193,6 +223,11 @@ function getInvalidOriginError() { ); } +/** + * Get an invalid request data error. + * + * @returns {Error} The invalid request data error. + */ function getInvalidRequestDataError() { return getError( 'Request data must be a plain object if specified.', @@ -200,18 +235,41 @@ function getInvalidRequestDataError() { ); } +/** + * Get an invalid type error. + * + * @param {number} code - The error code. + * @returns {Error} The invalid type error. + */ function getInvalidTypeError(code) { return getError('Must specify non-empty string type.', code); } +/** + * Get an invalid params error. + * + * @returns {Error} The invalid params error. + */ function getInvalidHasParamsError() { return getError('Must specify a valid combination of id, origin, and type.'); } +/** + * Get an invalid approval count params error. + * + * @returns {Error} The invalid approval count params error. + */ function getApprovalCountParamsError() { return getError('Must specify origin, type, or both.'); } +/** + * Get an Error. + * + * @param {string} message - The error message. + * @param {number} code - The error code. + * @returns {Error} An Error. + */ function getError(message, code) { const err = { name: 'Error', diff --git a/src/approval/ApprovalController.test.ts b/src/approval/ApprovalController.test.ts index 4c0cea0e7f..3dd6d1fd7d 100644 --- a/src/approval/ApprovalController.test.ts +++ b/src/approval/ApprovalController.test.ts @@ -14,6 +14,11 @@ const TYPE = 'TYPE'; const controllerName = 'ApprovalController'; +/** + * Constructs a restricted controller messenger. + * + * @returns A restricted controller messenger. + */ function getRestrictedMessenger() { const controllerMessenger = new ControllerMessenger< ApprovalControllerActions, @@ -656,6 +661,12 @@ describe('approval controller', () => { // helpers +/** + * Get an ID collision error. + * + * @param id - The ID with a collision. + * @returns The ID collision error. + */ function getIdCollisionError(id: string) { return getError( `Approval request with id '${id}' already exists.`, @@ -663,15 +674,35 @@ function getIdCollisionError(id: string) { ); } +/** + * Get an origin type collision error. + * + * @param origin - The origin. + * @param type - The type. + * @returns An origin type collision error. + */ function getOriginTypeCollisionError(origin: string, type = TYPE) { const message = `Request of type '${type}' already pending for origin ${origin}. Please wait.`; return getError(message, errorCodes.rpc.resourceUnavailable); } +/** + * Get an "ID not found" error. + * + * @param id - The ID that was not found. + * @returns An "ID not found" error. + */ function getIdNotFoundError(id: string) { return getError(`Approval request with id '${id}' not found.`); } +/** + * Get an error. + * + * @param message - The error message. + * @param code - The error code. + * @returns An Error. + */ function getError(message: string, code?: number) { const err: any = { name: 'Error', diff --git a/src/approval/ApprovalController.ts b/src/approval/ApprovalController.ts index a35ecfdf13..0939d01bd5 100644 --- a/src/approval/ApprovalController.ts +++ b/src/approval/ApprovalController.ts @@ -157,9 +157,13 @@ export class ApprovalController extends BaseController< private _showApprovalRequest: () => void; /** - * @param opts - Options bag - * @param opts.showApprovalRequest - Function for opening the UI such that + * Construct an Approval controller. + * + * @param options - The controller options. + * @param options.showApprovalRequest - Function for opening the UI such that * the request can be displayed to the user. + * @param options.messenger - The restricted controller messenger for the Approval controller. + * @param options.state - The initial controller state. */ constructor({ messenger, @@ -281,6 +285,7 @@ export class ApprovalController extends BaseController< * regardless of origin. * If both `origin` and `type` are specified, 0 or 1 will be returned. * + * @param opts - The approval count options. * @param opts.origin - An approval origin. * @param opts.type - The type of the approval request. * @returns The current approval request count for the given origin and/or @@ -311,8 +316,9 @@ export class ApprovalController extends BaseController< } /** - * @returns The current total approval request count, for all types and - * origins. + * Get the total count of all pending approval requests for all origins. + * + * @returns The total pending approval request count. */ getTotalApprovalCount(): number { return this.state.pendingApprovalCount; diff --git a/src/assets/AccountTrackerController.ts b/src/assets/AccountTrackerController.ts index d3339aaea0..176a8d5feb 100644 --- a/src/assets/AccountTrackerController.ts +++ b/src/assets/AccountTrackerController.ts @@ -8,7 +8,6 @@ import { BNToHex, query, safelyExecuteWithTimeout } from '../util'; * @type AccountInformation * * Account information object - * * @property balance - Hex string of an account balancec in wei */ export interface AccountInformation { @@ -19,7 +18,6 @@ export interface AccountInformation { * @type AccountTrackerConfig * * Account tracker controller configuration - * * @property provider - Provider used to create a new underlying EthQuery instance */ export interface AccountTrackerConfig extends BaseConfig { @@ -31,7 +29,6 @@ export interface AccountTrackerConfig extends BaseConfig { * @type AccountTrackerState * * Account tracker controller state - * * @property accounts - Map of addresses to account information */ export interface AccountTrackerState extends BaseState { @@ -79,13 +76,13 @@ export class AccountTrackerController extends BaseController< private getIdentities: () => PreferencesState['identities']; /** - * Creates an AccountTracker instance + * Creates an AccountTracker instance. * - * @param options - * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes - * @param options.getIdentities - Gets the identities from the Preferences store - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param options - The controller options. + * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes. + * @param options.getIdentities - Gets the identities from the Preferences store. + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( { @@ -114,11 +111,11 @@ export class AccountTrackerController extends BaseController< } /** - * Sets a new provider + * Sets a new provider. * - * TODO: Replace this wth a method + * TODO: Replace this wth a method. * - * @param provider - Provider used to create a new underlying EthQuery instance + * @param provider - Provider used to create a new underlying EthQuery instance. */ set provider(provider: any) { this.ethQuery = new EthQuery(provider); @@ -129,9 +126,9 @@ export class AccountTrackerController extends BaseController< } /** - * Starts a new polling interval + * Starts a new polling interval. * - * @param interval - Polling interval trigger a 'refresh' + * @param interval - Polling interval trigger a 'refresh'. */ async poll(interval?: number): Promise { const releaseLock = await this.mutex.acquire(); @@ -145,7 +142,7 @@ export class AccountTrackerController extends BaseController< } /** - * Refreshes all accounts in the current keychain + * Refreshes all accounts in the current keychain. */ refresh = async () => { this.syncAccounts(); diff --git a/src/assets/AssetsContractController.ts b/src/assets/AssetsContractController.ts index 40dbe80ed4..1dc8caf564 100644 --- a/src/assets/AssetsContractController.ts +++ b/src/assets/AssetsContractController.ts @@ -14,7 +14,6 @@ const SINGLE_CALL_BALANCES_ADDRESS = * @type AssetsContractConfig * * Assets Contract controller configuration - * * @property provider - Provider used to create a new web3 instance */ export interface AssetsContractConfig extends BaseConfig { @@ -25,7 +24,6 @@ export interface AssetsContractConfig extends BaseConfig { * @type BalanceMap * * Key value object containing the balance for each tokenAddress - * * @property [tokenAddress] - Address of the token */ export interface BalanceMap { @@ -42,12 +40,11 @@ export class AssetsContractController extends BaseController< private web3: any; /** + * Query if a contract implements an interface. * - * Query if a contract implements an interface - * - * @param address - Asset contract address - * @param interfaceId - Interface identifier - * @returns - Promise resolving to whether the contract implements `interfaceID` + * @param address - Asset contract address. + * @param interfaceId - Interface identifier. + * @returns Promise resolving to whether the contract implements `interfaceID`. */ private async contractSupportsInterface( address: string, @@ -75,10 +72,10 @@ export class AssetsContractController extends BaseController< name = 'AssetsContractController'; /** - * Creates a AssetsContractController instance + * Creates a AssetsContractController instance. * - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( config?: Partial, @@ -92,9 +89,9 @@ export class AssetsContractController extends BaseController< } /** - * Sets a new provider + * Sets a new provider. * - * TODO: Replace this wth a method + * TODO: Replace this wth a method. * * @property provider - Provider used to create a new underlying Web3 instance */ @@ -107,20 +104,20 @@ export class AssetsContractController extends BaseController< } /** - * Query if contract implements ERC721Metadata interface + * Query if contract implements ERC721Metadata interface. * - * @param address - ERC721 asset contract address - * @returns - Promise resolving to whether the contract implements ERC721Metadata interface + * @param address - ERC721 asset contract address. + * @returns Promise resolving to whether the contract implements ERC721Metadata interface. */ async contractSupportsMetadataInterface(address: string): Promise { return this.contractSupportsInterface(address, ERC721METADATA_INTERFACE_ID); } /** - * Query if contract implements ERC721Enumerable interface + * Query if contract implements ERC721Enumerable interface. * - * @param address - ERC721 asset contract address - * @returns - Promise resolving to whether the contract implements ERC721Enumerable interface + * @param address - ERC721 asset contract address. + * @returns Promise resolving to whether the contract implements ERC721Enumerable interface. */ async contractSupportsEnumerableInterface(address: string): Promise { return this.contractSupportsInterface( @@ -130,11 +127,11 @@ export class AssetsContractController extends BaseController< } /** - * Get balance or count for current account on specific asset contract + * Get balance or count for current account on specific asset contract. * - * @param address - Asset contract address - * @param selectedAddress - Current account public address - * @returns - Promise resolving to BN object containing balance for current account on specific asset contract + * @param address - Asset contract address. + * @param selectedAddress - Current account public address. + * @returns Promise resolving to BN object containing balance for current account on specific asset contract. */ async getBalanceOf(address: string, selectedAddress: string): Promise { const contract = this.web3.eth.contract(abiERC20).at(address); @@ -151,12 +148,12 @@ export class AssetsContractController extends BaseController< } /** - * Enumerate assets assigned to an owner + * Enumerate assets assigned to an owner. * - * @param address - ERC721 asset contract address - * @param selectedAddress - Current account public address - * @param index - A collectible counter less than `balanceOf(selectedAddress)` - * @returns - Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress' + * @param address - ERC721 asset contract address. + * @param selectedAddress - Current account public address. + * @param index - A collectible counter less than `balanceOf(selectedAddress)`. + * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'. */ getCollectibleTokenId( address: string, @@ -181,11 +178,11 @@ export class AssetsContractController extends BaseController< } /** - * Query for tokenURI for a given asset + * Query for tokenURI for a given asset. * - * @param address - ERC721 asset contract address - * @param tokenId - ERC721 asset identifier - * @returns - Promise resolving to the 'tokenURI' + * @param address - ERC721 asset contract address. + * @param tokenId - ERC721 asset identifier. + * @returns Promise resolving to the 'tokenURI'. */ async getCollectibleTokenURI( address: string, @@ -211,10 +208,10 @@ export class AssetsContractController extends BaseController< } /** - * Query for name for a given ERC20 asset + * Query for name for a given ERC20 asset. * - * @param address - ERC20 asset contract address - * @returns - Promise resolving to the 'decimals' + * @param address - ERC20 asset contract address. + * @returns Promise resolving to the 'decimals'. */ async getTokenDecimals(address: string): Promise { const contract = this.web3.eth.contract(abiERC20).at(address); @@ -231,10 +228,10 @@ export class AssetsContractController extends BaseController< } /** - * Query for name for a given asset + * Query for name for a given asset. * - * @param address - ERC721 or ERC20 asset contract address - * @returns - Promise resolving to the 'name' + * @param address - ERC721 or ERC20 asset contract address. + * @returns Promise resolving to the 'name'. */ async getAssetName(address: string): Promise { const contract = this.web3.eth.contract(abiERC721).at(address); @@ -251,10 +248,10 @@ export class AssetsContractController extends BaseController< } /** - * Query for symbol for a given asset + * Query for symbol for a given asset. * - * @param address - ERC721 or ERC20 asset contract address - * @returns - Promise resolving to the 'symbol' + * @param address - ERC721 or ERC20 asset contract address. + * @returns Promise resolving to the 'symbol'. */ async getAssetSymbol(address: string): Promise { const contract = this.web3.eth.contract(abiERC721).at(address); @@ -271,11 +268,11 @@ export class AssetsContractController extends BaseController< } /** - * Query for owner for a given ERC721 asset + * Query for owner for a given ERC721 asset. * - * @param address - ERC721 asset contract address - * @param tokenId - ERC721 asset identifier - * @returns - Promise resolving to the owner address + * @param address - ERC721 asset contract address. + * @param tokenId - ERC721 asset identifier. + * @returns Promise resolving to the owner address. */ async getOwnerOf(address: string, tokenId: number): Promise { const contract = this.web3.eth.contract(abiERC721).at(address); @@ -292,9 +289,12 @@ export class AssetsContractController extends BaseController< } /** - * Returns contract instance of + * Get the token balance for a list of token addresses in a single call. Only non-zero balances + * are returned. * - * @returns - Promise resolving to the 'tokenURI' + * @param selectedAddress - The address to check token balances for. + * @param tokensToDetect - The token addresses to detect balances for. + * @returns The list of non-zero token balances. */ async getBalancesInSingleCall( selectedAddress: string, diff --git a/src/assets/AssetsDetectionController.test.ts b/src/assets/AssetsDetectionController.test.ts index 8a0fb239a5..64e6e73271 100644 --- a/src/assets/AssetsDetectionController.test.ts +++ b/src/assets/AssetsDetectionController.test.ts @@ -85,6 +85,12 @@ const sampleTokenList = [ ], }, ]; + +/** + * Constructs a restricted controller messenger. + * + * @returns A restricted controller messenger. + */ function getTokenListMessenger() { const controllerMessenger = new ControllerMessenger< GetTokenListState, diff --git a/src/assets/AssetsDetectionController.ts b/src/assets/AssetsDetectionController.ts index 3824dfce4c..90d821737a 100644 --- a/src/assets/AssetsDetectionController.ts +++ b/src/assets/AssetsDetectionController.ts @@ -19,7 +19,6 @@ const DEFAULT_INTERVAL = 180000; * @type ApiCollectible * * Collectible object coming from OpenSea api - * * @property token_id - The collectible identifier * @property num_sales - Number of sales * @property background_color - The background color to be displayed with the item @@ -58,7 +57,6 @@ export interface ApiCollectible { * @type ApiCollectibleContract * * Collectible contract object coming from OpenSea api - * * @property address - Address of the collectible contract * @property asset_contract_type - The collectible type, it could be `semi-fungible` or `non-fungible` * @property created_date - Creation date @@ -87,7 +85,6 @@ export interface ApiCollectibleContract { * @type ApiCollectibleLastSale * * Collectible sale object coming from OpenSea api - * * @property event_timestamp - Object containing a `username` * @property total_price - URI of collectible image associated with this owner * @property transaction - Object containing transaction_hash and block_hash @@ -102,7 +99,6 @@ export interface ApiCollectibleLastSale { * @type ApiCollectibleCreator * * Collectible creator object coming from OpenSea api - * * @property user - Object containing a `username` * @property profile_img_url - URI of collectible image associated with this owner * @property address - The owner address @@ -117,7 +113,6 @@ export interface ApiCollectibleCreator { * @type AssetsConfig * * Assets controller configuration - * * @property interval - Polling interval used to fetch new token rates * @property networkType - Network type ID as per net_version * @property selectedAddress - Vault selected address @@ -192,22 +187,22 @@ export class AssetsDetectionController extends BaseController< private getTokenListState: () => TokenListState; /** - * Creates a AssetsDetectionController instance + * Creates a AssetsDetectionController instance. * - * @param options - * @param options.onCollectiblesStateChange - Allows subscribing to assets controller state changes - * @param options.onTokensStateChange - Allows subscribing to tokens controller state changes - * @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes - * @param options.onNetworkStateChange - Allows subscribing to network controller state changes - * @param options.getOpenSeaApiKey - Gets the OpenSea API key, if one is set - * @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address - * @param options.addTokens - Add a list of tokens - * @param options.addCollectible - Add a collectible - * @param options.getCollectiblesState - Gets the current state of the Assets controller - * @param options.getTokenListState - Gets the current state of the TokenList controller - * @param options.getTokensState - Gets the current state of the Tokens controller - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param options - The controller options. + * @param options.onCollectiblesStateChange - Allows subscribing to assets controller state changes. + * @param options.onTokensStateChange - Allows subscribing to tokens controller state changes. + * @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes. + * @param options.onNetworkStateChange - Allows subscribing to network controller state changes. + * @param options.getOpenSeaApiKey - Gets the OpenSea API key, if one is set. + * @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address. + * @param options.addTokens - Add a list of tokens. + * @param options.addCollectible - Add a collectible. + * @param options.getCollectiblesState - Gets the current state of the Assets controller. + * @param options.getTokenListState - Gets the current state of the TokenList controller. + * @param options.getTokensState - Gets the current state of the Tokens controller. + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( { @@ -279,9 +274,9 @@ export class AssetsDetectionController extends BaseController< } /** - * Starts a new polling interval + * Starts a new polling interval. * - * @param interval - Polling interval used to auto detect assets + * @param interval - Polling interval used to auto detect assets. */ async poll(interval?: number): Promise { interval && this.configure({ interval }, false, false); @@ -293,9 +288,9 @@ export class AssetsDetectionController extends BaseController< } /** - * Checks whether network is mainnet or not + * Checks whether network is mainnet or not. * - * @returns - Whether current network is mainnet + * @returns Whether current network is mainnet. */ isMainnet() { if (this.config.networkType !== MAINNET || this.disabled) { @@ -305,7 +300,7 @@ export class AssetsDetectionController extends BaseController< } /** - * Detect assets owned by current account on mainnet + * Detect assets owned by current account on mainnet. */ async detectAssets() { /* istanbul ignore if */ @@ -317,7 +312,7 @@ export class AssetsDetectionController extends BaseController< } /** - * Triggers asset ERC20 token auto detection for each contract address in contract metadata on mainnet + * Triggers asset ERC20 token auto detection for each contract address in contract metadata on mainnet. */ async detectTokens() { /* istanbul ignore if */ @@ -390,8 +385,8 @@ export class AssetsDetectionController extends BaseController< } /** - * Triggers asset ERC721 token auto detection on mainnet - * adding new collectibles and removing not owned collectibles + * Triggers asset ERC721 token auto detection on mainnet. Any newly detected collectibles are + * added. */ async detectCollectibles() { /* istanbul ignore if */ diff --git a/src/assets/CollectiblesController.ts b/src/assets/CollectiblesController.ts index d9da0dc019..eb9a1e1155 100644 --- a/src/assets/CollectiblesController.ts +++ b/src/assets/CollectiblesController.ts @@ -18,7 +18,6 @@ import { compareCollectiblesMetadata } from './assetsUtil'; * @type Collectible * * Collectible representation - * * @property address - Hex address of a ERC721 contract * @property description - The collectible description * @property image - URI of custom collectible image associated with this tokenId @@ -43,7 +42,6 @@ export interface Collectible extends CollectibleMetadata { * @type CollectibleContract * * Collectible contract information representation - * * @property name - Contract name * @property logo - Contract logo * @property address - Contract address @@ -72,7 +70,6 @@ export interface CollectibleContract { * @type CollectibleMetadata * * Collectible custom information - * * @property name - Collectible custom name * @property description - The collectible description * @property numberOfSales - Number of sales @@ -106,7 +103,6 @@ export interface CollectibleMetadata { * @type CollectiblesConfig * * Collectibles controller configuration - * * @property networkType - Network ID as per net_version * @property selectedAddress - Vault selected address */ @@ -120,7 +116,6 @@ export interface CollectiblesConfig extends BaseConfig { * @type CollectiblesState * * Assets controller state - * * @property allCollectibleContracts - Object containing collectibles contract information * @property allCollectibles - Object containing collectibles per account and network * @property collectibleContracts - List of collectibles contracts associated with the active vault @@ -155,11 +150,11 @@ export class CollectiblesController extends BaseController< } /** - * Request individual collectible information from OpenSea api + * Request individual collectible information from OpenSea API. * - * @param contractAddress - Hex address of the collectible contract - * @param tokenId - The collectible identifier - * @returns - Promise resolving to the current collectible name and image + * @param contractAddress - Hex address of the collectible contract. + * @param tokenId - The collectible identifier. + * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleInformationFromApi( contractAddress: string, @@ -215,11 +210,11 @@ export class CollectiblesController extends BaseController< } /** - * Request individual collectible information from contracts that follows Metadata Interface + * Request individual collectible information from contracts that follows Metadata Interface. * - * @param contractAddress - Hex address of the collectible contract - * @param tokenId - The collectible identifier - * @returns - Promise resolving to the current collectible name and image + * @param contractAddress - Hex address of the collectible contract. + * @param tokenId - The collectible identifier. + * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleInformationFromTokenURI( contractAddress: string, @@ -237,11 +232,11 @@ export class CollectiblesController extends BaseController< } /** - * Request individual collectible information (name, image url and description) + * Request individual collectible information (name, image url and description). * - * @param contractAddress - Hex address of the collectible contract - * @param tokenId - The collectible identifier - * @returns - Promise resolving to the current collectible name and image + * @param contractAddress - Hex address of the collectible contract. + * @param tokenId - The collectible identifier. + * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleInformation( contractAddress: string, @@ -277,10 +272,10 @@ export class CollectiblesController extends BaseController< } /** - * Request collectible contract information from OpenSea api + * Request collectible contract information from OpenSea API. * - * @param contractAddress - Hex address of the collectible contract - * @returns - Promise resolving to the current collectible name and image + * @param contractAddress - Hex address of the collectible contract. + * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleContractInformationFromApi( contractAddress: string, @@ -299,10 +294,10 @@ export class CollectiblesController extends BaseController< } /** - * Request collectible contract information from the contract itself + * Request collectible contract information from the contract itself. * - * @param contractAddress - Hex address of the collectible contract - * @returns - Promise resolving to the current collectible name and image + * @param contractAddress - Hex address of the collectible contract. + * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleContractInformationFromContract( contractAddress: string, @@ -324,10 +319,10 @@ export class CollectiblesController extends BaseController< } /** - * Request collectible contract information from OpenSea api + * Request collectible contract information from OpenSea API. * - * @param contractAddress - Hex address of the collectible contract - * @returns - Promise resolving to the collectible contract name, image and description + * @param contractAddress - Hex address of the collectible contract. + * @returns Promise resolving to the collectible contract name, image and description. */ private async getCollectibleContractInformation( contractAddress: string, @@ -370,12 +365,12 @@ export class CollectiblesController extends BaseController< } /** - * Adds an individual collectible to the stored collectible list + * Adds an individual collectible to the stored collectible list. * - * @param address - Hex address of the collectible contract - * @param tokenId - The collectible identifier - * @param opts - Collectible optional information (name, image and description) - * @returns - Promise resolving to the current collectible list + * @param address - Hex address of the collectible contract. + * @param tokenId - The collectible identifier. + * @param collectibleMetadata - Collectible optional information (name, image and description). + * @returns Promise resolving to the current collectible list. */ private async addIndividualCollectible( address: string, @@ -443,11 +438,11 @@ export class CollectiblesController extends BaseController< } /** - * Adds a collectible contract to the stored collectible contracts list + * Adds a collectible contract to the stored collectible contracts list. * - * @param address - Hex address of the collectible contract - * @param detection? - Whether the collectible is manually added or auto-detected - * @returns - Promise resolving to the current collectible contracts list + * @param address - Hex address of the collectible contract. + * @param detection - Whether the collectible is manually added or auto-detected. + * @returns Promise resolving to the current collectible contracts list. */ private async addCollectibleContract( address: string, @@ -524,10 +519,10 @@ export class CollectiblesController extends BaseController< } /** - * Removes an individual collectible from the stored token list and saves it in ignored collectibles list + * Removes an individual collectible from the stored token list and saves it in ignored collectibles list. * - * @param address - Hex address of the collectible contract - * @param tokenId - Token identifier of the collectible + * @param address - Hex address of the collectible contract. + * @param tokenId - Token identifier of the collectible. */ private removeAndIgnoreIndividualCollectible( address: string, @@ -567,10 +562,10 @@ export class CollectiblesController extends BaseController< } /** - * Removes an individual collectible from the stored token list + * Removes an individual collectible from the stored token list. * - * @param address - Hex address of the collectible contract - * @param tokenId - Token identifier of the collectible + * @param address - Hex address of the collectible contract. + * @param tokenId - Token identifier of the collectible. */ private removeIndividualCollectible(address: string, tokenId: number) { address = toChecksumHexAddress(address); @@ -599,10 +594,10 @@ export class CollectiblesController extends BaseController< } /** - * Removes a collectible contract to the stored collectible contracts list + * Removes a collectible contract to the stored collectible contracts list. * - * @param address - Hex address of the collectible contract - * @returns - Promise resolving to the current collectible contracts list + * @param address - Hex address of the collectible contract. + * @returns Promise resolving to the current collectible contracts list. */ private removeCollectibleContract(address: string): CollectibleContract[] { address = toChecksumHexAddress(address); @@ -651,16 +646,16 @@ export class CollectiblesController extends BaseController< private getCollectibleTokenURI: AssetsContractController['getCollectibleTokenURI']; /** - * Creates a CollectiblesController instance + * Creates a CollectiblesController instance. * - * @param options - * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes - * @param options.onNetworkStateChange - Allows subscribing to network controller state changes - * @param options.getAssetName - Gets the name of the asset at the given address - * @param options.getAssetSymbol - Gets the symbol of the asset at the given address - * @param options.getCollectibleTokenURI - Gets the URI of the NFT at the given address, with the given ID - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param options - The controller options. + * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes. + * @param options.onNetworkStateChange - Allows subscribing to network controller state changes. + * @param options.getAssetName - Gets the name of the asset at the given address. + * @param options.getAssetSymbol - Gets the symbol of the asset at the given address. + * @param options.getCollectibleTokenURI - Gets the URI of the NFT at the given address, with the given ID. + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( { @@ -726,22 +721,22 @@ export class CollectiblesController extends BaseController< } /** - * Sets an OpenSea API key to retrieve collectible information + * Sets an OpenSea API key to retrieve collectible information. * - * @param openSeaApiKey - OpenSea API key + * @param openSeaApiKey - OpenSea API key. */ setApiKey(openSeaApiKey: string) { this.openSeaApiKey = openSeaApiKey; } /** - * Adds a collectible and respective collectible contract to the stored collectible and collectible contracts lists + * Adds a collectible and respective collectible contract to the stored collectible and collectible contracts lists. * - * @param address - Hex address of the collectible contract - * @param tokenId - The collectible identifier - * @param collectibleMetadata - Collectible optional metadata - * @param detection? - Whether the collectible is manually added or autodetected - * @returns - Promise resolving to the current collectible list + * @param address - Hex address of the collectible contract. + * @param tokenId - The collectible identifier. + * @param collectibleMetadata - Collectible optional metadata. + * @param detection - Whether the collectible is manually added or autodetected. + * @returns Promise resolving to the current collectible list. */ async addCollectible( address: string, @@ -774,10 +769,10 @@ export class CollectiblesController extends BaseController< } /** - * Removes a collectible from the stored token list + * Removes a collectible from the stored token list. * - * @param address - Hex address of the collectible contract - * @param tokenId - Token identifier of the collectible + * @param address - Hex address of the collectible contract. + * @param tokenId - Token identifier of the collectible. */ removeCollectible(address: string, tokenId: number) { address = toChecksumHexAddress(address); @@ -793,10 +788,10 @@ export class CollectiblesController extends BaseController< } /** - * Removes a collectible from the stored token list and saves it in ignored collectibles list + * Removes a collectible from the stored token list and saves it in ignored collectibles list. * - * @param address - Hex address of the collectible contract - * @param tokenId - Token identifier of the collectible + * @param address - Hex address of the collectible contract. + * @param tokenId - Token identifier of the collectible. */ removeAndIgnoreCollectible(address: string, tokenId: number) { address = toChecksumHexAddress(address); @@ -812,7 +807,7 @@ export class CollectiblesController extends BaseController< } /** - * Removes all collectibles from the ignored list + * Removes all collectibles from the ignored list. */ clearIgnoredCollectibles() { this.update({ ignoredCollectibles: [] }); diff --git a/src/assets/CurrencyRateController.test.ts b/src/assets/CurrencyRateController.test.ts index 3fe9ab7af6..ba4d66ae53 100644 --- a/src/assets/CurrencyRateController.test.ts +++ b/src/assets/CurrencyRateController.test.ts @@ -9,6 +9,11 @@ import { const name = 'CurrencyRateController'; +/** + * Constructs a restricted controller messenger. + * + * @returns A restricted controller messenger. + */ function getRestrictedMessenger() { const controllerMessenger = new ControllerMessenger< GetCurrencyRateState, diff --git a/src/assets/CurrencyRateController.ts b/src/assets/CurrencyRateController.ts index bd0a5e1202..1479352153 100644 --- a/src/assets/CurrencyRateController.ts +++ b/src/assets/CurrencyRateController.ts @@ -9,7 +9,6 @@ import type { RestrictedControllerMessenger } from '../ControllerMessenger'; /** * @type CurrencyRateState - * * @property conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch * @property conversionRate - Conversion rate from current base asset to the current currency * @property currentCurrency - Currently-active ISO 4217 currency code @@ -88,13 +87,13 @@ export class CurrencyRateController extends BaseController< private includeUsdRate; /** - * Creates a CurrencyRateController instance + * Creates a CurrencyRateController instance. * - * @param options - Constructor options - * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate - * @param options.interval - The polling interval, in milliseconds - * @param options.messenger - A reference to the messaging system - * @param options.state - Initial state to set on this controller + * @param options - Constructor options. + * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate. + * @param options.interval - The polling interval, in milliseconds. + * @param options.messenger - A reference to the messaging system. + * @param options.state - Initial state to set on this controller. * @param options.fetchExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests. */ constructor({ @@ -122,14 +121,14 @@ export class CurrencyRateController extends BaseController< } /** - * Start polling for the currency rate + * Start polling for the currency rate. */ async start() { await this.startPolling(); } /** - * Stop polling for the currency rate + * Stop polling for the currency rate. */ stop() { this.stopPolling(); @@ -146,9 +145,9 @@ export class CurrencyRateController extends BaseController< } /** - * Sets a currency to track + * Sets a currency to track. * - * @param currentCurrency - ISO 4217 currency code + * @param currentCurrency - ISO 4217 currency code. */ async setCurrentCurrency(currentCurrency: string) { this.update((state) => { @@ -158,9 +157,9 @@ export class CurrencyRateController extends BaseController< } /** - * Sets a new native currency + * Sets a new native currency. * - * @param symbol - Symbol for the base asset + * @param symbol - Symbol for the base asset. */ async setNativeCurrency(symbol: string) { this.update((state) => { @@ -176,7 +175,7 @@ export class CurrencyRateController extends BaseController< } /** - * Starts a new polling interval + * Starts a new polling interval. */ private async startPolling(): Promise { this.stopPolling(); @@ -188,7 +187,9 @@ export class CurrencyRateController extends BaseController< } /** - * Updates exchange rate for the current currency + * Updates exchange rate for the current currency. + * + * @returns The controller state. */ async updateExchangeRate(): Promise { const releaseLock = await this.mutex.acquire(); diff --git a/src/assets/TokenBalancesController.ts b/src/assets/TokenBalancesController.ts index f3b4b3e2ce..56870d4301 100644 --- a/src/assets/TokenBalancesController.ts +++ b/src/assets/TokenBalancesController.ts @@ -13,7 +13,6 @@ export { BN }; * @type TokenBalancesConfig * * Token balances controller configuration - * * @property interval - Polling interval used to fetch new token balances * @property tokens - List of tokens to track balances for */ @@ -26,7 +25,6 @@ export interface TokenBalancesConfig extends BaseConfig { * @type TokenBalancesState * * Token balances controller state - * * @property contractBalances - Hash of token contract addresses to balances */ export interface TokenBalancesState extends BaseState { @@ -53,14 +51,14 @@ export class TokenBalancesController extends BaseController< private getBalanceOf: AssetsContractController['getBalanceOf']; /** - * Creates a TokenBalancesController instance + * Creates a TokenBalancesController instance. * - * @param options - * @param options.onTokensStateChange - Allows subscribing to assets controller state changes - * @param options.getSelectedAddress - Gets the current selected address - * @param options.getBalanceOf - Gets the balance of the given account at the given contract address - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param options - The controller options. + * @param options.onTokensStateChange - Allows subscribing to assets controller state changes. + * @param options.getSelectedAddress - Gets the current selected address. + * @param options.getBalanceOf - Gets the balance of the given account at the given contract address. + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( { @@ -94,9 +92,9 @@ export class TokenBalancesController extends BaseController< } /** - * Starts a new polling interval + * Starts a new polling interval. * - * @param interval - Polling interval used to fetch new token balances + * @param interval - Polling interval used to fetch new token balances. */ async poll(interval?: number): Promise { interval && this.configure({ interval }, false, false); @@ -108,9 +106,7 @@ export class TokenBalancesController extends BaseController< } /** - * Updates balances for all tokens - * - * @returns Promise resolving when this operation completes + * Updates balances for all tokens. */ async updateBalances() { if (this.disabled) { diff --git a/src/assets/TokenListController.test.ts b/src/assets/TokenListController.test.ts index 40cfb52b81..d8a51beee6 100644 --- a/src/assets/TokenListController.test.ts +++ b/src/assets/TokenListController.test.ts @@ -242,6 +242,11 @@ const expiredCacheExistingState = { }, }; +/** + * Get a TokenListController restricted controller messenger. + * + * @returns A restricted controller messenger for the TokenListController. + */ function getRestrictedMessenger() { const controllerMessenger = new ControllerMessenger< GetTokenListState, diff --git a/src/assets/TokenListController.ts b/src/assets/TokenListController.ts index 10f2b6d9fb..4aced204e5 100644 --- a/src/assets/TokenListController.ts +++ b/src/assets/TokenListController.ts @@ -111,12 +111,17 @@ export class TokenListController extends BaseController< // private abortSignal: AbortSignal; /** - * Creates a TokenListController instance + * Creates a TokenListController instance. * - * @param options - Constructor options - * @param options.interval - The polling interval, in milliseconds - * @param options.messenger - A reference to the messaging system - * @param options.state - Initial state to set on this controller + * @param options - The controller options. + * @param options.chainId - The chain ID of the current network. + * @param options.useStaticTokenList - Indicates whether to use the static token list or not. + * @param options.onNetworkStateChange - A function for registering an event handler for network state changes. + * @param options.onPreferencesStateChange -A function for registering an event handler for preference state changes. + * @param options.interval - The polling interval, in milliseconds. + * @param options.cacheRefreshThreshold - The token cache expiry time, in milliseconds. + * @param options.messenger - A restricted controller messenger. + * @param options.state - Initial state to set on this controller. */ constructor({ chainId, @@ -172,14 +177,14 @@ export class TokenListController extends BaseController< } /** - * Start polling for the token list + * Start polling for the token list. */ async start() { await this.startPolling(); } /** - * Restart polling for the token list + * Restart polling for the token list. */ async restart() { this.stopPolling(); @@ -187,7 +192,7 @@ export class TokenListController extends BaseController< } /** - * Stop polling for the token list + * Stop polling for the token list. */ stop() { this.stopPolling(); @@ -210,7 +215,7 @@ export class TokenListController extends BaseController< } /** - * Starts a new polling interval + * Starts a new polling interval. */ private async startPolling(): Promise { await safelyExecute(() => this.fetchTokenList()); @@ -220,7 +225,7 @@ export class TokenListController extends BaseController< } /** - * Fetching token list + * Fetching token list. */ async fetchTokenList(): Promise { if (this.useStaticTokenList) { @@ -231,7 +236,7 @@ export class TokenListController extends BaseController< } /** - * Fetching token list from the contract-metadata as a fallback + * Fetching token list from the contract-metadata as a fallback. */ async fetchFromStaticTokenList(): Promise { const tokenList: TokenListMap = {}; @@ -258,7 +263,7 @@ export class TokenListController extends BaseController< } /** - * Fetching token list from the Token Service API + * Fetching token list from the Token Service API. */ async fetchFromDynamicTokenList(): Promise { const releaseLock = await this.mutex.acquire(); @@ -334,9 +339,10 @@ export class TokenListController extends BaseController< /** * Checks if the Cache timestamp is valid, - * if yes data in cache will be returned - * otherwise null will be returned. - * @returns Promise that resolves into TokenListToken[] or null + * if yes data in cache will be returned + * otherwise null will be returned. + * + * @returns The cached data, or `null` if the cache was expired. */ async fetchFromCache(): Promise { const { tokensChainsCache }: TokenListState = this.state; @@ -352,9 +358,10 @@ export class TokenListController extends BaseController< } /** - * Fetch metadata for a token whose address is send to the API - * @param tokenAddress - * @returns Promise that resolves to Token Metadata + * Fetch metadata for a token. + * + * @param tokenAddress - The address of the token. + * @returns The token metadata. */ async fetchTokenMetadata(tokenAddress: string): Promise { const releaseLock = await this.mutex.acquire(); diff --git a/src/assets/TokenRatesController.ts b/src/assets/TokenRatesController.ts index dec15ddabe..19b383e8ca 100644 --- a/src/assets/TokenRatesController.ts +++ b/src/assets/TokenRatesController.ts @@ -11,7 +11,6 @@ import type { CurrencyRateState } from './CurrencyRateController'; * @type CoinGeckoResponse * * CoinGecko API response representation - * */ export interface CoinGeckoResponse { [address: string]: { @@ -22,7 +21,6 @@ export interface CoinGeckoResponse { * @type CoinGeckoPlatform * * CoinGecko supported platform API representation - * */ export interface CoinGeckoPlatform { id: string; @@ -35,7 +33,6 @@ export interface CoinGeckoPlatform { * @type Token * * Token representation - * * @property address - Hex address of the token contract * @property decimals - Number of decimals the token uses * @property symbol - Symbol of the token @@ -54,7 +51,6 @@ export interface Token { * @type TokenRatesConfig * * Token rates controller configuration - * * @property interval - Polling interval used to fetch new token rates * @property nativeCurrency - Current native currency selected to use base of rates * @property chainId - Current network chainId @@ -87,7 +83,6 @@ interface SupportedVsCurrenciesCache { * @type TokenRatesState * * Token rates controller state - * * @property contractExchangeRates - Hash of token contract addresses to exchange rates * @property supportedChains - Cached chain data */ @@ -109,11 +104,11 @@ const CoinGeckoApi = { }; /** - * Finds the chain slug in the data array given a chainId + * Finds the chain slug in the data array given a chainId. * - * @param chainId current chainId - * @param data Array of supported platforms from CoinGecko API - * @returns Slug of chainId + * @param chainId - The current chain ID. + * @param data - A list platforms supported by the CoinGecko API. + * @returns The CoinGecko slug for the given chain ID, or `null` if the slug was not found. */ function findChainSlug( chainId: string, @@ -158,13 +153,14 @@ export class TokenRatesController extends BaseController< name = 'TokenRatesController'; /** - * Creates a TokenRatesController instance + * Creates a TokenRatesController instance. * - * @param options - * @param options.onAssetsStateChange - Allows subscribing to assets controller state changes - * @param options.onCurrencyRateStateChange - Allows subscribing to currency rate controller state changes - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param options - The controller options. + * @param options.onTokensStateChange - Allows subscribing to token controller state changes. + * @param options.onCurrencyRateStateChange - Allows subscribing to currency rate controller state changes. + * @param options.onNetworkStateChange - Allows subscribing to network state changes. + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( { @@ -217,9 +213,9 @@ export class TokenRatesController extends BaseController< } /** - * Sets a new polling interval + * Sets a new polling interval. * - * @param interval - Polling interval used to fetch new token rates + * @param interval - Polling interval used to fetch new token rates. */ async poll(interval?: number): Promise { interval && this.configure({ interval }, false, false); @@ -231,11 +227,11 @@ export class TokenRatesController extends BaseController< } /** - * Sets a new chainId + * Sets a new chainId. * - * TODO: Replace this with a method + * TODO: Replace this with a method. * - * @param chainId current chainId + * @param _chainId - The current chain ID. */ set chainId(_chainId: string) { !this.disabled && safelyExecute(() => this.updateExchangeRates()); @@ -246,11 +242,11 @@ export class TokenRatesController extends BaseController< } /** - * Sets a new token list to track prices + * Sets a new token list to track prices. * - * TODO: Replace this with a method + * TODO: Replace this with a method. * - * @param tokens - List of tokens to track exchange rates for + * @param tokens - List of tokens to track exchange rates for. */ set tokens(tokens: Token[]) { this.tokenList = tokens; @@ -262,11 +258,11 @@ export class TokenRatesController extends BaseController< } /** - * Fetches a pairs of token address and native currency + * Fetches a pairs of token address and native currency. * - * @param chainSlug - Chain string identifier - * @param vsCurrency - the vsCurrency used to query token exchange rates against. - * @returns - Promise resolving to exchange rates for given pairs + * @param chainSlug - Chain string identifier. + * @param vsCurrency - Query according to tokens in tokenList and native currency. + * @returns The exchange rates for the given pairs. */ async fetchExchangeRate( chainSlug: string, @@ -279,10 +275,10 @@ export class TokenRatesController extends BaseController< /** * Checks if the current native currency is a supported vs currency to use - * to query for token exchange rates + * to query for token exchange rates. * - * @param nativeCurrency - the native currency of the currently active network - * @returns - Promise resolving to a boolean indicating whether it's a supported vsCurrency + * @param nativeCurrency - The native currency of the currently active network. + * @returns A boolean indicating whether it's a supported vsCurrency. */ private async checkIsSupportedVsCurrency(nativeCurrency: string) { const { threshold } = this.config; @@ -305,10 +301,10 @@ export class TokenRatesController extends BaseController< } /** - * Gets current chainId slug from cached supported platforms CoinGecko API response. + * Gets current chain ID slug from cached supported platforms CoinGecko API response. * If cached supported platforms response is stale, fetches and updates it. * - * @returns current chainId + * @returns The CoinGecko slug for the current chain ID. */ async getChainSlug(): Promise { const { threshold, chainId } = this.config; @@ -329,9 +325,7 @@ export class TokenRatesController extends BaseController< } /** - * Updates exchange rates for all tokens - * - * @returns Promise resolving when this operation completes + * Updates exchange rates for all tokens. */ async updateExchangeRates() { if (this.tokenList.length === 0 || this.disabled) { @@ -356,15 +350,16 @@ export class TokenRatesController extends BaseController< } /** - * Checks if the active network's native currency is supported by the coingecko API - * If supported. fetches and maps contractExchange rates in format to be consumed by UI - * If not supported fetches contractExchange rates and maps from from token/fallback-currency to token/nativeCurrency + * Checks if the active network's native currency is supported by the coingecko API. + * If supported, it fetches and maps contractExchange rates to a format to be consumed by the UI. + * If not supported, it fetches contractExchange rates and maps them from token/fallback-currency + * to token/nativeCurrency. * - * @param nativeCurrency - the native currency of the currently active network - * @param slug - the unique slug used to id the chain by the coingecko api - * should be used to query token exchange rates + * @param nativeCurrency - The native currency of the currently active network. + * @param slug - The unique slug used to id the chain by the coingecko api + * should be used to query token exchange rates. * @returns An object with conversion rates for each token - * related to the network's native currency + * related to the network's native currency. */ async fetchAndMapExchangeRates( nativeCurrency: string, diff --git a/src/assets/TokensController.ts b/src/assets/TokensController.ts index 5b05e85136..29f1472d2a 100644 --- a/src/assets/TokensController.ts +++ b/src/assets/TokensController.ts @@ -16,7 +16,6 @@ const ERC721_INTERFACE_ID = '0x80ac58cd'; * @type TokensConfig * * Tokens controller configuration - * * @property networkType - Network ID as per net_version * @property selectedAddress - Vault selected address */ @@ -29,7 +28,6 @@ export interface TokensConfig extends BaseConfig { /** * @type AssetSuggestionResult - * * @property result - Promise resolving to a new suggested asset address * @property suggestedAssetMeta - Meta information about this new suggested asset */ @@ -56,7 +54,6 @@ export type SuggestedAssetMetaBase = { * @type SuggestedAssetMeta * * Suggested asset by EIP747 meta data - * * @property error - Synthesized error information for failed asset suggestions * @property id - Generated UUID associated with this suggested asset * @property status - String status of this this suggested asset @@ -80,7 +77,6 @@ export type SuggestedAssetMeta = * @type TokensState * * Assets controller state - * * @property allTokens - Object containing tokens by network and account * @property suggestedAssets - List of pending suggested assets to be added or canceled * @property tokens - List of tokens associated with the active network and address pair @@ -132,13 +128,13 @@ export class TokensController extends BaseController< name = 'TokensController'; /** - * Creates a TokensController instance + * Creates a TokensController instance. * - * @param options - * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes - * @param options.onNetworkStateChange - Allows subscribing to network controller state changes - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param options - The controller options. + * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes. + * @param options.onNetworkStateChange - Allows subscribing to network controller state changes. + * @param options.config - Initial options used to configure this controller. + * @param options.state - Initial state to set on this controller. */ constructor({ onPreferencesStateChange, @@ -204,13 +200,13 @@ export class TokensController extends BaseController< } /** - * Adds a token to the stored token list + * Adds a token to the stored token list. * - * @param address - Hex address of the token contract - * @param symbol - Symbol of the token - * @param decimals - Number of decimals the token uses - * @param image - Image of the token - * @returns - Current token list + * @param address - Hex address of the token contract. + * @param symbol - Symbol of the token. + * @param decimals - Number of decimals the token uses. + * @param image - Image of the token. + * @returns Current token list. */ async addToken( address: string, @@ -255,10 +251,10 @@ export class TokensController extends BaseController< } /** - * Adds a batch of tokens to the stored token list + * Adds a batch of tokens to the stored token list. * - * @param tokens - Array of Tokens to be added or updated - * @returns - Current token list + * @param tokensToAdd - Array of Tokens to be added or updated. + * @returns Current token list. */ async addTokens(tokensToAdd: Token[]): Promise { const releaseLock = await this.mutex.acquire(); @@ -320,12 +316,11 @@ export class TokensController extends BaseController< } /** - * Adds isERC721 field to token object - * (Called when a user attempts to add tokens that were previously added which do not yet had isERC721 field) + * Adds isERC721 field to token object. This is called when a user attempts to add tokens that + * were previously added which do not yet had isERC721 field. * - * @param {string} tokenAddress - The contract address of the token requiring the isERC721 field added. + * @param tokenAddress - The contract address of the token requiring the isERC721 field added. * @returns The new token object with the added isERC721 field. - * */ async updateTokenType(tokenAddress: string) { const isERC721 = await this._detectIsERC721(tokenAddress); @@ -341,9 +336,9 @@ export class TokensController extends BaseController< /** * Detects whether or not a token is ERC-721 compatible. * - * @param {string} tokensAddress - the token contract address. - * @returns boolean indicating whether the token address passed in supports the EIP-721 interface. - * + * @param tokenAddress - The token contract address. + * @returns A boolean indicating whether the token address passed in supports the EIP-721 + * interface. */ async _detectIsERC721(tokenAddress: string) { const checksumAddress = toChecksumHexAddress(tokenAddress); @@ -392,9 +387,9 @@ export class TokensController extends BaseController< * Adds a new suggestedAsset to state. Parameters will be validated according to * asset type being watched. A `:pending` hub event will be emitted once added. * - * @param asset - Asset to be watched. For now only ERC20 tokens are accepted. - * @param type - Asset type - * @returns - Object containing a promise resolving to the suggestedAsset address if accepted + * @param asset - The asset to be watched. For now only ERC20 tokens are accepted. + * @param type - The asset type. + * @returns Object containing a Promise resolving to the suggestedAsset address if accepted. */ async watchAsset(asset: Token, type: string): Promise { const suggestedAssetMeta = { @@ -448,8 +443,7 @@ export class TokensController extends BaseController< * adding the asset to corresponding asset state. In this case ERC20 tokens. * A `:finished` hub event is fired after accepted or failure. * - * @param suggestedAssetID - ID of the suggestedAsset to accept - * @returns - Promise resolving when this operation completes + * @param suggestedAssetID - The ID of the suggestedAsset to accept. */ async acceptWatchAsset(suggestedAssetID: string): Promise { const { suggestedAssets } = this.state; @@ -486,7 +480,7 @@ export class TokensController extends BaseController< * Rejects a watchAsset request based on its ID by setting its status to "rejected" * and emitting a `:finished` hub event. * - * @param suggestedAssetID - ID of the suggestedAsset to accept + * @param suggestedAssetID - The ID of the suggestedAsset to accept. */ rejectWatchAsset(suggestedAssetID: string) { const { suggestedAssets } = this.state; @@ -506,9 +500,9 @@ export class TokensController extends BaseController< } /** - * Removes a token from the stored token list and saves it in ignored tokens list + * Removes a token from the stored token list and saves it in ignored tokens list. * - * @param address - Hex address of the token contract + * @param address - The hex address of the token contract. */ removeAndIgnoreToken(address: string) { address = toChecksumHexAddress(address); @@ -575,7 +569,7 @@ export class TokensController extends BaseController< } /** - * Removes all tokens from the ignored list + * Removes all tokens from the ignored list. */ clearIgnoredTokens() { this.update({ ignoredTokens: [], allIgnoredTokens: {} }); diff --git a/src/assets/assetsUtil.ts b/src/assets/assetsUtil.ts index 9b7d194446..8b8a90c4ff 100644 --- a/src/assets/assetsUtil.ts +++ b/src/assets/assetsUtil.ts @@ -1,13 +1,13 @@ import { Collectible, CollectibleMetadata } from './CollectiblesController'; /** - * Compares collectible metadata entries to any collectible entry + * Compares collectible metadata entries to any collectible entry. * We need this method when comparing a new fetched collectible metadata, in case a entry changed to a defined value, * there's a need to update the collectible in state. * - * @param collectibleMetadata - Collectible metadata object - * @param collectible - Collectible object to compare with - * @returns - Whether there are differences + * @param newCollectibleMetadata - Collectible metadata object. + * @param collectible - Collectible object to compare with. + * @returns Whether there are differences. */ export function compareCollectiblesMetadata( newCollectibleMetadata: CollectibleMetadata, diff --git a/src/gas/GasFeeController.test.ts b/src/gas/GasFeeController.test.ts index 5cc8ec05da..6c5e2bf267 100644 --- a/src/gas/GasFeeController.test.ts +++ b/src/gas/GasFeeController.test.ts @@ -13,6 +13,11 @@ const TEST_LEGACY_FEE_API = 'https://test/'; const name = 'GasFeeController'; +/** + * Constructs a restricted controller messenger. + * + * @returns A restricted controller messenger. + */ function getRestrictedMessenger() { const controllerMessenger = new ControllerMessenger< GetGasFeeState, diff --git a/src/gas/GasFeeController.ts b/src/gas/GasFeeController.ts index bc044685a5..d53d8b7d06 100644 --- a/src/gas/GasFeeController.ts +++ b/src/gas/GasFeeController.ts @@ -68,7 +68,6 @@ export type EstimatedGasFeeTimeBounds = { * A single gas price estimate for networks and accounts that don't support EIP-1559 * This estimate comes from eth_gasPrice but is converted to dec gwei to match other * return values - * * @property gasPrice - A GWEI dec string */ @@ -82,7 +81,6 @@ export type EthGasPriceEstimate = { * A set of gas price estimates for networks and accounts that don't support EIP-1559 * These estimates include low, medium and high all as strings representing gwei in * decimal format. - * * @property high - gasPrice, in decimal gwei string format, suggested for fast inclusion * @property medium - gasPrice, in decimal gwei string format, suggested for avg inclusion * @property low - gasPrice, in decimal gwei string format, suggested for slow inclusion @@ -97,7 +95,6 @@ export type LegacyGasPriceEstimate = { * @type Eip1559GasFee * * Data necessary to provide an estimate of a gas fee with a specific tip - * * @property minWaitTimeEstimate - The fastest the transaction will take, in milliseconds * @property maxWaitTimeEstimate - The slowest the transaction will take, in milliseconds * @property suggestedMaxPriorityFeePerGas - A suggested "tip", a GWEI hex number @@ -115,7 +112,6 @@ export type Eip1559GasFee = { * @type GasFeeEstimates * * Data necessary to provide multiple GasFee estimates, and supporting information, to the user - * * @property low - A GasFee for a minimum necessary combination of tip and maxFee * @property medium - A GasFee for a recommended combination of tip and maxFee * @property high - A GasFee for a high combination of tip and maxFee @@ -167,7 +163,6 @@ export type FetchGasFeeEstimateOptions = { * @type GasFeeState * * Gas Fee controller state - * * @property gasFeeEstimates - Gas fee estimate data based on new EIP-1559 properties * @property estimatedGasFeeTimeBounds - Estimates representing the minimum and maximum */ @@ -242,8 +237,34 @@ export class GasFeeController extends BaseController< private clientId?: string; /** - * Creates a GasFeeController instance + * Creates a GasFeeController instance. * + * @param options - The controller options. + * @param options.interval - The time in milliseconds to wait between polls. + * @param options.messenger - The controller messenger. + * @param options.state - The initial state. + * @param options.fetchGasEstimates - The function to use to fetch gas estimates. This option is + * primarily for testing purposes. + * @param options.fetchEthGasPriceEstimate - The function to use to fetch gas price estimates. + * This option is primarily for testing purposes. + * @param options.fetchLegacyGasPriceEstimates - The function to use to fetch legacy gas price + * estimates. This option is primarily for testing purposes. + * @param options.getCurrentNetworkEIP1559Compatibility - Determines whether or not the current + * network is EIP-1559 compatible. + * @param options.getCurrentNetworkLegacyGasAPICompatibility - Determines whether or not the + * current network is compatible with the legacy gas price API. + * @param options.getCurrentAccountEIP1559Compatibility - Determines whether or not the current + * account is EIP-1559 compatible. + * @param options.getChainId - Returns the current chain ID. + * @param options.getProvider - Returns a network provider for the current network. + * @param options.onNetworkStateChange - A function for registering an event handler for the + * network state change event. + * @param options.legacyAPIEndpoint - The legacy gas price API URL. This option is primarily for + * testing purposes. + * @param options.EIP1559APIEndpoint - The EIP-1559 gas price API URL. This option is primarily + * for testing purposes. + * @param options.clientId - The client ID used to identify to the gas estimation API who is + * asking for estimates. */ constructor({ interval = 15000, @@ -341,9 +362,12 @@ export class GasFeeController extends BaseController< } /** - * Gets and sets gasFeeEstimates in state + * Gets and sets gasFeeEstimates in state. * - * @returns GasFeeEstimates + * @param options - The gas fee estimate options. + * @param options.shouldUpdateState - Determines whether the state should be updated with the + * updated gas estimates. + * @returns The gas fee estimates. */ async _fetchGasFeeEstimateData( options: FetchGasFeeEstimateOptions = {}, @@ -427,7 +451,9 @@ export class GasFeeController extends BaseController< } /** - * Remove the poll token, and stop polling if the set of poll tokens is empty + * Remove the poll token, and stop polling if the set of poll tokens is empty. + * + * @param pollToken - The poll token to disconnect. */ disconnectPoller(pollToken: string) { this.pollTokens.delete(pollToken); diff --git a/src/gas/gas-util.ts b/src/gas/gas-util.ts index a1606201c6..117ec30432 100644 --- a/src/gas/gas-util.ts +++ b/src/gas/gas-util.ts @@ -10,12 +10,25 @@ import { const makeClientIdHeader = (clientId: string) => ({ 'X-Client-Id': clientId }); +/** + * Convert a decimal GWEI value to a decimal string rounded to the nearest WEI. + * + * @param n - The input GWEI amount, as a decimal string or a number. + * @returns The decimal string GWEI amount. + */ export function normalizeGWEIDecimalNumbers(n: string | number) { const numberAsWEIHex = gweiDecToWEIBN(n).toString(16); const numberAsGWEI = weiHexToGweiDec(numberAsWEIHex).toString(10); return numberAsGWEI; } +/** + * Fetch gas estimates from the given URL. + * + * @param url - The gas estimate URL. + * @param clientId - The client ID used to identify to the API who is asking for estimates. + * @returns The gas estimates. + */ export async function fetchGasEstimates( url: string, clientId?: string, @@ -60,6 +73,10 @@ export async function fetchGasEstimates( /** * Hit the legacy MetaSwaps gasPrices estimate api and return the low, medium * high values from that API. + * + * @param url - The URL to fetch gas price estimates from. + * @param clientId - The client ID used to identify to the API who is asking for estimates. + * @returns The gas price estimates. */ export async function fetchLegacyGasPriceEstimates( url: string, @@ -82,6 +99,12 @@ export async function fetchLegacyGasPriceEstimates( }; } +/** + * Get a gas price estimate from the network using the `eth_gasPrice` method. + * + * @param ethQuery - The EthQuery instance to call the network with. + * @returns A gas price estimate. + */ export async function fetchEthGasPriceEstimate( ethQuery: any, ): Promise { @@ -91,6 +114,14 @@ export async function fetchEthGasPriceEstimate( }; } +/** + * Estimate the time it will take for a transaction to be confirmed. + * + * @param maxPriorityFeePerGas - The max priority fee per gas. + * @param maxFeePerGas - The max fee per gas. + * @param gasFeeEstimates - The gas fee estimates. + * @returns The estimated lower and upper bounds for when this transaction will be confirmed. + */ export function calculateTimeEstimate( maxPriorityFeePerGas: string, maxFeePerGas: string, diff --git a/src/keyring/KeyringController.ts b/src/keyring/KeyringController.ts index 1b130b7b02..f8a1008807 100644 --- a/src/keyring/KeyringController.ts +++ b/src/keyring/KeyringController.ts @@ -39,7 +39,6 @@ export enum KeyringTypes { * @type KeyringObject * * Keyring object - * * @property type - Keyring type * @property accounts - Associated accounts * @function getAccounts - Get associated accounts @@ -54,7 +53,6 @@ export interface KeyringObject { * @type KeyringState * * Keyring controller state - * * @property vault - Encrypted string representing keyring data * @property keyrings - Group of accounts */ @@ -67,7 +65,6 @@ export interface KeyringState extends BaseState { * @type KeyringMemState * * Keyring mem controller state - * * @property isUnlocked - Whether vault is unlocked * @property keyringTypes - Account types * @property keyrings - Group of accounts @@ -82,7 +79,6 @@ export interface KeyringMemState extends BaseState { * @type KeyringConfig * * Keyring controller configuration - * * @property encryptor - Keyring encryptor */ export interface KeyringConfig extends BaseConfig { @@ -93,7 +89,6 @@ export interface KeyringConfig extends BaseConfig { * @type Keyring * * Keyring object to return in fullUpdate - * * @property type - Keyring type * @property accounts - Associated accounts * @property index - Associated index @@ -114,6 +109,7 @@ export enum AccountImportStrategy { /** * The `signTypedMessage` version + * * @see https://docs.metamask.io/guide/signing-data.html */ export enum SignTypedDataVersion { @@ -145,15 +141,15 @@ export class KeyringController extends BaseController< private setSelectedAddress: PreferencesController['setSelectedAddress']; /** - * Creates a KeyringController instance + * Creates a KeyringController instance. * - * @param options - * @param options.removeIdentity - Remove the identity with the given address - * @param options.syncIdentities - Sync identities with the given list of addresses - * @param options.updateIdentities - Generate an identity for each address given that doesn't already have an identity - * @param options.setSelectedAddress - Set the selected address - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param options - The controller options. + * @param options.removeIdentity - Remove the identity with the given address. + * @param options.syncIdentities - Sync identities with the given list of addresses. + * @param options.updateIdentities - Generate an identity for each address given that doesn't already have an identity. + * @param options.setSelectedAddress - Set the selected address. + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( { @@ -188,9 +184,9 @@ export class KeyringController extends BaseController< } /** - * Adds a new account to the default (first) HD seed phrase keyring + * Adds a new account to the default (first) HD seed phrase keyring. * - * @returns - Promise resolving to current state when the account is added + * @returns Promise resolving to current state when the account is added. */ async addNewAccount(): Promise { const primaryKeyring = privates @@ -216,9 +212,9 @@ export class KeyringController extends BaseController< } /** - * Adds a new account to the default (first) HD seed phrase keyring without updating identities in preferences + * Adds a new account to the default (first) HD seed phrase keyring without updating identities in preferences. * - * @returns - Promise resolving to current state when the account is added + * @returns Promise resolving to current state when the account is added. */ async addNewAccountWithoutUpdate(): Promise { const primaryKeyring = privates @@ -235,11 +231,11 @@ export class KeyringController extends BaseController< /** * Effectively the same as creating a new keychain then populating it - * using the given seed phrase + * using the given seed phrase. * - * @param password - Password to unlock keychain - * @param seed - Seed phrase to restore keychain - * @returns - Promise resolving to th restored keychain object + * @param password - Password to unlock keychain. + * @param seed - Seed phrase to restore keychain. + * @returns Promise resolving to th restored keychain object. */ async createNewVaultAndRestore(password: string, seed: string) { const releaseLock = await this.mutex.acquire(); @@ -257,10 +253,10 @@ export class KeyringController extends BaseController< } /** - * Create a new primary keychain and wipe any previous keychains + * Create a new primary keychain and wipe any previous keychains. * - * @param password - Password to unlock the new vault - * @returns - Newly-created keychain object + * @param password - Password to unlock the new vault. + * @returns Newly-created keychain object. */ async createNewVaultAndKeychain(password: string) { const releaseLock = await this.mutex.acquire(); @@ -277,19 +273,19 @@ export class KeyringController extends BaseController< } /** - * Returns the status of the vault + * Returns the status of the vault. * - * @returns - Boolean returning true if the vault is unlocked + * @returns Boolean returning true if the vault is unlocked. */ isUnlocked(): boolean { return privates.get(this).keyring.memStore.getState().isUnlocked; } /** - * Gets the seed phrase of the HD keyring + * Gets the seed phrase of the HD keyring. * - * @param password - Password of the keyring - * @returns - Promise resolving to the seed phrase + * @param password - Password of the keyring. + * @returns Promise resolving to the seed phrase. */ exportSeedPhrase(password: string) { if (privates.get(this).keyring.password === password) { @@ -299,11 +295,11 @@ export class KeyringController extends BaseController< } /** - * Gets the private key from the keyring controlling an address + * Gets the private key from the keyring controlling an address. * - * @param password - Password of the keyring - * @param address - Address to export - * @returns - Promise resolving to the private key for an address + * @param password - Password of the keyring. + * @param address - Address to export. + * @returns Promise resolving to the private key for an address. */ exportAccount(password: string, address: string): Promise { if (privates.get(this).keyring.password === password) { @@ -313,21 +309,21 @@ export class KeyringController extends BaseController< } /** - * Returns the public addresses of all accounts for the current keyring + * Returns the public addresses of all accounts for the current keyring. * - * @returns - A promise resolving to an array of addresses + * @returns A promise resolving to an array of addresses. */ getAccounts(): Promise { return privates.get(this).keyring.getAccounts(); } /** - * Imports an account with the specified import strategy + * Imports an account with the specified import strategy. * - * @param strategy - Import strategy name - * @param args - Array of arguments to pass to the underlying stategy - * @throws Will throw when passed an unrecognized strategy - * @returns - Promise resolving to current state when the import is complete + * @param strategy - Import strategy name. + * @param args - Array of arguments to pass to the underlying stategy. + * @throws Will throw when passed an unrecognized strategy. + * @returns Promise resolving to current state when the import is complete. */ async importAccountWithStrategy( strategy: AccountImportStrategy, @@ -371,10 +367,10 @@ export class KeyringController extends BaseController< } /** - * Removes an account from keyring state + * Removes an account from keyring state. * - * @param address - Address of the account to remove - * @returns - Promise resolving current state when this account removal completes + * @param address - Address of the account to remove. + * @returns Promise resolving current state when this account removal completes. */ async removeAccount(address: string): Promise { this.removeIdentity(address); @@ -383,41 +379,41 @@ export class KeyringController extends BaseController< } /** - * Deallocates all secrets and locks the wallet + * Deallocates all secrets and locks the wallet. * - * @returns - Promise resolving to current state + * @returns Promise resolving to current state. */ setLocked(): Promise { return privates.get(this).keyring.setLocked(); } /** - * Signs message by calling down into a specific keyring + * Signs message by calling down into a specific keyring. * - * @param messageParams - PersonalMessageParams object to sign - * @returns - Promise resolving to a signed message string + * @param messageParams - PersonalMessageParams object to sign. + * @returns Promise resolving to a signed message string. */ signMessage(messageParams: PersonalMessageParams) { return privates.get(this).keyring.signMessage(messageParams); } /** - * Signs personal message by calling down into a specific keyring + * Signs personal message by calling down into a specific keyring. * - * @param messageParams - PersonalMessageParams object to sign - * @returns - Promise resolving to a signed message string + * @param messageParams - PersonalMessageParams object to sign. + * @returns Promise resolving to a signed message string. */ signPersonalMessage(messageParams: PersonalMessageParams) { return privates.get(this).keyring.signPersonalMessage(messageParams); } /** - * Signs typed message by calling down into a specific keyring + * Signs typed message by calling down into a specific keyring. * - * @param messageParams - TypedMessageParams object to sign - * @param version - Compatibility version EIP712 - * @throws Will throw when passed an unrecognized version - * @returns - Promise resolving to a signed message string or an error if any + * @param messageParams - TypedMessageParams object to sign. + * @param version - Compatibility version EIP712. + * @throws Will throw when passed an unrecognized version. + * @returns Promise resolving to a signed message string or an error if any. */ async signTypedMessage( messageParams: TypedMessageParams, @@ -451,21 +447,21 @@ export class KeyringController extends BaseController< } /** - * Signs a transaction by calling down into a specific keyring + * Signs a transaction by calling down into a specific keyring. * * @param transaction - Transaction object to sign. Must be a `ethereumjs-tx` transaction instance. - * @param from - Address to sign from, should be in keychain - * @returns - Promise resolving to a signed transaction string + * @param from - Address to sign from, should be in keychain. + * @returns Promise resolving to a signed transaction string. */ signTransaction(transaction: unknown, from: string) { return privates.get(this).keyring.signTransaction(transaction, from); } /** - * Attempts to decrypt the current vault and load its keyrings + * Attempts to decrypt the current vault and load its keyrings. * - * @param password - Password to unlock the keychain - * @returns - Promise resolving to the current state + * @param password - Password to unlock the keychain. + * @returns Promise resolving to the current state. */ async submitPassword(password: string): Promise { await privates.get(this).keyring.submitPassword(password); @@ -475,48 +471,48 @@ export class KeyringController extends BaseController< } /** - * Adds new listener to be notified of state changes + * Adds new listener to be notified of state changes. * - * @param listener - Callback triggered when state changes + * @param listener - Callback triggered when state changes. */ subscribe(listener: Listener) { privates.get(this).keyring.store.subscribe(listener); } /** - * Removes existing listener from receiving state changes + * Removes existing listener from receiving state changes. * - * @param listener - Callback to remove - * @returns - True if a listener is found and unsubscribed + * @param listener - Callback to remove. + * @returns True if a listener is found and unsubscribed. */ unsubscribe(listener: Listener) { return privates.get(this).keyring.store.unsubscribe(listener); } /** - * Adds new listener to be notified when the wallet is locked + * Adds new listener to be notified when the wallet is locked. * - * @param listener - Callback triggered when wallet is locked - * @returns - EventEmitter if listener added + * @param listener - Callback triggered when wallet is locked. + * @returns EventEmitter if listener added. */ onLock(listener: () => void) { return privates.get(this).keyring.on('lock', listener); } /** - * Adds new listener to be notified when the wallet is unlocked + * Adds new listener to be notified when the wallet is unlocked. * - * @param listener - Callback triggered when wallet is unlocked - * @returns - EventEmitter if listener added + * @param listener - Callback triggered when wallet is unlocked. + * @returns EventEmitter if listener added. */ onUnlock(listener: () => void) { return privates.get(this).keyring.on('unlock', listener); } /** - * Verifies the that the seed phrase restores the current keychain's accounts + * Verifies the that the seed phrase restores the current keychain's accounts. * - * @returns - Promise resolving if the verification succeeds + * @returns Whether the verification succeeds. */ async verifySeedPhrase(): Promise { const primaryKeyring = privates @@ -558,9 +554,9 @@ export class KeyringController extends BaseController< } /** - * Update keyrings in state and calls KeyringController fullUpdate method returning current state + * Update keyrings in state and calls KeyringController fullUpdate method returning current state. * - * @returns - Promise resolving to current state + * @returns The current state. */ async fullUpdate(): Promise { const keyrings: Keyring[] = await Promise.all( diff --git a/src/message-manager/AbstractMessageManager.ts b/src/message-manager/AbstractMessageManager.ts index 11975166db..6f8631e865 100644 --- a/src/message-manager/AbstractMessageManager.ts +++ b/src/message-manager/AbstractMessageManager.ts @@ -5,7 +5,6 @@ import { BaseController, BaseConfig, BaseState } from '../BaseController'; * @type OriginalRequest * * Represents the original request object for adding a message. - * * @property origin? - Is it is specified, represents the origin */ export interface OriginalRequest { @@ -16,7 +15,6 @@ export interface OriginalRequest { * @type Message * * Represents and contains data about a signing type signature request. - * * @property id - An id to track and identify the message object * @property type - The json-prc signing method for which a signature request has been made. * A 'Message' which always has a signing type @@ -34,7 +32,6 @@ export interface AbstractMessage { * @type MessageParams * * Represents the parameters to pass to the signing method once the signature request is approved. - * * @property from - Address to sign this message from * @property origin? - Added for request origin identification */ @@ -48,7 +45,6 @@ export interface AbstractMessageParams { * * Represents the parameters to pass to the signing method once the signature request is approved * plus data added by MetaMask. - * * @property metamaskId - Added for tracking and identification within MetaMask * @property from - Address to sign this message from * @property origin? - Added for request origin identification @@ -61,7 +57,6 @@ export interface AbstractMessageParamsMetamask extends AbstractMessageParams { * @type MessageManagerState * * Message Manager state - * * @property unapprovedMessages - A collection of all Messages in the 'unapproved' state * @property unapprovedMessagesCount - The count of all Messages in this.unapprovedMessages */ @@ -82,7 +77,7 @@ export abstract class AbstractMessageManager< protected messages: M[]; /** - * Saves the unapproved messages, and their count to state + * Saves the unapproved messages, and their count to state. * */ protected saveMessageList() { @@ -93,10 +88,10 @@ export abstract class AbstractMessageManager< } /** - * Updates the status of a Message in this.messages + * Updates the status of a Message in this.messages. * - * @param messageId - The id of the Message to update - * @param status - The new status of the Message + * @param messageId - The id of the Message to update. + * @param status - The new status of the Message. */ protected setMessageStatus(messageId: string, status: string) { const message = this.getMessage(messageId); @@ -113,9 +108,9 @@ export abstract class AbstractMessageManager< /** * Sets a Message in this.messages to the passed Message if the ids are equal. - * Then saves the unapprovedMessage list to storage + * Then saves the unapprovedMessage list to storage. * - * @param message - A Message that will replace an existing Message (with the id) in this.messages + * @param message - A Message that will replace an existing Message (with the id) in this.messages. */ protected updateMessage(message: M) { const index = this.messages.findIndex((msg) => message.id === msg.id); @@ -137,10 +132,10 @@ export abstract class AbstractMessageManager< name = 'AbstractMessageManager'; /** - * Creates an AbstractMessageManager instance + * Creates an AbstractMessageManager instance. * - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( config?: Partial, @@ -156,20 +151,18 @@ export abstract class AbstractMessageManager< } /** - * A getter for the number of 'unapproved' Messages in this.messages - * - * @returns - The number of 'unapproved' Messages in this.messages + * A getter for the number of 'unapproved' Messages in this.messages. * + * @returns The number of 'unapproved' Messages in this.messages. */ getUnapprovedMessagesCount() { return Object.keys(this.getUnapprovedMessages()).length; } /** - * A getter for the 'unapproved' Messages in state messages - * - * @returns - An index of Message ids to Messages, for all 'unapproved' Messages in this.messages + * A getter for the 'unapproved' Messages in state messages. * + * @returns An index of Message ids to Messages, for all 'unapproved' Messages in this.messages. */ getUnapprovedMessages() { return this.messages @@ -184,8 +177,7 @@ export abstract class AbstractMessageManager< * Adds a passed Message to this.messages, and calls this.saveMessageList() to save * the unapproved Messages from that list to this.messages. * - * @param {Message} message The Message to add to this.messages - * + * @param message - The Message to add to this.messages. */ addMessage(message: M) { this.messages.push(message); @@ -195,10 +187,9 @@ export abstract class AbstractMessageManager< /** * Returns a specified Message. * - * @param messageId - The id of the Message to get - * @returns - The Message with the id that matches the passed messageId, or undefined + * @param messageId - The id of the Message to get. + * @returns The Message with the id that matches the passed messageId, or undefined * if no Message has that id. - * */ getMessage(messageId: string) { return this.messages.find((message) => message.id === messageId); @@ -209,8 +200,8 @@ export abstract class AbstractMessageManager< * and returns a promise with any the message params modified for proper signing. * * @param messageParams - The messageParams to be used when signing method is called, - * plus data added by MetaMask - * @returns - Promise resolving to the messageParams with the metamaskId property removed + * plus data added by MetaMask. + * @returns Promise resolving to the messageParams with the metamaskId property removed. */ approveMessage(messageParams: PM): Promise

{ // eslint-disable-next-line @typescript-eslint/ban-ts-comment @@ -222,7 +213,7 @@ export abstract class AbstractMessageManager< /** * Sets a Message status to 'approved' via a call to this.setMessageStatus. * - * @param messageId - The id of the Message to approve + * @param messageId - The id of the Message to approve. */ setMessageStatusApproved(messageId: string) { this.setMessageStatus(messageId, 'approved'); @@ -233,8 +224,8 @@ export abstract class AbstractMessageManager< * that Message in this.messages by adding the raw signature data of the signature * request to the Message. * - * @param messageId - The id of the Message to sign - * @param rawSig - The raw data of the signature request + * @param messageId - The id of the Message to sign. + * @param rawSig - The raw data of the signature request. */ setMessageStatusSigned(messageId: string, rawSig: string) { const message = this.getMessage(messageId); @@ -252,7 +243,7 @@ export abstract class AbstractMessageManager< * resolves the updated messageParams * * @param messageParams - The messageParams to modify - * @returns - Promise resolving to the messageParams with the metamaskId property removed + * @returns Promise resolving to the messageParams with the metamaskId property removed */ abstract prepMessageForSigning(messageParams: PM): Promise

; diff --git a/src/message-manager/MessageManager.ts b/src/message-manager/MessageManager.ts index e06474ac4b..f8a72f51ac 100644 --- a/src/message-manager/MessageManager.ts +++ b/src/message-manager/MessageManager.ts @@ -13,7 +13,6 @@ import { * * Represents and contains data about a 'eth_sign' type signature request. * These are created when a signature for an eth_sign call is requested. - * * @property id - An id to track and identify the message object * @property messageParams - The parameters to pass to the eth_sign method once the signature request is approved * @property type - The json-prc signing method for which a signature request has been made. @@ -28,7 +27,6 @@ export interface Message extends AbstractMessage { * @type PersonalMessageParams * * Represents the parameters to pass to the eth_sign method once the signature request is approved. - * * @property data - A hex string conversion of the raw buffer data of the signature request * @property from - Address to sign this message from * @property origin? - Added for request origin identification @@ -42,7 +40,6 @@ export interface MessageParams extends AbstractMessageParams { * * Represents the parameters to pass to the eth_sign method once the signature request is approved * plus data added by MetaMask. - * * @property metamaskId - Added for tracking and identification within MetaMask * @property data - A hex string conversion of the raw buffer data of the signature request * @property from - Address to sign this message from @@ -69,9 +66,9 @@ export class MessageManager extends AbstractMessageManager< * Creates a new Message with an 'unapproved' status using the passed messageParams. * this.addMessage is called to add the new Message to this.messages, and to save the unapproved Messages. * - * @param messageParams - The params for the eth_sign call to be made after the message is approved - * @param req? - The original request object possibly containing the origin - * @returns - Promise resolving to the raw data of the signature request + * @param messageParams - The params for the eth_sign call to be made after the message is approved. + * @param req - The original request object possibly containing the origin. + * @returns Promise resolving to the raw data of the signature request. */ addUnapprovedMessageAsync( messageParams: MessageParams, @@ -109,9 +106,9 @@ export class MessageManager extends AbstractMessageManager< * unapproved Messages. * * @param messageParams - The params for the eth_sign call to be made after the message - * is approved - * @param req? - The original request object possibly containing the origin - * @returns - The id of the newly created message + * is approved. + * @param req - The original request object possibly containing the origin. + * @returns The id of the newly created message. */ addUnapprovedMessage(messageParams: MessageParams, req?: OriginalRequest) { if (req) { @@ -136,10 +133,10 @@ export class MessageManager extends AbstractMessageManager< /** * Removes the metamaskId property from passed messageParams and returns a promise which - * resolves the updated messageParams + * resolves the updated messageParams. * - * @param messageParams - The messageParams to modify - * @returns - Promise resolving to the messageParams with the metamaskId property removed + * @param messageParams - The messageParams to modify. + * @returns Promise resolving to the messageParams with the metamaskId property removed. */ prepMessageForSigning( messageParams: MessageParamsMetamask, diff --git a/src/message-manager/PersonalMessageManager.ts b/src/message-manager/PersonalMessageManager.ts index 1354be2529..cb3bee49fd 100644 --- a/src/message-manager/PersonalMessageManager.ts +++ b/src/message-manager/PersonalMessageManager.ts @@ -13,7 +13,6 @@ import { * * Represents and contains data about a 'personal_sign' type signature request. * These are created when a signature for a personal_sign call is requested. - * * @property id - An id to track and identify the message object * @property messageParams - The parameters to pass to the personal_sign method once the signature request is approved * @property type - The json-prc signing method for which a signature request has been made. @@ -28,7 +27,6 @@ export interface PersonalMessage extends AbstractMessage { * @type PersonalMessageParams * * Represents the parameters to pass to the personal_sign method once the signature request is approved. - * * @property data - A hex string conversion of the raw buffer data of the signature request * @property from - Address to sign this message from * @property origin? - Added for request origin identification @@ -42,7 +40,6 @@ export interface PersonalMessageParams extends AbstractMessageParams { * * Represents the parameters to pass to the personal_sign method once the signature request is approved * plus data added by MetaMask. - * * @property metamaskId - Added for tracking and identification within MetaMask * @property data - A hex string conversion of the raw buffer data of the signature request * @property from - Address to sign this message from @@ -70,9 +67,9 @@ export class PersonalMessageManager extends AbstractMessageManager< * Creates a new Message with an 'unapproved' status using the passed messageParams. * this.addMessage is called to add the new Message to this.messages, and to save the unapproved Messages. * - * @param messageParams - The params for the personal_sign call to be made after the message is approved - * @param req? - The original request object possibly containing the origin - * @returns - Promise resolving to the raw data of the signature request + * @param messageParams - The params for the personal_sign call to be made after the message is approved. + * @param req - The original request object possibly containing the origin. + * @returns Promise resolving to the raw data of the signature request. */ addUnapprovedMessageAsync( messageParams: PersonalMessageParams, @@ -110,9 +107,9 @@ export class PersonalMessageManager extends AbstractMessageManager< * unapproved Messages. * * @param messageParams - The params for the personal_sign call to be made after the message - * is approved - * @param req? - The original request object possibly containing the origin - * @returns - The id of the newly created message + * is approved. + * @param req - The original request object possibly containing the origin. + * @returns The id of the newly created message. */ addUnapprovedMessage( messageParams: PersonalMessageParams, @@ -140,10 +137,10 @@ export class PersonalMessageManager extends AbstractMessageManager< /** * Removes the metamaskId property from passed messageParams and returns a promise which - * resolves the updated messageParams + * resolves the updated messageParams. * - * @param messageParams - The messageParams to modify - * @returns - Promise resolving to the messageParams with the metamaskId property removed + * @param messageParams - The messageParams to modify. + * @returns Promise resolving to the messageParams with the metamaskId property removed. */ prepMessageForSigning( messageParams: PersonalMessageParamsMetamask, diff --git a/src/message-manager/TypedMessageManager.ts b/src/message-manager/TypedMessageManager.ts index 494ab6c36e..18cb49d5ce 100644 --- a/src/message-manager/TypedMessageManager.ts +++ b/src/message-manager/TypedMessageManager.ts @@ -16,7 +16,6 @@ import { * * Represents and contains data about an 'eth_signTypedData' type signature request. * These are created when a signature for an eth_signTypedData call is requested. - * * @property id - An id to track and identify the message object * @property error - Error corresponding to eth_signTypedData error in failure case * @property messageParams - The parameters to pass to the eth_signTypedData method once @@ -38,7 +37,6 @@ export interface TypedMessage extends AbstractMessage { * @type TypedMessageParams * * Represents the parameters to pass to the eth_signTypedData method once the signature request is approved. - * * @property data - A hex string conversion of the raw buffer or an object containing data of the signature * request depending on version * @property from - Address to sign this message from @@ -53,7 +51,6 @@ export interface TypedMessageParams extends AbstractMessageParams { * * Represents the parameters to pass to the eth_signTypedData method once the signature request is approved * plus data added by MetaMask. - * * @property metamaskId - Added for tracking and identification within MetaMask * @property data - A hex string conversion of the raw buffer or an object containing data of the signature * request depending on version @@ -87,10 +84,10 @@ export class TypedMessageManager extends AbstractMessageManager< * Creates a new TypedMessage with an 'unapproved' status using the passed messageParams. * this.addMessage is called to add the new TypedMessage to this.messages, and to save the unapproved TypedMessages. * - * @param messageParams - The params for the eth_signTypedData call to be made after the message is approved - * @param version - Compatibility version EIP712 - * @param req? - The original request object possibly containing the origin - * @returns - Promise resolving to the raw data of the signature request + * @param messageParams - The params for the eth_signTypedData call to be made after the message is approved. + * @param version - Compatibility version EIP712. + * @param req - The original request object possibly containing the origin. + * @returns Promise resolving to the raw data of the signature request. */ addUnapprovedMessageAsync( messageParams: TypedMessageParams, @@ -139,10 +136,10 @@ export class TypedMessageManager extends AbstractMessageManager< * unapproved TypedMessages. * * @param messageParams - The params for the 'eth_signTypedData' call to be made after the message - * is approved - * @param version - Compatibility version EIP712 - * @param req? - The original request object possibly containing the origin - * @returns - The id of the newly created TypedMessage + * is approved. + * @param version - Compatibility version EIP712. + * @param req - The original request object possibly containing the origin. + * @returns The id of the newly created TypedMessage. */ addUnapprovedMessage( messageParams: TypedMessageParams, @@ -173,8 +170,8 @@ export class TypedMessageManager extends AbstractMessageManager< /** * Sets a TypedMessage status to 'errored' via a call to this.setMessageStatus. * - * @param messageId - The id of the TypedMessage to error - * @param error - The error to be included in TypedMessage + * @param messageId - The id of the TypedMessage to error. + * @param error - The error to be included in TypedMessage. */ setMessageStatusErrored(messageId: string, error: string) { const message = this.getMessage(messageId); @@ -189,10 +186,10 @@ export class TypedMessageManager extends AbstractMessageManager< /** * Removes the metamaskId and version properties from passed messageParams and returns a promise which - * resolves the updated messageParams + * resolves the updated messageParams. * - * @param messageParams - The messageParams to modify - * @returns - Promise resolving to the messageParams with the metamaskId and version properties removed + * @param messageParams - The messageParams to modify. + * @returns Promise resolving to the messageParams with the metamaskId and version properties removed. */ prepMessageForSigning( messageParams: TypedMessageParamsMetamask, diff --git a/src/network/NetworkController.ts b/src/network/NetworkController.ts index 0783490ed4..4a23107e41 100644 --- a/src/network/NetworkController.ts +++ b/src/network/NetworkController.ts @@ -36,12 +36,11 @@ export enum NetworksChainId { * @type ProviderConfig * * Configuration passed to web3-provider-engine - * - * @param rpcTarget? - RPC target URL - * @param type - Human-readable network name - * @param chainId? - Network ID as per EIP-155 - * @param ticker? - Currency ticker - * @param nickname? - Personalized network name + * @property rpcTarget - RPC target URL. + * @property type - Human-readable network name. + * @property chainId - Network ID as per EIP-155. + * @property ticker - Currency ticker. + * @property nickname - Personalized network name. */ export interface ProviderConfig { rpcTarget?: string; @@ -63,7 +62,6 @@ export interface NetworkProperties { * @type NetworkConfig * * Network controller configuration - * * @property infuraProjectId - an Infura project ID * @property providerConfig - web3-provider-engine configuration */ @@ -76,7 +74,6 @@ export interface NetworkConfig extends BaseConfig { * @type NetworkState * * Network controller state - * * @property network - Network ID as per net_version * @property isCustomNetwork - Identifies if the network is a custom network * @property provider - RPC URL and network name provider settings @@ -221,10 +218,10 @@ export class NetworkController extends BaseController< provider: any; /** - * Creates a NetworkController instance + * Creates a NetworkController instance. * - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor(config?: Partial, state?: Partial) { super(config, state); @@ -239,11 +236,11 @@ export class NetworkController extends BaseController< } /** - * Sets a new configuration for web3-provider-engine + * Sets a new configuration for web3-provider-engine. * - * TODO: Replace this wth a method + * TODO: Replace this wth a method. * - * @param providerConfig - web3-provider-engine configuration + * @param providerConfig - The web3-provider-engine configuration. */ set providerConfig(providerConfig: ProviderConfig) { this.internalProviderConfig = providerConfig; @@ -258,7 +255,7 @@ export class NetworkController extends BaseController< } /** - * Refreshes the current network code + * Refreshes the current network code. */ async lookupNetwork() { /* istanbul ignore if */ @@ -278,9 +275,9 @@ export class NetworkController extends BaseController< } /** - * Convenience method to update provider network type settings + * Convenience method to update provider network type settings. * - * @param type - Human readable network name + * @param type - Human readable network name. */ setProviderType(type: NetworkType) { const { @@ -299,12 +296,12 @@ export class NetworkController extends BaseController< } /** - * Convenience method to update provider RPC settings + * Convenience method to update provider RPC settings. * - * @param rpcTarget - RPC endpoint URL - * @param chainId - Network ID as per EIP-155 - * @param ticker? - Currency ticker - * @param nickname? - Personalized network name + * @param rpcTarget - The RPC endpoint URL. + * @param chainId - The chain ID as per EIP-155. + * @param ticker - The currency ticker. + * @param nickname - Personalized network name. */ setRpcTarget( rpcTarget: string, diff --git a/src/notification/NotificationController.ts b/src/notification/NotificationController.ts index 34959dbefa..d8a7375c62 100644 --- a/src/notification/NotificationController.ts +++ b/src/notification/NotificationController.ts @@ -54,10 +54,10 @@ export class NotificationController extends BaseController< NotificationState > { /** - * Creates a NotificationController instance + * Creates a NotificationController instance. * - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor(config: NotificationConfig, state?: NotificationState) { super(config, state || defaultState); @@ -70,8 +70,6 @@ export class NotificationController extends BaseController< * to check if there are any new notifications/announcements * if yes, the new notification will be added to the state with a flag indicating * that the notification is not seen by the user. - * - * @param allNotifications */ private _addNotifications(): void { const newNotifications: StateNotificationMap = {}; @@ -95,7 +93,7 @@ export class NotificationController extends BaseController< * Updates the status of the status of the specified notifications * once it is read by the user. * - * @param viewedIds + * @param viewedIds - The notification IDs to mark as viewed. */ updateViewed(viewedIds: viewedNotification): void { const stateNotifications = this.state.notifications; diff --git a/src/third-party/EnsController.ts b/src/third-party/EnsController.ts index 88d1176d8d..36d21a8934 100644 --- a/src/third-party/EnsController.ts +++ b/src/third-party/EnsController.ts @@ -9,7 +9,6 @@ import { * @type EnsEntry * * ENS entry representation - * * @property chainId - Id of the associated chain * @property ensName - The ENS name * @property address - Hex address with the ENS name, or null @@ -24,7 +23,6 @@ export interface EnsEntry { * @type EnsState * * ENS controller state - * * @property ensEntries - Object of ENS entry objects */ export interface EnsState extends BaseState { @@ -42,10 +40,10 @@ export class EnsController extends BaseController { name = 'EnsController'; /** - * Creates an EnsController instance + * Creates an EnsController instance. * - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor(config?: Partial, state?: Partial) { super(config, state); @@ -56,7 +54,7 @@ export class EnsController extends BaseController { } /** - * Remove all chain Ids and ENS entries from state + * Remove all chain Ids and ENS entries from state. */ clear() { this.update({ ensEntries: {} }); @@ -65,10 +63,9 @@ export class EnsController extends BaseController { /** * Delete an ENS entry. * - * @param chainId - Parent chain of the ENS entry to delete - * @param ensName - Name of the ENS entry to delete - * - * @returns - Boolean indicating if the entry was deleted + * @param chainId - Parent chain of the ENS entry to delete. + * @param ensName - Name of the ENS entry to delete. + * @returns Boolean indicating if the entry was deleted. */ delete(chainId: string, ensName: string): boolean { const normalizedEnsName = normalizeEnsName(ensName); @@ -94,10 +91,9 @@ export class EnsController extends BaseController { /** * Retrieve a DNS entry. * - * @param chainId - Parent chain of the ENS entry to retrieve - * @param ensName - Name of the ENS entry to retrieve - * - * @returns - The EnsEntry or null if it does not exist + * @param chainId - Parent chain of the ENS entry to retrieve. + * @param ensName - Name of the ENS entry to retrieve. + * @returns The EnsEntry or null if it does not exist. */ get(chainId: string, ensName: string): EnsEntry | null { const normalizedEnsName = normalizeEnsName(ensName); @@ -114,11 +110,10 @@ export class EnsController extends BaseController { * * A null address indicates that the ENS name does not resolve. * - * @param chainId - Id of the associated chain - * @param ensName - The ENS name - * @param address - Associated address (or null) to add or update - * - * @returns - Boolean indicating if the entry was set + * @param chainId - Id of the associated chain. + * @param ensName - The ENS name. + * @param address - Associated address (or null) to add or update. + * @returns Boolean indicating if the entry was set. */ set(chainId: string, ensName: string, address: string | null): boolean { if ( diff --git a/src/third-party/PhishingController.ts b/src/third-party/PhishingController.ts index b3834a11de..83910c172f 100644 --- a/src/third-party/PhishingController.ts +++ b/src/third-party/PhishingController.ts @@ -9,7 +9,6 @@ import { safelyExecute } from '../util'; * * Configuration response from the eth-phishing-detect package * consisting of approved and unapproved website origins - * * @property blacklist - List of unapproved origins * @property fuzzylist - List of fuzzy-matched unapproved origins * @property tolerance - Fuzzy match tolerance level @@ -28,7 +27,6 @@ export interface EthPhishingResponse { * @type PhishingConfig * * Phishing controller configuration - * * @property interval - Polling interval used to fetch new block / approve lists */ export interface PhishingConfig extends BaseConfig { @@ -39,7 +37,6 @@ export interface PhishingConfig extends BaseConfig { * @type PhishingState * * Phishing controller state - * * @property phishing - eth-phishing-detect configuration * @property whitelist - array of temporarily-approved origins */ @@ -68,10 +65,10 @@ export class PhishingController extends BaseController< name = 'PhishingController'; /** - * Creates a PhishingController instance + * Creates a PhishingController instance. * - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( config?: Partial, @@ -89,9 +86,9 @@ export class PhishingController extends BaseController< } /** - * Starts a new polling interval + * Starts a new polling interval. * - * @param interval - Polling interval used to fetch new approval lists + * @param interval - Polling interval used to fetch new approval lists. */ async poll(interval?: number): Promise { interval && this.configure({ interval }, false, false); @@ -103,10 +100,10 @@ export class PhishingController extends BaseController< } /** - * Determines if a given origin is unapproved + * Determines if a given origin is unapproved. * - * @param origin - Domain origin of a website - * @returns - True if the origin is an unapproved origin + * @param origin - Domain origin of a website. + * @returns Whether the origin is an unapproved origin. */ test(origin: string): boolean { const punycodeOrigin = toASCII(origin); @@ -117,7 +114,9 @@ export class PhishingController extends BaseController< } /** - * Temporarily marks a given origin as approved + * Temporarily marks a given origin as approved. + * + * @param origin - The origin to mark as approved. */ bypass(origin: string) { const punycodeOrigin = toASCII(origin); @@ -129,9 +128,7 @@ export class PhishingController extends BaseController< } /** - * Updates lists of approved and unapproved website origins - * - * @returns Promise resolving when this operation completes + * Updates lists of approved and unapproved website origins. */ async updatePhishingLists() { if (this.disabled) { diff --git a/src/transaction/TransactionController.test.ts b/src/transaction/TransactionController.test.ts index 2130ee54e1..cf81926069 100644 --- a/src/transaction/TransactionController.test.ts +++ b/src/transaction/TransactionController.test.ts @@ -78,6 +78,12 @@ jest.mock('eth-query', () => }), ); +/** + * Create a mock implementation of `fetch` that always returns the same data. + * + * @param data - The mock data to return. + * @returns The mock `fetch` implementation. + */ function mockFetch(data: any) { return jest.fn().mockImplementation(() => Promise.resolve({ @@ -87,6 +93,12 @@ function mockFetch(data: any) { ); } +/** + * Create a mock implementation of `fetch` that returns different mock data for each URL. + * + * @param data - A map of mock data, keyed by URL. + * @returns The mock `fetch` implementation. + */ function mockFetchs(data: any) { return jest.fn().mockImplementation((key) => Promise.resolve({ diff --git a/src/transaction/TransactionController.ts b/src/transaction/TransactionController.ts index b92b1ee0ff..f26d06a934 100644 --- a/src/transaction/TransactionController.ts +++ b/src/transaction/TransactionController.ts @@ -35,7 +35,6 @@ const HARDFORK = 'london'; /** * @type Result - * * @property result - Promise resolving to a new transaction hash * @property transactionMeta - Meta information about this new transaction */ @@ -46,7 +45,6 @@ export interface Result { /** * @type Fetch All Options - * * @property fromBlock - String containing a specific block decimal number * @property etherscanApiKey - API key to be used to fetch token transactions */ @@ -59,7 +57,6 @@ export interface FetchAllOptions { * @type Transaction * * Transaction representation - * * @property chainId - Network ID as per EIP-155 * @property data - Data to pass with this transaction * @property from - Address to send this transaction from @@ -144,7 +141,6 @@ type TransactionMetaBase = { * @type TransactionMeta * * TransactionMeta representation - * * @property error - Synthesized error information for failed transactions * @property id - Generated UUID associated with this transaction * @property networkID - Network code as per EIP-155 for this transaction @@ -184,7 +180,6 @@ export type TransactionMeta = * @property contractAddress - Address of the contract * @property cumulativeGasUsed - Amount of gas used * @property confirmations - Number of confirmations - * */ export interface EtherscanTransactionMeta { blockNumber: string; @@ -213,7 +208,6 @@ export interface EtherscanTransactionMeta { * @type TransactionConfig * * Transaction controller configuration - * * @property interval - Polling interval used to fetch new currency rate * @property provider - Provider used to create a new underlying EthQuery instance * @property sign - Method used to sign transactions @@ -228,7 +222,6 @@ export interface TransactionConfig extends BaseConfig { * @type MethodData * * Method data registry object - * * @property registryMethod - Registry method raw string * @property parsedRegistryMethod - Registry method object, containing name and method arguments */ @@ -241,7 +234,6 @@ export interface MethodData { * @type TransactionState * * Transaction controller state - * * @property transactions - A list of TransactionMeta objects * @property methodData - Object containing all known method data information */ @@ -295,12 +287,12 @@ export class TransactionController extends BaseController< /** * Normalizes the transaction information from etherscan - * to be compatible with the TransactionMeta interface + * to be compatible with the TransactionMeta interface. * - * @param txMeta - Object containing the transaction information - * @param currentNetworkID - string representing the current network id - * @param currentChainId - string representing the current chain id - * @returns - TransactionMeta + * @param txMeta - The transaction. + * @param currentNetworkID - The current network ID. + * @param currentChainId - The current chain ID. + * @returns The normalized transaction. */ private normalizeTx( txMeta: EtherscanTransactionMeta, @@ -407,14 +399,14 @@ export class TransactionController extends BaseController< ) => Promise; /** - * Creates a TransactionController instance + * Creates a TransactionController instance. * - * @param options - * @param options.getNetworkState - Gets the state of the network controller - * @param options.onNetworkStateChange - Allows subscribing to network controller state changes - * @param options.getProvider - Returns a provider for the current network - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param options - The controller options. + * @param options.getNetworkState - Gets the state of the network controller. + * @param options.onNetworkStateChange - Allows subscribing to network controller state changes. + * @param options.getProvider - Returns a provider for the current network. + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor( { @@ -453,9 +445,9 @@ export class TransactionController extends BaseController< } /** - * Starts a new polling interval + * Starts a new polling interval. * - * @param interval - Polling interval used to fetch new transaction statuses + * @param interval - The polling interval used to fetch new transaction statuses. */ async poll(interval?: number): Promise { interval && this.configure({ interval }, false, false); @@ -467,10 +459,10 @@ export class TransactionController extends BaseController< } /** - * Handle new method data request + * Handle new method data request. * - * @param fourBytePrefix - String corresponding to method prefix - * @returns - Promise resolving to method data object corresponding to signature prefix + * @param fourBytePrefix - The method prefix. + * @returns The method data object corresponding to the given signature prefix. */ async handleMethodData(fourBytePrefix: string): Promise { const releaseLock = await this.mutex.acquire(); @@ -497,10 +489,10 @@ export class TransactionController extends BaseController< * unique transaction id will be generated, and gas and gasPrice will be calculated * if not provided. If A `:unapproved` hub event will be emitted once added. * - * @param transaction - Transaction object to add - * @param origin - Domain origin to append to the generated TransactionMeta - * @param deviceConfirmedOn - enum to indicate what device the transaction was confirmed to append to the generated TransactionMeta - * @returns - Object containing a promise resolving to the transaction hash if approved + * @param transaction - The transaction object to add. + * @param origin - The domain origin to append to the generated TransactionMeta. + * @param deviceConfirmedOn - An enum to indicate what device the transaction was confirmed to append to the generated TransactionMeta. + * @returns Object containing a promise resolving to the transaction hash if approved. */ async addTransaction( transaction: Transaction, @@ -579,11 +571,12 @@ export class TransactionController extends BaseController< } /** - * @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 * transaction type to use. + * * @returns {Common} common configuration object */ @@ -612,8 +605,7 @@ export class TransactionController extends BaseController< * using the sign configuration property, then published to the blockchain. * A `:finished` hub event is fired after success or failure. * - * @param transactionID - ID of the transaction to approve - * @returns - Promise resolving when this operation completes + * @param transactionID - The ID of the transaction to approve. */ async approveTransaction(transactionID: string) { const { transactions } = this.state; @@ -703,7 +695,7 @@ export class TransactionController extends BaseController< * Cancels a transaction based on its ID by setting its status to "rejected" * and emitting a `:finished` hub event. * - * @param transactionID - ID of the transaction to cancel + * @param transactionID - The ID of the transaction to cancel. */ cancelTransaction(transactionID: string) { const transactionMeta = this.state.transactions.find( @@ -724,7 +716,8 @@ export class TransactionController extends BaseController< * Attempts to cancel a transaction based on its ID by setting its status to "rejected" * and emitting a `:finished` hub event. * - * @param transactionID - ID of the transaction to cancel + * @param transactionID - The ID of the transaction to cancel. + * @param gasValues - The gas values to use for the cancellation transation. */ async stopTransaction( transactionID: string, @@ -821,9 +814,10 @@ export class TransactionController extends BaseController< } /** - * Attemps to speed up a transaction increasing transaction gasPrice by ten percent + * Attemps to speed up a transaction increasing transaction gasPrice by ten percent. * - * @param transactionID - ID of the transaction to speed up + * @param transactionID - The ID of the transaction to speed up. + * @param gasValues - The gas values to use for the speed up transation. */ async speedUpTransaction( transactionID: string, @@ -944,10 +938,10 @@ export class TransactionController extends BaseController< } /** - * Estimates required gas for a given transaction + * Estimates required gas for a given transaction. * - * @param transaction - Transaction object to estimate gas for - * @returns - Promise resolving to an object containing gas and gasPrice + * @param transaction - The transaction to estimate gas for. + * @returns The gas and gas price. */ async estimateGas(transaction: Transaction) { const estimatedTransaction = { ...transaction }; @@ -1016,11 +1010,8 @@ export class TransactionController extends BaseController< } /** - * Resiliently checks all submitted transactions on the blockchain - * and verifies that it has been included in a block - * when that happens, the tx status is updated to confirmed - * - * @returns - Promise resolving when this operation completes + * Check the status of submitted transactions on the network to determine whether they have + * been included in a block. Any that have been included in a block are marked as confirmed. */ async queryTransactionStatuses() { const { transactions } = this.state; @@ -1059,9 +1050,9 @@ export class TransactionController extends BaseController< } /** - * Updates an existing transaction in state + * Updates an existing transaction in state. * - * @param transactionMeta - New transaction meta to store in state + * @param transactionMeta - The new transaction to store in state. */ updateTransaction(transactionMeta: TransactionMeta) { const { transactions } = this.state; @@ -1075,9 +1066,10 @@ export class TransactionController extends BaseController< } /** - * Removes all transactions from state, optionally based on the current network + * Removes all transactions from state, optionally based on the current network. * - * @param ignoreNetwork - Ignores network + * @param ignoreNetwork - Determines whether to wipe all transactions, or just those on the + * current network. If `true`, all transactions are wiped. */ wipeTransactions(ignoreNetwork?: boolean) { /* istanbul ignore next */ @@ -1103,12 +1095,13 @@ export class TransactionController extends BaseController< } /** - * Gets all transactions from etherscan for a specific address - * optionally starting from a specific block + * Get transactions from Etherscan for the given address. By default all transactions are + * returned, but the `fromBlock` option can be given to filter just for transactions from a + * specific block onward. * - * @param address - string representing the address to fetch the transactions from - * @param opt - Object containing optional data, fromBlock and Alethio API key - * @returns - Promise resolving to an string containing the block number of the latest incoming transaction. + * @param address - The address to fetch the transactions for. + * @param opt - Object containing optional data, fromBlock and Etherscan API key. + * @returns The block number of the latest incoming transaction. */ async fetchAll( address: string, @@ -1205,8 +1198,9 @@ export class TransactionController extends BaseController< * same nonce, created on the same day, per network. Not accounting for transactions of the same * nonce, same day and network combo can result in confusing or broken experiences * in the UI. The transactions are then updated using the BaseController update. - * @param transactions - array of transactions to be applied to the state - * @returns Array of TransactionMeta with the desired length. + * + * @param transactions - The transactions to be applied to the state. + * @returns The trimmed list of transactions. */ private trimTransactionsForState( transactions: TransactionMeta[], @@ -1235,9 +1229,10 @@ export class TransactionController extends BaseController< } /** - * Method to determine if the transaction is in a final state - * @param status - Transaction status - * @returns boolean if the transaction is in a final state + * Determines if the transaction is in a final state. + * + * @param status - The transaction status. + * @returns Whether the transaction is in a final state. */ private isFinalState(status: TransactionStatus): boolean { return ( @@ -1249,9 +1244,10 @@ export class TransactionController extends BaseController< } /** - * Method to verify the state of a transaction using the Blockchain as a source of truth - * @param meta Local transaction to verify data in blockchain - * @returns Promise with [TransactionMeta, boolean] + * Method to verify the state of a transaction using the Blockchain as a source of truth. + * + * @param meta - The local transaction to verify on the blockchain. + * @returns A tuple containing the updated transaction, and whether or not an update was required. */ private async blockchainTransactionStateReconciler( meta: TransactionMeta, @@ -1319,8 +1315,9 @@ export class TransactionController extends BaseController< * According to the Web3 docs: * TRUE if the transaction was successful, FALSE if the EVM reverted the transaction. * The receipt is not available for pending transactions and returns null. - * @param txHash Transaction hash - * @returns Promise indicating if the transaction have failed + * + * @param txHash - The transaction hash. + * @returns Whether the transaction has failed. */ private async checkTxReceiptStatusIsFailed( txHash: string | undefined, @@ -1336,10 +1333,11 @@ export class TransactionController extends BaseController< } /** - * Method to verify the state of transactions using Etherscan as a source of truth - * @param remoteTxs Array of transactions from remote source - * @param localTxs Array of transactions stored locally - * @returns [boolean, TransactionMeta[]] + * Method to verify the state of transactions using Etherscan as a source of truth. + * + * @param remoteTxs - Transactions to reconcile that are from a remote source. + * @param localTxs - Transactions to reconcile that are local. + * @returns A tuple containing a boolean indicating whether or not an update was required, and the updated transaction. */ private etherscanTransactionStateReconciler( remoteTxs: TransactionMeta[], @@ -1369,10 +1367,11 @@ export class TransactionController extends BaseController< /** * Get all transactions that are in the remote transactions array - * but not in the local transactions array - * @param remoteTxs - Array of transactions from remote source - * @param localTxs - Array of transactions stored locally - * @returns TransactionMeta array + * but not in the local transactions array. + * + * @param remoteTxs - Array of transactions from remote source. + * @param localTxs - Array of transactions stored locally. + * @returns The new transactions. */ private getNewTransactions( remoteTxs: TransactionMeta[], @@ -1390,9 +1389,10 @@ export class TransactionController extends BaseController< * Get all the transactions that are locally outdated with respect * to a remote source (etherscan or blockchain). The returned array * contains the transactions with the updated data. - * @param remoteTxs - Array of transactions from remote source - * @param localTxs - Array of transactions stored locally - * @returns TransactionMeta array + * + * @param remoteTxs - Array of transactions from remote source. + * @param localTxs - Array of transactions stored locally. + * @returns The updated transactions. */ private getUpdatedTransactions( remoteTxs: TransactionMeta[], @@ -1410,10 +1410,11 @@ export class TransactionController extends BaseController< } /** - * Verifies if a local transaction is outdated with respect to the remote transaction - * @param remoteTx - Remote transaction from Etherscan - * @param localTx - Local transaction - * @returns boolean + * Verifies if a local transaction is outdated with respect to the remote transaction. + * + * @param remoteTx - The remote transaction from Etherscan. + * @param localTx - The local transaction. + * @returns Whether the transaction is outdated. */ private isTransactionOutdated( remoteTx: TransactionMeta, @@ -1433,12 +1434,13 @@ export class TransactionController extends BaseController< } /** - * Verifies if the status of a local transaction is outdated with respect to the remote transaction - * @param remoteTxHash - Remote transaction hash - * @param localTxHash - Local transaction hash - * @param remoteTxStatus - Remote transaction status - * @param localTxStatus - Local transaction status - * @returns boolean + * Verifies if the status of a local transaction is outdated with respect to the remote transaction. + * + * @param remoteTxHash - Remote transaction hash. + * @param localTxHash - Local transaction hash. + * @param remoteTxStatus - Remote transaction status. + * @param localTxStatus - Local transaction status. + * @returns Whether the status is outdated. */ private isStatusOutdated( remoteTxHash: string | undefined, @@ -1450,10 +1452,11 @@ export class TransactionController extends BaseController< } /** - * Verifies if the gas data of a local transaction is outdated with respect to the remote transaction - * @param remoteGasUsed - Remote gas used in the transaction - * @param localGasUsed - Local gas used in the transaction - * @returns boolean + * Verifies if the gas data of a local transaction is outdated with respect to the remote transaction. + * + * @param remoteGasUsed - Remote gas used in the transaction. + * @param localGasUsed - Local gas used in the transaction. + * @returns Whether the gas data is outdated. */ private isGasDataOutdated( remoteGasUsed: string | undefined, diff --git a/src/user/AddressBookController.ts b/src/user/AddressBookController.ts index 659acc8a82..96e9025a44 100644 --- a/src/user/AddressBookController.ts +++ b/src/user/AddressBookController.ts @@ -9,7 +9,6 @@ import { BaseController, BaseConfig, BaseState } from '../BaseController'; * @type ContactEntry * * ContactEntry representation - * * @property address - Hex address of a recipient account * @property name - Nickname associated with this address * @property importTime - Data time when an account as created/imported @@ -24,7 +23,6 @@ export interface ContactEntry { * @type AddressBookEntry * * AddressBookEntry representation - * * @property address - Hex address of a recipient account * @property name - Nickname associated with this address * @property chainId - Chain id identifies the current chain @@ -43,7 +41,6 @@ export interface AddressBookEntry { * @type AddressBookState * * Address book controller state - * * @property addressBook - Array of contact entry objects */ export interface AddressBookState extends BaseState { @@ -63,10 +60,10 @@ export class AddressBookController extends BaseController< name = 'AddressBookController'; /** - * Creates an AddressBookController instance + * Creates an AddressBookController instance. * - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor(config?: Partial, state?: Partial) { super(config, state); @@ -77,17 +74,18 @@ export class AddressBookController extends BaseController< } /** - * Remove all contract entries + * Remove all contract entries. */ clear() { this.update({ addressBook: {} }); } /** - * Remove a contract entry by address + * Remove a contract entry by address. * - * @param chainId - Chain id identifies the current chain - * @param address - Recipient address to delete + * @param chainId - Chain id identifies the current chain. + * @param address - Recipient address to delete. + * @returns Whether the entry was deleted. */ delete(chainId: string, address: string) { address = toChecksumHexAddress(address); @@ -111,13 +109,13 @@ export class AddressBookController extends BaseController< } /** - * Add or update a contact entry by address + * Add or update a contact entry by address. * - * @param address - Recipient address to add or update - * @param name - Nickname to associate with this address - * @param chainId - Chain id identifies the current chain - * @param memo - User's note about address - * @returns - Boolean indicating if the address was successfully set + * @param address - Recipient address to add or update. + * @param name - Nickname to associate with this address. + * @param chainId - Chain id identifies the current chain. + * @param memo - User's note about address. + * @returns Boolean indicating if the address was successfully set. */ set(address: string, name: string, chainId = '1', memo = '') { address = toChecksumHexAddress(address); diff --git a/src/user/PreferencesController.ts b/src/user/PreferencesController.ts index f65b78eb18..46691b3df2 100644 --- a/src/user/PreferencesController.ts +++ b/src/user/PreferencesController.ts @@ -5,11 +5,11 @@ import { ContactEntry } from './AddressBookController'; /** * Custom RPC network information * - * @param rpcUrl - RPC target URL - * @param chainId? - Network ID as per EIP-155 - * @param ticker? - Currency ticker - * @param nickname? - Personalized network name - * @param rpcPrefs? - Personalized preferences + * @property rpcUrl - RPC target URL. + * @property chainId - Network ID as per EIP-155 + * @property nickname - Personalized network name. + * @property ticker - Currency ticker. + * @property rpcPrefs - Personalized preferences. */ export interface FrequentRpc { rpcUrl: string; @@ -22,7 +22,7 @@ export interface FrequentRpc { /** * Custom RPC network preferences * - * @param blockExplorerUrl - Block explorer URL + * @param blockExplorerUrl - Block explorer URL. */ export interface RpcPreferences { blockExplorerUrl: string; @@ -32,7 +32,6 @@ export interface RpcPreferences { * @type PreferencesState * * Preferences controller state - * * @property featureFlags - Map of specific features to enable or disable * @property frequentRpcList - A list of custom RPCs to provide the user * @property identities - Map of addresses to ContactEntry objects @@ -62,10 +61,10 @@ export class PreferencesController extends BaseController< name = 'PreferencesController'; /** - * Creates a PreferencesController instance + * Creates a PreferencesController instance. * - * @param config - Initial options used to configure this controller - * @param state - Initial state to set on this controller + * @param config - Initial options used to configure this controller. + * @param state - Initial state to set on this controller. */ constructor(config?: Partial, state?: Partial) { super(config, state); @@ -82,9 +81,9 @@ export class PreferencesController extends BaseController< } /** - * Adds identities to state + * Adds identities to state. * - * @param addresses - List of addresses to use to generate new identities + * @param addresses - List of addresses to use to generate new identities. */ addIdentities(addresses: string[]) { const { identities } = this.state; @@ -105,9 +104,9 @@ export class PreferencesController extends BaseController< } /** - * Removes an identity from state + * Removes an identity from state. * - * @param address - Address of the identity to remove + * @param address - Address of the identity to remove. */ removeIdentity(address: string) { address = toChecksumHexAddress(address); @@ -123,10 +122,10 @@ export class PreferencesController extends BaseController< } /** - * Associates a new label with an identity + * Associates a new label with an identity. * - * @param address - Address of the identity to associate - * @param label - New label to assign + * @param address - Address of the identity to associate. + * @param label - New label to assign. */ setAccountLabel(address: string, label: string) { address = toChecksumHexAddress(address); @@ -137,10 +136,10 @@ export class PreferencesController extends BaseController< } /** - * Enable or disable a specific feature flag + * Enable or disable a specific feature flag. * - * @param feature - Feature to toggle - * @param activated - Value to assign + * @param feature - Feature to toggle. + * @param activated - Value to assign. */ setFeatureFlag(feature: string, activated: boolean) { const oldFeatureFlags = this.state.featureFlags; @@ -149,10 +148,10 @@ export class PreferencesController extends BaseController< } /** - * Synchronizes the current identity list with new identities + * Synchronizes the current identity list with new identities. * - * @param addresses - List of addresses corresponding to identities to sync - * @returns - Newly-selected address after syncing + * @param addresses - List of addresses corresponding to identities to sync. + * @returns Newly-selected address after syncing. */ syncIdentities(addresses: string[]) { addresses = addresses.map((address: string) => @@ -192,7 +191,7 @@ export class PreferencesController extends BaseController< * is unset, or if it refers to an identity that was removed, it will be set to the first * identity. * - * @param addresses - List of addresses to use as a basis for each identity + * @param addresses - List of addresses to use as a basis for each identity. */ updateIdentities(addresses: string[]) { addresses = addresses.map((address: string) => @@ -218,14 +217,13 @@ export class PreferencesController extends BaseController< } /** - * Adds custom RPC URL to state - * - * @param url - Custom RPC URL - * @param chainId? - Network ID as per EIP-155 - * @param ticker? - Currency ticker - * @param nickname? - Personalized network name - * @param rpcPrefs? - Personalized preferences + * Adds custom RPC URL to state. * + * @param url - The custom RPC URL. + * @param chainId - The chain ID of the network, as per EIP-155. + * @param ticker - Currency ticker. + * @param nickname - Personalized network name. + * @param rpcPrefs - Personalized preferences. */ addToFrequentRpcList( url: string, @@ -253,9 +251,9 @@ export class PreferencesController extends BaseController< } /** - * Removes custom RPC URL from state + * Removes custom RPC URL from state. * - * @param url - Custom RPC URL + * @param url - Custom RPC URL. */ removeFromFrequentRpcList(url: string) { const { frequentRpcList } = this.state; @@ -269,27 +267,27 @@ export class PreferencesController extends BaseController< } /** - * Sets selected address + * Sets selected address. * - * @param selectedAddress - Ethereum address + * @param selectedAddress - Ethereum address. */ setSelectedAddress(selectedAddress: string) { this.update({ selectedAddress: toChecksumHexAddress(selectedAddress) }); } /** - * Sets new IPFS gateway + * Sets new IPFS gateway. * - * @param ipfsGateway - IPFS gateway string + * @param ipfsGateway - IPFS gateway string. */ setIpfsGateway(ipfsGateway: string) { this.update({ ipfsGateway }); } /** - * Toggle the token detection setting to use dynamic token list + * Toggle the token detection setting to use dynamic token list. * - * @param useStaticTokenList - IPFS gateway string + * @param useStaticTokenList - IPFS gateway string. */ setUseStaticTokenList(useStaticTokenList: boolean) { this.update({ useStaticTokenList }); diff --git a/src/util.ts b/src/util.ts index 5319254674..56ec3fccbe 100644 --- a/src/util.ts +++ b/src/util.ts @@ -42,23 +42,22 @@ const NORMALIZERS: { [param in keyof Transaction]: any } = { }; /** - * Converts a BN object to a hex string with a '0x' prefix - * - * @param inputBn - BN instance to convert to a hex string - * @returns - '0x'-prefixed hex string + * Converts a BN object to a hex string with a '0x' prefix. * + * @param inputBn - BN instance to convert to a hex string. + * @returns A '0x'-prefixed hex string. */ export function BNToHex(inputBn: any) { return addHexPrefix(inputBn.toString(16)); } /** - * Used to multiply a BN by a fraction + * Used to multiply a BN by a fraction. * - * @param targetBN - Number to multiply by a fraction - * @param numerator - Numerator of the fraction multiplier - * @param denominator - Denominator of the fraction multiplier - * @returns - Product of the multiplication + * @param targetBN - Number to multiply by a fraction. + * @param numerator - Numerator of the fraction multiplier. + * @param denominator - Denominator of the fraction multiplier. + * @returns Product of the multiplication. */ export function fractionBN( targetBN: any, @@ -71,10 +70,10 @@ export function fractionBN( } /** - * Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts + * Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts. * - * @param n - The base 10 number to convert to WEI - * @returns - The number in WEI, as a BN + * @param n - The base 10 number to convert to WEI. + * @returns The number in WEI, as a BN. */ export function gweiDecToWEIBN(n: number | string) { if (Number.isNaN(n)) { @@ -107,9 +106,10 @@ export function gweiDecToWEIBN(n: number | string) { } /** - * Used to convert values from wei hex format to dec gwei format - * @param hex - value in hex wei - * @returns - value in dec gwei as string + * Used to convert values from wei hex format to dec gwei format. + * + * @param hex - The value in hex wei. + * @returns The value in dec gwei as string. */ export function weiHexToGweiDec(hex: string) { const hexWei = new BN(stripHexPrefix(hex), 16); @@ -117,12 +117,12 @@ export function weiHexToGweiDec(hex: string) { } /** - * Return a URL that can be used to obtain ETH for a given network + * Return a URL that can be used to obtain ETH for a given network. * - * @param networkCode - Network code of desired network - * @param address - Address to deposit obtained ETH - * @param amount - How much ETH is desired - * @returns - URL to buy ETH based on network + * @param networkCode - Network code of desired network. + * @param address - Address to deposit obtained ETH. + * @param amount - How much ETH is desired. + * @returns URL to buy ETH based on network. */ export function getBuyURL( networkCode = '1', @@ -146,11 +146,11 @@ export function getBuyURL( } /** - * Return a URL that can be used to fetch ETH transactions + * Return a URL that can be used to fetch ETH transactions. * - * @param networkType - Network type of desired network - * @param urlParams - Parameters used to construct the URL - * @returns - URL to fetch the access the endpoint + * @param networkType - Network type of desired network. + * @param urlParams - The parameters used to construct the URL. + * @returns URL to fetch the access the endpoint. */ export function getEtherscanApiUrl( networkType: string, @@ -173,12 +173,13 @@ export function getEtherscanApiUrl( } /** - * Handles the fetch of incoming transactions + * Handles the fetch of incoming transactions. * - * @param networkType - Network type of desired network - * @param address - Address to get the transactions from - * @param opt? - Object that can contain fromBlock and Etherscan service API key - * @returns - Responses for both ETH and ERC20 token transactions + * @param networkType - Network type of desired network. + * @param address - Address to get the transactions from. + * @param txHistoryLimit - The maximum number of transactions to fetch. + * @param opt - Object that can contain fromBlock and Etherscan service API key. + * @returns Responses for both ETH and ERC20 token transactions. */ export async function handleTransactionFetch( networkType: string, @@ -234,22 +235,20 @@ export async function handleTransactionFetch( } /** - * Converts a hex string to a BN object - * - * @param inputHex - Number represented as a hex string - * @returns - A BN instance + * Converts a hex string to a BN object. * + * @param inputHex - Number represented as a hex string. + * @returns A BN instance. */ export function hexToBN(inputHex: string) { return new BN(stripHexPrefix(inputHex), 16); } /** - * A helper function that converts hex data to human readable string - * - * @param hex - The hex string to convert to string - * @returns - A human readable string conversion + * A helper function that converts hex data to human readable string. * + * @param hex - The hex string to convert to string. + * @returns A human readable string conversion. */ export function hexToText(hex: string) { try { @@ -263,10 +262,10 @@ export function hexToText(hex: string) { } /** - * Normalizes properties on a Transaction object + * Normalizes properties on a Transaction object. * - * @param transaction - Transaction object to normalize - * @returns - Normalized Transaction object + * @param transaction - Transaction object to normalize. + * @returns Normalized Transaction object. */ export function normalizeTransaction(transaction: Transaction) { const normalizedTransaction: Transaction = { from: '' }; @@ -280,12 +279,12 @@ export function normalizeTransaction(transaction: Transaction) { } /** - * Execute and return an asynchronous operation without throwing errors + * Execute and return an asynchronous operation without throwing errors. * - * @param operation - Function returning a Promise - * @param logError - Determines if the error should be logged - * @param retry - Function called if an error is caught - * @returns - Promise resolving to the result of the async operation + * @param operation - Function returning a Promise. + * @param logError - Determines if the error should be logged. + * @param retry - Function called if an error is caught. + * @returns Promise resolving to the result of the async operation. */ export async function safelyExecute( operation: () => Promise, @@ -305,13 +304,12 @@ export async function safelyExecute( } /** - * Execute and return an asynchronous operation with a timeout + * Execute and return an asynchronous operation with a timeout. * - * @param operation - Function returning a Promise - * @param logError - Determines if the error should be logged - * @param retry - Function called if an error is caught - * @param timeout - Timeout to fail the operation - * @returns - Promise resolving to the result of the async operation + * @param operation - Function returning a Promise. + * @param logError - Determines if the error should be logged. + * @param timeout - Timeout to fail the operation. + * @returns Promise resolving to the result of the async operation. */ export async function safelyExecuteWithTimeout( operation: () => Promise, @@ -336,6 +334,12 @@ export async function safelyExecuteWithTimeout( } } +/** + * Convert an address to a checksummed hexidecimal address. + * + * @param address - The address to convert. + * @returns A 0x-prefixed hexidecimal checksummed address. + */ export function toChecksumHexAddress(address: string) { const hexPrefixed = addHexPrefix(address); if (!isHexString(hexPrefixed)) { @@ -356,11 +360,11 @@ export function toChecksumHexAddress(address: string) { * 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' - * is prepended to the string - * @returns {boolean} whether or not the input is a valid hex address + * + * @param possibleAddress - Input parameter to check against. + * @param options - The validation options. + * @param options.allowNonPrefixed - If true will first ensure '0x' is prepended to the string. + * @returns Whether or not the input is a valid hex address. */ export function isValidHexAddress( possibleAddress: string, @@ -380,7 +384,7 @@ export function isValidHexAddress( * Validates a Transaction object for required properties and throws in * the event of any validation error. * - * @param transaction - Transaction object to validate + * @param transaction - Transaction object to validate. */ export function validateTransaction(transaction: Transaction) { if ( @@ -439,9 +443,8 @@ export function validateTransaction(transaction: Transaction) { * A helper function that converts rawmessageData buffer data to a hex, or just returns the data if * it is already formatted as a hex. * - * @param data - The buffer data to convert to a hex - * @returns - A hex string conversion of the buffer data - * + * @param data - The buffer data to convert to a hex. + * @returns A hex string conversion of the buffer data. */ export function normalizeMessageData(data: string) { try { @@ -459,7 +462,7 @@ export function normalizeMessageData(data: string) { * Validates a PersonalMessageParams and MessageParams objects for required properties and throws in * the event of any validation error. * - * @param messageData - PersonalMessageParams object to validate + * @param messageData - PersonalMessageParams object to validate. */ export function validateSignMessageData( messageData: PersonalMessageParams | MessageParams, @@ -478,8 +481,7 @@ export function validateSignMessageData( * Validates a TypedMessageParams object for required properties and throws in * the event of any validation error for eth_signTypedMessage_V1. * - * @param messageData - TypedMessageParams object to validate - * @param activeChainId - Active chain id + * @param messageData - TypedMessageParams object to validate. */ export function validateTypedSignMessageDataV1( messageData: TypedMessageParams, @@ -512,7 +514,7 @@ export function validateTypedSignMessageDataV1( * Validates a TypedMessageParams object for required properties and throws in * the event of any validation error for eth_signTypedMessage_V3. * - * @param messageData - TypedMessageParams object to validate + * @param messageData - TypedMessageParams object to validate. */ export function validateTypedSignMessageDataV3( messageData: TypedMessageParams, @@ -549,7 +551,7 @@ export function validateTypedSignMessageDataV3( /** * Validates a ERC20 token to be added with EIP747. * - * @param token - Token object to validate + * @param token - Token object to validate. */ export function validateTokenToWatch(token: Token) { const { address, symbol, decimals } = token; @@ -581,9 +583,10 @@ export function validateTokenToWatch(token: Token) { } /** - * Returns wether the given code corresponds to a smart contract + * Returns whether the given code corresponds to a smart contract. * - * @returns {string} - Corresponding code to review + * @param code - The potential smart contract code. + * @returns Whether the code was smart contract code or not. */ export function isSmartContractCode(code: string) { /* istanbul ignore if */ @@ -596,11 +599,11 @@ export function isSmartContractCode(code: string) { } /** - * Execute fetch and verify that the response was successful + * Execute fetch and verify that the response was successful. * - * @param request - Request information - * @param options - Options - * @returns - Promise resolving to the fetch response + * @param request - Request information. + * @param options - Fetch options. + * @returns The fetch response. */ export async function successfulFetch(request: string, options?: RequestInit) { const response = await fetch(request, options); @@ -613,11 +616,11 @@ export async function successfulFetch(request: string, options?: RequestInit) { } /** - * Execute fetch and return object response + * Execute fetch and return object response. * - * @param request - Request information - * @param options - Options - * @returns - Promise resolving to the result object of fetch + * @param request - The request information. + * @param options - The fetch options. + * @returns The fetch response JSON data. */ export async function handleFetch(request: string, options?: RequestInit) { const response = await successfulFetch(request, options); @@ -626,13 +629,12 @@ export async function handleFetch(request: string, options?: RequestInit) { } /** - * Fetch that fails after timeout - * - * @param url - Url to fetch - * @param options - Options to send with the request - * @param timeout - Timeout to fail request + * Fetch that fails after timeout. * - * @returns - Promise resolving the request + * @param url - Url to fetch. + * @param options - Options to send with the request. + * @param timeout - Timeout to fail request. + * @returns Promise resolving the request. */ export async function timeoutFetch( url: string, @@ -652,9 +654,8 @@ export async function timeoutFetch( /** * Normalizes the given ENS name. * - * @param {string} ensName - The ENS name - * - * @returns - the normalized ENS name string + * @param ensName - The ENS name. + * @returns The normalized ENS name string. */ export function normalizeEnsName(ensName: string): string | null { if (ensName && typeof ensName === 'string') { @@ -673,13 +674,12 @@ export function normalizeEnsName(ensName: string): string | null { } /** - * Wrapper method to handle EthQuery requests - * - * @param ethQuery - EthQuery object initialized with a provider - * @param method - Method to request - * @param args - Arguments to send + * Wrapper method to handle EthQuery requests. * - * @returns - Promise resolving the request + * @param ethQuery - EthQuery object initialized with a provider. + * @param method - Method to request. + * @param args - Arguments to send. + * @returns Promise resolving the request. */ export function query( ethQuery: any, @@ -699,10 +699,10 @@ export function query( /** * Checks if a transaction is EIP-1559 by checking for the existence of - * maxFeePerGas and maxPriorityFeePerGas within its parameters + * maxFeePerGas and maxPriorityFeePerGas within its parameters. * - * @param transaction - Transaction object to add - * @returns - Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false + * @param transaction - Transaction object to add. + * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false. */ export const isEIP1559Transaction = (transaction: Transaction): boolean => { const hasOwnProp = (obj: Transaction, key: string) => @@ -750,6 +750,14 @@ export const isGasPriceValue = ( ): gasValues is GasPriceValue => (gasValues as GasPriceValue)?.gasPrice !== undefined; +/** + * Validates that the proposed value is greater than or equal to the minimum value. + * + * @param proposed - The proposed value. + * @param min - The minimum value. + * @returns The proposed value. + * @throws Will throw if the proposed value is too low. + */ export function validateMinimumIncrease(proposed: string, min: string) { const proposedDecimal = convertPriceToDecimal(proposed); const minDecimal = convertPriceToDecimal(min); diff --git a/yarn.lock b/yarn.lock index ccad72b250..deea1f6d1f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -416,6 +416,15 @@ exec-sh "^0.3.2" minimist "^1.2.0" +"@es-joy/jsdoccomment@0.10.8": + version "0.10.8" + resolved "https://registry.yarnpkg.com/@es-joy/jsdoccomment/-/jsdoccomment-0.10.8.tgz#b3152887e25246410ed4ea569a55926ec13b2b05" + integrity sha512-3P1JiGL4xaR9PoTKUHa2N/LKwa2/eUdRqGwijMWWgBqbFEqJUVpmaOi2TcjcemrsRMgFLBzQCK4ToPhrSVDiFQ== + dependencies: + comment-parser "1.2.4" + esquery "^1.4.0" + jsdoc-type-pratt-parser "1.1.1" + "@eslint/eslintrc@^0.4.0": version "0.4.0" resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-0.4.0.tgz#99cc0a0584d72f1df38b900fb062ba995f395547" @@ -1062,25 +1071,25 @@ resolved "https://registry.yarnpkg.com/@metamask/contract-metadata/-/contract-metadata-1.30.0.tgz#fa8e1b0c3e7aaa963986088f691fb553ffbe3904" integrity sha512-b2usYW/ptQYnE6zhUmr4T+nvOAQJK5ABcpKudyQANpy4K099elpv4aN0WcrcOcwV99NHOdMzFP3ZuG0HoAyOBQ== -"@metamask/eslint-config-jest@^8.0.0": - version "8.0.0" - resolved "https://registry.yarnpkg.com/@metamask/eslint-config-jest/-/eslint-config-jest-8.0.0.tgz#1433c2dffbd60239430ea789c71df11e94872a1c" - integrity sha512-m2/crRcaiRO8z6NC04+AudfjgIXvdrUy2oDjecjELa3nmgkJ+cVemCfioREpjaXoXW/soNImZXbgLrA98uQ6ig== +"@metamask/eslint-config-jest@^9.0.0": + version "9.0.0" + resolved "https://registry.yarnpkg.com/@metamask/eslint-config-jest/-/eslint-config-jest-9.0.0.tgz#516fdf1f03f6f006b26ca790bf748e2189d19d17" + integrity sha512-tImEEWNRedcIMHZ3pmXDAQ+6xS61G3IEyqKf2+1xSMEMaa94KM+vo6v3GM7YB+M1DsErzgx3g70fEYtPItU4pw== -"@metamask/eslint-config-nodejs@^8.0.0": - version "8.0.0" - resolved "https://registry.yarnpkg.com/@metamask/eslint-config-nodejs/-/eslint-config-nodejs-8.0.0.tgz#2181f2777a8e66825c2fd9882cb173b5a4d2b689" - integrity sha512-hN49rqgzhqo7WCJuCCD8P3e9ZhwNt6m9+XEKxnj3v1DKw8v6P6BW210LvOfzd6TfpZxN20qqnt5kxZOcN/ZPpA== +"@metamask/eslint-config-nodejs@^9.0.0": + version "9.0.0" + resolved "https://registry.yarnpkg.com/@metamask/eslint-config-nodejs/-/eslint-config-nodejs-9.0.0.tgz#ec737a47c04febfb921ce844362d875ca2cae9e7" + integrity sha512-kPUrMPdpGeapbdG+LxysnDNzM9SlBNUvqVl1XoKnOGjo1pbZXB8hOI36PT3IlR1qa2FJumKYfgDSu7JLmOLxqQ== -"@metamask/eslint-config-typescript@^8.0.0": - version "8.0.0" - resolved "https://registry.yarnpkg.com/@metamask/eslint-config-typescript/-/eslint-config-typescript-8.0.0.tgz#72f5b0cd72ffdfb8c6bbad86437801267316f254" - integrity sha512-tCCgh5nMg/GTtQ1e84jF48PoelG9MWZxe3GrBZOdKw1JgTanmyapRND4TukbUFghruoXi/HmwlY2qHQSQTVlIg== +"@metamask/eslint-config-typescript@^9.0.1": + version "9.0.1" + resolved "https://registry.yarnpkg.com/@metamask/eslint-config-typescript/-/eslint-config-typescript-9.0.1.tgz#900d53579ce074734ac9bf4e3f66fc20b92bd6af" + integrity sha512-+W7MXCoq8Q29wvkAv0ycwKB82xMbl+LfkUoM8oWN4n7vyMDXgcgbNjY7ug+quJPZfDTJJ7fxgPmG8m4LrkEImw== -"@metamask/eslint-config@^8.0.0": - version "8.0.0" - resolved "https://registry.yarnpkg.com/@metamask/eslint-config/-/eslint-config-8.0.0.tgz#f4e3bcd6b37ec135b5a72902b0526cba2a6b5a4d" - integrity sha512-ZO9B3ohNhjomrufNAkxnDXV46Kut7NKzri7itDxUzHJncNtI1of7ewWh6fKPl/hr6Al6Gd7WgjPdJZGFpzKPQw== +"@metamask/eslint-config@^9.0.0": + version "9.0.0" + resolved "https://registry.yarnpkg.com/@metamask/eslint-config/-/eslint-config-9.0.0.tgz#22d4911b705f7e4e566efbdda0e37912da33e30f" + integrity sha512-mWlLGQKjXXFOj9EtDClKSoTLeQuPW2kM1w3EpUMf4goYAQ+kLXCCa8pEff6h8ApWAnjhYmXydA1znQ2J4XvD+A== "@metamask/safe-event-emitter@^2.0.0": version "2.0.0" @@ -2331,6 +2340,11 @@ commander@~2.20.3: resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== +comment-parser@1.2.4: + version "1.2.4" + resolved "https://registry.yarnpkg.com/comment-parser/-/comment-parser-1.2.4.tgz#489f3ee55dfd184a6e4bffb31baba284453cb760" + integrity sha512-pm0b+qv+CkWNriSTMsfnjChF9kH0kxz55y44Wo5le9qLxMj5xDQAaEd9ZN1ovSuk9CsrncWaFwgpOMg7ClJwkw== + component-emitter@^1.2.1: version "1.3.0" resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0" @@ -2505,6 +2519,13 @@ debug@^4.0.1, debug@^4.1.0, debug@^4.1.1: dependencies: ms "^2.1.1" +debug@^4.3.2: + version "4.3.2" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.2.tgz#f0a49c18ac8779e31d4a0c6029dfb76873c7428b" + integrity sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw== + dependencies: + ms "2.1.2" + decamelize@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" @@ -2865,6 +2886,21 @@ eslint-plugin-jest@^24.1.5: dependencies: "@typescript-eslint/experimental-utils" "^4.0.1" +eslint-plugin-jsdoc@^36.1.0: + version "36.1.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-36.1.0.tgz#8dfe5f27edfb6aa3812e6d86ccaea849ddc86b03" + integrity sha512-Qpied2AJCQcScxfzTObLKRiP5QgLXjMU/ITjBagEV5p2Q/HpumD1EQtazdRYdjDSwPmXhwOl2yquwOGQ4HOJNw== + dependencies: + "@es-joy/jsdoccomment" "0.10.8" + comment-parser "1.2.4" + debug "^4.3.2" + esquery "^1.4.0" + jsdoc-type-pratt-parser "^1.1.1" + lodash "^4.17.21" + regextras "^0.8.0" + semver "^7.3.5" + spdx-expression-parse "^3.0.1" + eslint-plugin-node@^11.1.0: version "11.1.0" resolved "https://registry.yarnpkg.com/eslint-plugin-node/-/eslint-plugin-node-11.1.0.tgz#c95544416ee4ada26740a30474eefc5402dc671d" @@ -5104,6 +5140,11 @@ jsbn@~0.1.0: resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM= +jsdoc-type-pratt-parser@1.1.1, jsdoc-type-pratt-parser@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-1.1.1.tgz#10fe5e409ba38de22a48b555598955a26ff0160f" + integrity sha512-uelRmpghNwPBuZScwgBG/OzodaFk5RbO5xaivBdsAY70icWfShwZ7PCMO0x1zSkOa8T1FzHThmrdoyg/0AwV5g== + jsdom@^15.2.1: version "15.2.1" resolved "https://registry.yarnpkg.com/jsdom/-/jsdom-15.2.1.tgz#d2feb1aef7183f86be521b8c6833ff5296d07ec5" @@ -5679,7 +5720,7 @@ ms@2.0.0: resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= -ms@^2.1.1: +ms@2.1.2, ms@^2.1.1: version "2.1.2" resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== @@ -6538,6 +6579,11 @@ regexpp@^3.0.0, regexpp@^3.1.0: resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2" integrity sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q== +regextras@^0.8.0: + version "0.8.0" + resolved "https://registry.yarnpkg.com/regextras/-/regextras-0.8.0.tgz#ec0f99853d4912839321172f608b544814b02217" + integrity sha512-k519uI04Z3SaY0fLX843MRXnDeG2+vHOFsyhiPZvNLe7r8rD2YNRjq4BQLZZ0oAr2NrtvZlICsXysGNFPGa3CQ== + remove-trailing-separator@^1.0.1: version "1.1.0" resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" @@ -7087,7 +7133,7 @@ spdx-exceptions@^2.1.0: resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz#3f28ce1a77a00372683eade4a433183527a2163d" integrity sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A== -spdx-expression-parse@^3.0.0: +spdx-expression-parse@^3.0.0, spdx-expression-parse@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz#cf70f50482eefdc98e3ce0a6833e4a53ceeba679" integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==