Use MetaMask SDK with JavaScript
Import MetaMask SDK into your JavaScript dapp to enable your users to easily connect to the MetaMask browser extension and MetaMask Mobile. The following instructions work for web dapps based on standard JavaScript. You can also see instructions for the following JavaScript-based platforms:
Prerequisites
- A JavaScript project set up
- MetaMask Mobile version 5.8.1 or later
- Yarn or npm
Steps
1. Install the SDK
In your project directory, install the SDK using Yarn or npm:
yarn add @metamask/sdk
or
npm i @metamask/sdk
2. Import the SDK
In your project script, add the following to import the SDK:
import { MetaMaskSDK } from "@metamask/sdk"
3. Instantiate the SDK
Instantiate the SDK using any options:
const MMSDK = new MetaMaskSDK({
dappMetadata: {
name: "JavaScript example dapp",
},
infuraAPIKey: process.env.INFURA_API_KEY,
// Other options.
})
- Use
dappMetadata
to display information about your dapp in the MetaMask connection modal. - Use
infuraAPIKey
to make read-only RPC requests from your dapp. - Use
headless
to customize the logic and UI of the displayed modals.
4. Use the SDK
We recommend calling connect()
first. You can also call eth_requestAccounts
using
request()
first, which will prompt the installation or connection popup to appear.
const accounts = await MMSDK.connect()
const provider = MMSDK.getProvider()
provider.request({ method: "eth_accounts", params: [] })
You can also call the SDK's connectAndSign
method, and
batch multiple JSON-RPC requests using the metamask_batch
method.
Example
You can copy the full JavaScript example to get started:
import { MetaMaskSDK } from "@metamask/sdk"
const MMSDK = new MetaMaskSDK({
dappMetadata: {
name: "Example JavaScript Dapp",
url: window.location.href,
},
infuraAPIKey: process.env.INFURA_API_KEY,
// Other options.
})
const accounts = await MMSDK.connect()
// You can also access the Ethereum provider object but we recommend using the SDK's methods.
const ethereum = MMSDK.getProvider()
ethereum.request({ method: "eth_accounts", params: [] })
See the example JavaScript dapps in the JavaScript SDK GitHub repository for more information.