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)
Top Articles
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.