Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@metamask/utils

MetaMask4.1mISC11.4.0TypeScript support: included

Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase

readme

MetaMask Utils

Various JavaScript/TypeScript utilities of wide relevance to the MetaMask codebase.

Installation

yarn add @metamask/utils

or

npm install @metamask/utils

API

The full API documentation for the latest published version of this library is available here.

Contributing

Setup

  • Install Node.js version 16
    • If you are using nvm (recommended) running nvm use will automatically choose the right node version for you.
  • Install Yarn v3
  • Run yarn install to install dependencies and run any required post-install scripts

Testing and Linting

Run yarn test to run the tests once. To run tests on file changes, run yarn test:watch.

Run yarn lint to run the linter, or run yarn lint:fix to run the linter and fix any automatically fixable issues.

Documentation

The API documentation can be generated with the command yarn docs, which saves it in the ./docs directory. Open the ./docs/index.html file to browse the documentation.

Release & Publishing

The project follows the same release process as the other libraries in the MetaMask organization. The GitHub Actions action-create-release-pr and action-publish-release are used to automate the release process; see those repositories for more information about how they work.

  1. Choose a release version.

    • The release version should be chosen according to SemVer. Analyze the changes to see whether they include any breaking changes, new features, or deprecations, then choose the appropriate SemVer version. See the SemVer specification for more information.
  2. If this release is backporting changes onto a previous release, then ensure there is a major version branch for that version (e.g. 1.x for a v1 backport release).

    • The major version branch should be set to the most recent release with that major version. For example, when backporting a v1.0.2 release, you'd want to ensure there was a 1.x branch that was set to the v1.0.1 tag.
  3. Trigger the workflow_dispatch event manually for the Create Release Pull Request action to create the release PR.

    • For a backport release, the base branch should be the major version branch that you ensured existed in step 2. For a normal release, the base branch should be the main branch for that repository (which should be the default value).
    • This should trigger the action-create-release-pr workflow to create the release PR.
  4. Update the changelog to move each change entry into the appropriate change category (See here for the full list of change categories, and the correct ordering), and edit them to be more easily understood by users of the package.

    • Generally any changes that don't affect consumers of the package (e.g. lockfile changes or development environment changes) are omitted. Exceptions may be made for changes that might be of interest despite not having an effect upon the published package (e.g. major test improvements, security improvements, improved documentation, etc.).
    • Try to explain each change in terms that users of the package would understand (e.g. avoid referencing internal variables/concepts).
    • Consolidate related changes into one change entry if it makes it easier to explain.
    • Run yarn auto-changelog validate --rc to check that the changelog is correctly formatted.
  5. Review and QA the release.

    • If changes are made to the base branch, the release branch will need to be updated with these changes and review/QA will need to restart again. As such, it's probably best to avoid merging other PRs into the base branch while review is underway.
  6. Squash & Merge the release.

    • This should trigger the action-publish-release workflow to tag the final release commit and publish the release on GitHub.
  7. Publish the release on npm.

    • Be very careful to use a clean local environment to publish the release, and follow exactly the same steps used during CI.
    • Use npm publish --dry-run to examine the release contents to ensure the correct files are included. Compare to previous releases if necessary (e.g. using https://unpkg.com/browse/[package name]@[package version]/).
    • Once you are confident the release contents are correct, publish the release using npm publish.

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

Unreleased

11.4.0

Changed

  • Deprecate local exactOptional implementation (#244)
    • Use the one from @metamask/superstruct@>=3.2.0 instead.

11.3.0

Added

  • Add default JSON-RPC generics that extend Json to Json (#241)

Changed

  • Deprecate Keyring types (#236)
    • These should now be imported from @metamask/keyring-utils.

11.2.0

Added

  • Add optional signEip7702Authorization method to Keyring type (#231)

11.1.0

Added

  • Add additional CAIP-19 types (CaipAsset{Namespace,Reference,TokenId} support (#227)
  • Add CAIP-19 CaipAssetTypeOrId (#229)
    • This one combines both CaipAssetType and CaipAssetId to avoid relying on superstruct.union, resulting in better error messages.
  • Add definePattern superstruct helper (#228)
    • Allow to define a superstruct.pattern while naming the struct and enforcing its type.

Changed

  • Use named structs for all CAIP types (#228)

11.0.1

Fixed

  • Improve error message for invalid JSON values (#224)

11.0.0

Changed

  • BREAKING: generateRandomMnemonic now returns Promise<void> instead of void (#222)

10.0.1

Added

  • Add Solana CAIP namespace (#219)

10.0.0

Changed

  • BREAKING: Drop support for Node.js versions 16, 21 (#212)
  • Improve JSON validation performance (#218)

9.3.0

Added

  • Add support for CAIP-19 (#183)
  • Add Bip122 member to KnownCaipNamespace (#213)

9.2.1

Fixed

  • Fix wrong types for CAIP-2 and CAIP-10 structs (#210)

9.2.0

Added

  • Add Wallet member to KnownCaipNamespace enum (#207)

9.1.0

Added

  • Add PublicInterface type (#197)

9.0.0

Changed

  • BREAKING: The return types of functions getChecksumAddress, numberToHex, bigIntToHex are narrowed from string to Hex (#193)

Fixed

  • Bump @metamask/superstruct from ^3.0.0 to ^3.1.0 (#194)
    • If @metamask/utils <=8.5.0 is used with @metamask/superstruct >=3.1.0 the following error may be encountered:
      error TS2742: The inferred type of 'ExampleType' cannot be named without a reference to '@metamask/utils/node_modules/@metamask/superstruct'. This is likely not portable. A type annotation is necessary.
      This can be resolved by updating @metamask/utils to >=9.0.0.

8.5.0

Changed

  • Bump dependency semver from ^5.7.1 to ^7.6.0 (#181).

Fixed

  • Replace dependency superstruct ^1.0.3 with ESM-compatible @metamask/superstruct ^3.0.0 (#185).
    • This fixes the issue of this package being unusable by any TypeScript project that uses Node16 or NodeNext as its moduleResolution option.
  • Produce and export ESM-compatible TypeScript type declaration files in addition to CommonJS-compatible declaration files (#182)
    • Previously, this package shipped with only one variant of type declaration files, and these files were only CommonJS-compatible, and the exports field in package.json linked to these files. This is an anti-pattern and was rightfully flagged by the "Are the Types Wrong?" tool as "masquerading as CJS". All of the ATTW checks now pass.
  • Remove chunk files (#182).
    • Previously, the build tool we used to generate JavaScript files extracted common code to "chunk" files. While this was intended to make this package more tree-shakeable, it also made debugging more difficult for our development teams. These chunk files are no longer present.

8.4.0

Added

  • Add toCaipChainId utility function (#175)
  • Add KnownCaipNamespace enum (#175)

Changed

  • Update docs for createDeferredPromise to caution against using suppressUnhandledRejection (#174)

Fixed

  • Fix createSandbox to assign a unique name to the sandbox directory, so that it can be used in multiple concurrently running Jest tests (#171)

8.3.0

Added

  • Add createDeferredPromise (#164)

8.2.1

Fixed

  • Fix issue with source maps where line numbers were incorrect for src/error.ts (#156)

8.2.0

Added

  • Add struct utils for validating JSON objects with optional values (#136)
  • Add filesystem utils (#148)
  • Add error utils (#146, #151)
  • Add base64 encoding and decoding functions (#145)

Changed

  • Use tsup for bundling (#144)
    • This makes the package fully compliant with ES modules.
  • Bump @ethereumjs/tx from 4.1.2 to 4.2.0 (#133)

8.1.0

Changed

  • Make types for JSON-RPC-related structs more accurate (#134)
    • Aligning JsonRpcParams to be optional, yet not undefined.
    • Updated types:
      • InferWithParams
      • JsonRpcNotificationStruct
      • JsonRpcParamsStruct
      • JsonRpcRequestStruct

8.0.0

Changed

  • BREAKING: JsonRpcParams type no longer accepts undefined as value, as undefined is not a valid JSON type (#130)

7.1.0

Added

  • Add CAIP-2 and CAIP-10 types (#116)

7.0.0

Added

  • Add getKnownPropertyNames function (#111)

Changed

  • BREAKING: Build the package as both CJS and ESM (#115, #124)
    • It's no longer possible to import from the dist folder. Everything must be imported from @metamask/utils.
  • Bump semver to ^7.5.4 (#123)

6.2.0

Added

  • Add address related utils (#112)
    • isValidHexAddress has been added to check the validity of an hex address
    • getChecksumAddress has been added to calculate the ERC-55 mixed-case checksum of an hex address
    • isValidChecksumAddress has been added to check the validity of an ERC-55 mixed-case checksum address

6.1.0

Added

  • Add optional destroy method to Keyring type (#108)

6.0.1

Fixed

  • Strip __proto__ and constructor JSON properties in getSafeJson (#105)

6.0.0

Changed

  • BREAKING: Bump minimum Node version to 16 (#102)
  • BREAKING: Target ES2020 (#102)

Fixed

  • Fix JSON validation security issue (#103)
    • This adds a new function getSafeJson which validates and returns sanitized JSON.

5.0.2

Changed

  • The Keyring exposes a new optional method init (#99)

Fixed

  • Bump @ethereumjs/tx to 4.1.2 to address runtime compatibility issues (#100)

5.0.1

Fixed

  • Keep original type when using hasProperty if defined (#94)

5.0.0

Changed

  • BREAKING: Update Keyring type (#89)
    • The Keyring class now uses the data types TypedTransaction and TxData from @ethereumjs/tx (v4.1.1).
    • The Keyring now exposes a new optional method called generateRandomMnemonic.

4.0.0

Changed

  • Export new modules (keyring, transaction-types, and encryption-types) (#86)
  • BREAKING: Improve JSON validation (#85)
    • Fixes edge cases in our JSON validation logic.
    • The previous function used for JSON validation (validateJsonAndGetSize) was removed.
      • The isValidJson function now uses the new JSON validation logic.
      • To get the size of a JSON value, you can use the getJsonSize function.

3.6.0

Added

  • Add Keyring types (#74)
    • New data types added. These are Keyring, Transaction (LegacyTransaction, EIP2930Transaction, EIP1559Transaction), SignedTransaction, Signature, and Eip1024EncryptedData.

3.5.0

Changed

  • Improve the hasProperty function (#79, #80)
    • This function now acts as a type guard, informing TypeScript that the property exists.
    • The function is now compatible with more types of objects, such as Errors and class instances.

3.4.1

Fixed

  • Bump superstruct to ^1.0.3 (#71)

3.4.0

Added

  • Add types and utility functions for validating versions and checksums (#67, #69)

Fixed

  • JSON-RPC types now have a default generic Params value (#54)

3.3.1

Fixed

  • JSON-RPC parameters are now properly cast to Json upon validation (#51)

3.3.0

Added

  • Add more assertion utils (#49)
  • Add JSON-RPC error validation functions (#46)
  • Add convenience function for creating a DataView (#45)

Fixed

  • Update JSON validation logic (#47)
    • Validation would previously allow for undefined values, which is not a standard JSON type

3.2.0

Added

  • Add PendingJsonRpcResponse type (#43)
  • Add utils for converting between numbers and hex (#41)
  • Add coercion utils (#38)

3.1.0

Added

  • Add assertion utils (#33)
  • Add util functions for encoding and decoding bytes (#34)

Fixed

  • Make JSON-RPC error data property optional (#31)
  • Don't include test files in dist folder (#35)
  • Fix typo in README (#28)

3.0.3

Fixed

  • Allow omitting JSON-RPC params when params can be undefined (#29)

3.0.2

Fixed

  • Bump superstruct to ^0.16.5 (#26)
    • superstructs 0.16.1 through 0.16.4 were not compatible with Node 14; this restores that compatibility.

3.0.1

Fixed

  • Promote @types/debug from development dependencies to production dependencies (#23)

3.0.0

Added

  • Add logging functions (#20)
  • Add frozen collections (implemented in #5 but exported in #19)

Changed

  • BREAKING: Improve types and type validation (#19)
    • Various type changes have been made that might be breaking:
      • The JsonRpcRequest and JsonRpcNotification types now include a generic constraint requiring that the Params type extends the JsonRpcParams type.
      • The JsonRpcSuccess and JsonRpcResponse types now include a generic contraint for the Result type, requiring that it extends the Json type.
      • Various validation functions now accept unknown parameters rather than specific types. This should not be breaking except that it may affect type inference for the parameters passed in.
    • New JSON-related functions have been added:
      • assertIsJsonRpcResponse
      • isJsonRpcResponse
      • InferWithParams
      • JsonRpcParams
    • New JSON Struct types have been added:
      • JsonRpcErrorStruct
      • JsonRpcFailureStruct
      • JsonRpcIdStruct
      • JsonRpcParamsStruct
      • JsonRpcRequestStruct
      • JsonRpcResponseStruct
      • JsonRpcSuccessStruct
      • JsonRpcVersionStruct
      • JsonStruct

2.1.0

Added

  • Add JSON storage validation and limit utilities (#14)
    • Adds a new function validateJsonAndGetSize.

2.0.0

Added

  • Add more JSON utils (#8)

Changed

  • BREAKING: Refactor and expand time utils (#9)
    • Adds a new function, inMilliseconds, and moves the time constants into a TypeScript enum.

1.0.0

Added

  • Initial release