Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article examines EIP-1193, which standardizes the Provider API so that Web3 applications and Ethereum wallets can interact through a common interface.

This article translates, summarizes, and expands on the specification linked below.

I also cover a variety of other EIPs.

Overview

What is the Ethereum Provider API?

Ethereum decentralized applications (dApps) commonly use software called a wallet to manage users' private keys and accounts. Wallets interact with applications through a JavaScript object. This object is called a provider.

The provider may be injected into a web page and is often accessible as window.ethereum. However, this name and method of exposing the provider are conventions, not formal requirements of the specification.

Why is the Ethereum Provider API needed?

Historically, individual wallets implemented their own providers, resulting in differences in their interfaces and behavior. Code that worked with one wallet might not work with another, creating compatibility problems.

The Ethereum Provider API was proposed to address these issues. It aims to improve interoperability between wallets and enable dApp developers to access them consistently, regardless of which wallet they target.

What are the characteristics of the API?

The Ethereum Provider API has the following characteristics.

  • Minimal design
    • It includes only the essential functionality.
  • Event-driven
    • It provides events that notify applications of state changes.
  • Transport-agnostic
    • It abstracts away specific communication protocols such as HTTP or WebSocket.
  • Extensible
    • New RPC methods and events can be added as needed.

The basic interface is defined, while allowing implementations to extend it with additional functionality.

How window.ethereum becomes accessible

When an Ethereum provider such as MetaMask is installed as a Chrome extension, the extension injects window.ethereum into the global scope of web pages.

The following sequence illustrates how this works.

Provider injection process

  1. The extension prepares an injected script rather than relying solely on a content script Chrome extensions have content scripts that can interact with web pages. To modify the page's window object directly, an injected script must run in the same execution context as the page.

  2. The injected script is embedded in the DOM as a <script> tag and executed This script assigns the provider object to window.ethereum.

    javascript
    window.ethereum = {
      request: async function(args) { ... },
      on: function(eventName, handler) { ... },
      // その他のプロパティ
    };
  3. The provider becomes accessible as window.ethereum from the page's JavaScript The dApp can use it to perform Ethereum RPC operations.

Why use window.ethereum?

The window object is the browser's global object and is accessible to JavaScript code, including dApp code. By adding an ethereum property to it, wallet extensions provide a common entry point between dApps and the Ethereum network.

Detecting the provider

Scripts within a web page can detect the provider as follows.

javascript
if (typeof window.ethereum !== 'undefined') {
  console.log('Ethereum provider detected');
} else {
  console.log('No Ethereum provider found');
}

This is a common way to determine whether a user has installed MetaMask or another wallet extension. The code examples retain their original comments, including Japanese comments where present.

Specification

The Ethereum Provider API defines a common interface for accessing Ethereum from web browsers. It aims to resolve inconsistencies between wallets and clients and provide a unified way for dApps to connect to wallets.

Terminology

  • Provider
    • A JavaScript object exposed to web applications that provides an entry point for interacting with Ethereum.
  • Client
    • An endpoint, such as a node, that receives RPC (remote procedure call) requests from the provider and returns the results.
  • Wallet
    • Software that manages private keys and mediates signing and user authentication.
    • It also serves as middleware between the provider and client.
  • RPC (Remote Procedure Call)
    • A request sent to the provider to perform an operation.
    • It enables operations such as retrieving blockchain information and submitting transactions.

Connection state

A provider is connected when it can successfully process RPC requests for at least one chain. Conversely, it is considered disconnected if it cannot process requests for any chain.

Basic structure of the Provider API

The API is described in TypeScript, and implementers are encouraged to use these definitions as the basis for their own types.

At the core of the API is the request method. It provides a common function for making Ethereum requests independently of any particular protocol or transport.

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

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

Passing a method name and parameters to request sends an instruction to an Ethereum node. The return value is a Promise that resolves with the expected result on success and rejects with an error on failure.

Error handling

If a problem occurs while processing a request, the request is rejected with an error in the ProviderRpcError format. It contains a numeric error code, an error message, and optional additional information.

The specification defines error codes such as the following.

  • 4001
    • The user rejected the request.
  • 4100
    • The request is unauthorized.
  • 4200
    • The method is unsupported.
  • 4900
    • The provider is disconnected from all chains.
  • 4901
    • The provider is disconnected from a particular chain.

Event specification

Providers must implement event handling. Specifically, they must provide on and removeListener functions that follow Node.js's EventEmitter API.

The following events are defined.

message

Emitted when the provider receives an arbitrary notification. It can be used to receive subscription notifications, for example those from eth_subscribe.

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

Subscription messages take the following form.

typescript
interface EthSubscription extends ProviderMessage {
  readonly type: 'eth_subscription';
  readonly data: {
    readonly subscription: string;
    readonly result: unknown;
  };
}

connect

Emitted when the provider successfully connects to a chain.

typescript
interface ProviderConnectInfo {
  readonly chainId: string;
}

chainId contains the connected chain's ID as a hexadecimal string.

disconnect

Emitted when the provider disconnects from all chains, passing a ProviderRpcError. The error's code follows the CloseEvent status code specification.

chainChanged

Emitted when the connected chain changes. The new chainId is passed to the listener.

accountsChanged

Emitted when the accounts available through the provider change. The new array of account addresses is passed to the listener.

Supported RPC methods

A provider can decide which RPC methods to support. However, it is recommended to reject unsupported standardized methods, such as those defined by EIPs, with error code 4200.

Additional details

Purpose and responsibilities of a provider

An Ethereum provider gives web applications (dApps) access to the Ethereum network. Its primary responsibilities can be grouped into two categories.

First, it enables Ethereum RPC requests. Applications can use these requests to perform operations such as retrieving information from Ethereum nodes and submitting transactions.

Second, it enables applications to detect and respond to changes in the connected Ethereum chain or wallet state in real time. For example, the application must handle cases where a user switches accounts or connects to a different chain.

A minimal API design

The Provider API is designed to be simple and consists of the following elements.

  • One function
    • request
  • Five events
    • message
    • connect
    • disconnect
    • chainChanged
    • accountsChanged

The request function and message event are especially important. Together, they allow arbitrary RPC requests and notifications to be sent and received, providing the minimum functionality needed for a provider.

The remaining four events help applications efficiently detect common state changes. For example, chainChanged and accountsChanged are essential notifications for maintaining a consistent user experience.

Why these events are included

The connect and disconnect events signal changes in the provider's ability to process RPC requests. They allow applications to determine accurately when Ethereum is accessible.

The chainChanged and accountsChanged events report important changes caused by user actions, such as switching chains or accounts. Without these notifications, applications might continue operating with incorrect state.

These events build on design patterns already used by many dApps in production and address practical application requirements.

Compatibility

The specification is compatible with the previously widespread, unofficial draft Provider API. In other words, the formal specification is designed as a strict superset of the earlier draft and remains consistent with many existing wallet implementations.

However, a provider implementing only this specification may not be compatible with older dApps that rely on the legacy API. This is because methods and events specific to that earlier API may no longer be available.

Developers can use the new API for standards-aligned development, but they must also consider legacy API behavior when compatibility with older applications is required.

Security

Provider responsibilities and security boundaries

An Ethereum provider sends and receives RPC messages between web applications and Ethereum clients (nodes). The provider itself does not manage private keys or accounts. Those responsibilities belong to the wallet, which sits between the provider and Ethereum client.

The provider should not handle users' private keys or personal information; it is a component that relays requests. The wallet is responsible for protecting users' assets and accounts.

An important consideration is that the provider is exposed as a JavaScript object within a web page and therefore operates in an untrusted environment. For example, a malicious website can manipulate the provider object.

Defending against malicious manipulation

Because providers operate in third-party JavaScript environments, developers must design them on the assumption that the provider may be under an attacker's control. With that assumption in mind, the following safeguards are recommended.

First, the provider must not contain private keys or personal data. It should serve as a relay rather than storing or processing sensitive information.

Second, wallet and provider processes should be clearly isolated to minimize their influence on one another. All requests and data received by the wallet through the provider must be treated as untrusted and validated.

Wallets and clients should also rate-limit requests from the provider to strengthen protection against DoS attacks and abusive request flooding.

Chain state and consistency

Every Ethereum operation targets a particular chain (network). The provider must therefore always report the correct chain ID.

This chain ID is retrieved using the eth_chainId RPC method. When the user switches networks, the provider must immediately detect the change and notify the application by emitting chainChanged.

Failure to implement this correctly could cause serious problems, such as a dApp sending a transaction to the wrong chain.

Exposing accounts and handling account changes

Many Ethereum operations, such as eth_sendTransaction, require specifying the user's sending account. The provider supplies this information to the application through eth_accounts. When the available accounts change, it also emits accountsChanged.

Importantly, this account information should not be disclosed automatically by default. To protect user privacy, providers are encouraged not to expose accounts initially and to disclose them only after an application explicitly requests access.

Applications can use RPC methods such as eth_requestAccounts (ERC1102) and wallet_requestPermissions (ERC2255) to request account access and prompt the user for approval.

Using the Ethereum Provider API and implementation examples

The Ethereum Provider API provides a common interface for web applications interacting with Ethereum. This appendix offers practical information for developers about using the API, key events, error handling, subscriptions, and differences from earlier deprecated APIs.

Using the request method

The most important feature of an Ethereum provider is the request method. It provides the standard interface for invoking Ethereum RPC methods.

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

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

This method returns a Promise that resolves with the result on success and rejects with an error in the ProviderRpcError format on failure. For example, the following retrieves the currently available accounts.

javascript
Provider.request({ method: 'eth_accounts' })
  .then((accounts) => console.log(accounts))
  .catch((error) => console.error(error));

For available methods and parameters, consult the relevant RPC specification, such as EIP-1474.

Available RPC protocols

Ethereum supports several RPC protocols, including these two principal examples.

  • ERC1474: Ethereum JSON-RPC API
  • ERC1767: Ethereum GraphQL schema

For more information about ERC1474, see the article below.

[ERC1474] Standardizing Ethereum RPC Interfaces

For more information about ERC1767, see the article below.

[ERC1767] Understanding the JSON-RPC-Compatible GraphQL API

The provider offers an abstract interface independent of these protocols.

Handling events

Ethereum providers implement an event system compatible with Node.js's EventEmitter. Applications can detect state changes using events such as the following.

connect

Emitted when the provider successfully connects to a chain.

typescript
Provider.on('connect', (connectInfo) => {
  console.log(connectInfo.chainId); // 例: "0x1"
});

disconnect

Emitted when the provider disconnects from all chains.

typescript
Provider.on('disconnect', (error) => {
  console.error(`Disconnected: ${error.message} (code: ${error.code})`);
});

chainChanged

Emitted when the connected chain ID changes.

typescript
Provider.on('chainChanged', (chainId) => {
  console.log(`New chain ID: ${chainId}`);
});

accountsChanged

Emitted when the available accounts change.

typescript
Provider.on('accountsChanged', (accounts) => {
  console.log(`Current accounts: ${accounts.join(', ')}`);
});

message

An event for receiving arbitrary notifications. These include notifications from eth_subscribe.

typescript
Provider.on('message', (message) => {
  console.log(`Message type: ${message.type}`);
  console.log(message.data);
});

Subscriptions

RPC methods such as eth_subscribe enable event subscriptions. Subscription notifications are received through the message event.

javascript
Provider.request({ method: 'eth_subscribe', params: ['newHeads'] })
  .then((subscriptionId) => {
    Provider.on('message', (message) => {
      if (message.type === 'eth_subscription' && message.data.subscription === subscriptionId) {
        console.log(`New block:`, message.data.result);
      }
    });
  });

Handling errors

Provider errors use the common ProviderRpcError format.

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

For example, error code 4001 is returned when a user rejects an operation.

Common examples

In web browsers, implementations commonly use window.ethereum. The following are representative examples.

Retrieve the chain ID

javascript
window.ethereum.request({ method: 'eth_chainId' })
  .then((chainId) => {
    console.log(`Chain ID: ${chainId}`);
  });

Retrieve the latest block

javascript
window.ethereum.request({ method: 'eth_getBlockByNumber', params: ['latest', true] })
  .then((block) => {
    console.log(`Block ${block.number}:`, block);
  });

Monitor account changes

javascript
const logAccounts = (accounts) => {
  console.log(`Accounts:\n${accounts.join('\n')}`);
};
window.ethereum.on('accountsChanged', logAccounts);

Log connection closure notifications

javascript
window.ethereum.on('disconnect', (error) => {
  console.log(`Connection closed: ${error.message} (code: ${error.code})`);
});

Differences from the legacy API

The current Provider API is designed as a superset of the earlier, unofficial legacy API. The legacy API included the following methods and events, which are now deprecated.

  • sendAsync
    • Sends RPC requests using callbacks (replaced by request).
  • send
    • Deprecated because its format was inconsistent.
  • close, networkChanged, notification
    • Replaced by disconnect, chainChanged, and message, respectively.

Developers should not introduce these legacy interfaces into new implementations. Instead, they are encouraged to use request and the event API.

References

Fabian Vogelsteller (@frozeman), Ryan Ghods (@ryanio), Victor Maia (@MaiaVictor), Marc Garreau (@wolovim), Erik Marks (@rekmarks), "EIP-1193: Ethereum Provider JavaScript API," Ethereum Improvement Proposals, no. 1193, June 2018. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-1193.

Conclusion

This article covered EIP-1193, which standardizes the Provider API so that Web3 applications and Ethereum wallets can interact consistently.

If you have questions, feel free to reach out via direct message on Twitter.

Twitter @cardene777

I also publish content on other platforms, which you can find below.

https://chaldene.net/