Ethereum provider API | MetaMask developer documentation (2024)

This section provides a reference for the Ethereum provider API of MetaMask's Wallet API.MetaMask injects the provider API into websites visited by its users using the window.ethereum provider object.You can use the provider properties, methods, and events in your dapp.

Properties

window.ethereum.isMetaMask

This property is true if the user has MetaMask installed.

note

This property is non-standard.Non-MetaMask providers may also set this property to true.

Methods

window.ethereum.isConnected()

window.ethereum.isConnected(): boolean;

Returns true if the provider is connected to the current chain.

If the provider isn't connected, the page must be reloaded to re-establish the connection.See the connect and disconnect events for more information.

note

This method is unrelated to accessing a user's accounts.In the provider interface, "connected" and "disconnected" refer to whether the provider can make RPCrequests to the current chain.

window.ethereum.request(args)

interface RequestArguments {
method: string;
params?: unknown[] | object;
}

window.ethereum.request(args: RequestArguments): Promise<unknown>;

Use this method to submit JSON-RPC API requests to Ethereum using MetaMask.It returns a promise that resolves to the result of the RPC method call.

The parameters and return value vary by RPC method.In practice, if a method has parameters, they're almost always of type Array<any>.

If the request fails, the promise rejects with an error.

The following is an example of using window.ethereum.request(args) to calleth_sendTransaction:

params: [
{
from: "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
to: "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
// 30400
gas: "0x76c0",
// 10000000000000
gasPrice: "0x9184e72a000",
// 2441406250
value: "0x9184e72a",
data: "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675",
},
];

window.ethereum
.request({
method: "eth_sendTransaction",
params,
})
.then((result) => {
// The result varies by RPC method.
// For example, this method returns a transaction hash hexadecimal string upon success.
})
.catch((error) => {
// If the request fails, the Promise rejects with an error.
});

window.ethereum._metamask.isUnlocked()

caution

This method is experimental.Use it at your own risk.

window.ethereum._metamask.isUnlocked(): Promise<boolean>;

Returns a promise that resolves to a boolean indicating if MetaMask is unlocked by the user.MetaMask must be unlocked to perform any operation involving user accounts.Note that this method doesn't indicate if the user has exposed any accounts to the caller.

Events

The MetaMask provider emits events using the Node.jsEventEmitter API.The following is an example of listening to the accountsChanged event.You should remove listeners once you're done listening to an event (for example, on componentunmount in React).

function handleAccountsChanged(accounts) {
// Handle new accounts, or lack thereof.
}

window.ethereum.on("accountsChanged", handleAccountsChanged);

// Later

window.ethereum.removeListener("accountsChanged", handleAccountsChanged);

The first argument of window.ethereum.removeListener is the event name, and the second argument isa reference to the function passed to window.ethereum.on for the event.

accountsChanged

window.ethereum.on("accountsChanged", handler: (accounts: Array<string>) => void);

The provider emits this event when the return value of theeth_accounts RPCmethod changes.eth_accounts returns either an empty array, or an array that contains the addresses of the accountsthe caller is permitted to access with the most recently used account first.Callers are identified by their URL origin, which means that all sites with the same origin sharethe same permissions.

This means that the provider emits accountsChanged when the user's exposed account address changes.Listen to this event to handle accounts.

chainChanged

window.ethereum.on("chainChanged", handler: (chainId: string) => void);

The provider emits this event when the currently connected chain changes.Listen to this event to detect a user's network.

important

We strongly recommend reloading the page upon chain changes, unless you have a good reason not to:

window.ethereum.on("chainChanged", (chainId) => window.location.reload());

connect

interface ConnectInfo {
chainId: string;
}

window.ethereum.on("connect", handler: (connectInfo: ConnectInfo) => void);

The provider emits this event when it's first able to submit RPC requests to a chain.We recommend listening to this event and using thewindow.ethereum.isConnected() provider method to determine whenthe provider is connected.

disconnect

ethereum.on("disconnect", handler: (error: ProviderRpcError) => void);

The provider emits this event if it becomes unable to submit RPC requests to a chain.In general, this only happens due to network connectivity issues or some unforeseen error.

When the provider emits this event, it doesn't accept new requests until the connection to the chainis re-established, which requires reloading the page.You can also use the window.ethereum.isConnected() provider methodto determine if the provider is disconnected.

message

interface ProviderMessage {
type: string;
data: unknown;
}

window.ethereum.on("message", handler: (message: ProviderMessage) => void);

The provider emits this event when it receives a message that the user should be notified of.The type property identifies the kind of message.

RPC subscription updates are a common use case for this event.For example, if you create a subscription usingeth_subscribe, eachsubscription update is emitted as a message event with a type of eth_subscription.

Errors

All errors returned by the MetaMask provider follow this interface:

interface ProviderRpcError extends Error {
message: string;
code: number;
data?: unknown;
}

The window.ethereum.request(args) provider method throws errorseagerly.You can use the error code property to determine why the request failed.Common codes and their meaning include:

  • 4001 - The request is rejected by the user.
  • -32602 - The parameters are invalid.
  • -32603 - Internal error.

For the complete list of errors, see EIP-1193and EIP-1474.

tip

The eth-rpc-errors package implements all RPC errorsreturned by the MetaMask provider, and can help you identify their meaning.

Ethereum provider API | MetaMask developer documentation (2024)

FAQs

Is there a MetaMask API? ›

The MetaMask Wallet API is a global JavaScript API that can be connected to websites visited by users who have the MetaMask wallet installed via the window.

What is MetaMask SDK? ›

MetaMask SDK is a library that can be installed by developers in their projects. It will automatically guide their users to connect easily with a MetaMask Wallet client.

What is error code 4001 in MetaMask? ›

Common codes and their meaning include: 4001 - The request is rejected by the user. -32602 - The parameters are invalid. -32603 - Internal error.

What is eth_requestaccounts? ›

MetaMask. Requests that the user provide an Ethereum address to be identified by. This method is specified by EIP-1102. Internally, this method calls wallet_requestPermissions for permission to call eth_accounts .

Is there a fake MetaMask? ›

MetaMask will never pop up without you initiating a transaction. This means you need to click on some kind of button on a connected dapp for the genuine MetaMask to respond. If something appears as soon as you enter a site, or just randomly, it's likely a scam.

What country is MetaMask based out of? ›

Originating from Brooklyn, New York, it may not be too surprising to see the crypto wallet being popular in the United States. Nevertheless, other countries from the around the world downloaded the app in 2022 - most notably Brazil, Indonesia, Russia, India, and Nigeria.

What provider does MetaMask use? ›

Infura is the service provider that MetaMask uses to get information on and off blockchains.

Who are the developers of MetaMask? ›

MetaMask is developed by Consensys, a blockchain software company focusing on Ethereum-based tools and infrastructure.

What is MetaMask secret? ›

MetaMask has three different types of secret that are used in different ways to keep your wallet, and your accounts, private and safe: The Secret Recovery Phrase, the password, and private keys. We'll walk you through these secrets one at a time.

Why not to use MetaMask? ›

Most of the risks of using MetaMask aren't associated with the wallet itself but with the user and the dapps you interact with. Potential risks of using a MetaMask wallet include: Phishing attacks: These are some of the most common threats for MetaMask users.

What's wrong with MetaMask? ›

So, the reasons are: In case you have installed more than one browser-based wallet on your device, MetaMask may fail to work. In case there is a problem with the RPC connection or VPN, then MetaMask may not work. If you are using an outdated version of the MetaMask app or your device is not compatible with the app.

How to handle MetaMask errors? ›

Here are some of our top fixes:
  1. Restart your browser, or force close the mobile app and reopen.
  2. Restart your computer or mobile device.
  3. Lock and unlock MetaMask.
  4. If your problem relates to a specific transaction, check the relevant block explorer for the network you're using, such as Etherscan.
6 days ago

How to use web3provider? ›

Steps​
  1. Create the React app​ In the terminal, run the following command to create an app called my-app: npx create-react-app my-app. ...
  2. Install ethers. js​ Install ethers. ...
  3. Create the environment variables​ Create a . ...
  4. Build the app​ info. ...
  5. Run the app​ Run the app from the root of the directory:
Jul 4, 2024

What is error code 4902 in MetaMask? ›

If the requested chain does not exist in the user's wallet, the request throws an error code error. code of 4902 . If this happens, you can request to add the chain to the wallet. You can follow this guide to see how to add a new chain to MetaMask using JavaScript.

How to connect MetaMask API? ›

Follow these steps for creating a vanilla TypeScript project to connect to MetaMask:
  1. Create a project​ Create a Vite project using the template for vanilla TypeScript: ...
  2. Set up the project​ In your Vite project, update src/vite-env.d.ts with the EIP-6963 interfaces: ...
  3. Update main. ts ​ ...
  4. Connect to wallets​ ...
  5. View the project​

How do I find my MetaMask API key? ›

To access your private key: open Metamask browser extension -> account options -> account details -> EXPORT PRIVATE KEY (never share this publicly!) API key is from Infura. To access: log on to http://infura.io -> go to your project -> copy paste PROJECT SECRET (which is your key).

Is MetaMask code open source? ›

Metamask is an open-source self-custody wallet for Ethereum and Ethereum-like blockchains. This browser extension and mobile app enable users to hold their cryptocurrency and make transactions while maintaining control of their private keys.

How do I enable OpenSea API in MetaMask? ›

Find'security & Privacy' and scroll until you see 'Autodetect NFTs'. Flick the switch to turn on autodetect. Note that 'Enable OpenSea API' (directly above in the menu) must be turned on as well, otherwise the NFT autodetect switch will be greyed out.

Top Articles
Studying Medicine in the USA – The Medic Portal
Ranking giełd kryptowalut - najlepsze platformy do krypto
Nullreferenceexception 7 Days To Die
Menards Thermal Fuse
Www.craigslist Virginia
Archived Obituaries
Air Canada bullish about its prospects as recovery gains steam
Snarky Tea Net Worth 2022
Paketshops | PAKET.net
Employeeres Ual
Bbc 5Live Schedule
Leeks — A Dirty Little Secret (Ingredient)
Mary Kay Lipstick Conversion Chart PDF Form - FormsPal
Craigslist Farm And Garden Tallahassee Florida
Chastity Brainwash
Nail Salon Goodman Plaza
Is Grande Internet Down In My Area
Iu Spring Break 2024
Lakewood Campground Golf Cart Rental
Parc Soleil Drowning
Drift Hunters - Play Unblocked Game Online
Wsbtv Fish And Game Report
Malluvilla In Malayalam Movies Download
Receptionist Position Near Me
Garden Grove Classlink
Ascensionpress Com Login
27 Fantastic Things to do in Lynchburg, Virginia - Happy To Be Virginia
Meggen Nut
Perry Inhofe Mansion
Rush County Busted Newspaper
Basil Martusevich
Salons Open Near Me Today
Wake County Court Records | NorthCarolinaCourtRecords.us
One Credit Songs On Touchtunes 2022
Ni Hao Kai Lan Rule 34
The 50 Best Albums of 2023
Lyca Shop Near Me
Colorado Parks And Wildlife Reissue List
Entry of the Globbots - 20th Century Electro​-​Synthesis, Avant Garde & Experimental Music 02;31,​07 - Volume II, by Various
Seven Rotten Tomatoes
Weekly Math Review Q2 7 Answer Key
11 Best Hotels in Cologne (Köln), Germany in 2024 - My Germany Vacation
Divinity: Original Sin II - How to Use the Conjurer Class
How Big Is 776 000 Acres On A Map
Streameast Io Soccer
Jimmy John's Near Me Open
De Donde Es El Area +63
Buildapc Deals
Convert Celsius to Kelvin
Kobe Express Bayside Lakes Photos
Cbs Scores Mlb
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 6017

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.