# Ethereum Provider API

{% hint style="success" %}
Recommended reading

We recommend that all Web3.0 site developers read the [Basic Usage](#basic-usage) sectio&#x6E;**.**
{% endhint %}

TokenPocket Extension injects a global API into websites visited by its users at window\.ethereum. This API allows websites to request users' Ethereum accounts, read data from blockchains the user is connected to, and suggest that the user sign messages and transactions. The presence of the provider object indicates an Ethereum user. We recommend using `@metamask/detect-provider` to detect our provider on any platform or browser.

The Ethereum JavaScript provider API is specified by [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193)

### **Basic usage**

For any non-trivial Ethereum web application — DApp, Web3.0 site etc— to work, you will have to:

* Detect the Ethereum provider (`window.ethereum`or`window.tokenpocket.ethereum`)
* Detect which Ethereum network the user is connected to
* Get the user's Ethereum account(s)
* We also support[ EIP-6963 🔗 ](https://eips.ethereum.org/EIPS/eip-6963)

The snippet at the top of this page is sufficient for detecting the provider. The provider API is all you need to create a full-featured Web3.0 application.

That said, many developers use a convenience library, such as [ethers](https://www.npmjs.com/package/ethers), instead of using the provider directly.

### Chain ID <a href="#chain-ids" id="chain-ids"></a>

These are the IDs of the Ethereum chains that TokenPocket Extension supports by default. Consult [chainid.network](https://chainlist.tokenpocket.pro/?from=old) for more.

| Hex        | Decimal    | Network             |
| ---------- | ---------- | ------------------- |
| 0x1        | 1          | Ethereum（Mainnet）   |
| 0x38       | 56         | BNB Chain           |
| 0x80       | 128        | HECO Chain          |
| 0x42       | 66         | OKExChain           |
| 0x89       | 137        | Polygon(Matic)      |
| 0xa86a     | 43114      | Avalanche C-Chain   |
| 0x141      | 321        | KCC Mainnet         |
| 0x63564c40 | 1666600000 | Harmony             |
| 0xfa       | 250        | Fantom              |
| 0x2019     | 8217       | Klaytn              |
| 0xa4b1     | 42161      | Arbitrum            |
| 0x4e454152 | 1313161554 | Aurora              |
| 0xa        | 10         | Optimistic Ethereum |
| 0x46       | 70         | Hoo Smart Chain     |
| 0x406      | 1030       | Conflux eSpace      |
| 0x504      | 1284       | Moonbeam            |
| 0x64       | 100        | Gnosis Chain (xDai) |

### Properties <a href="#properties" id="properties"></a>

#### ethereum.isTokenPocket <a href="#properties" id="properties"></a>

true if the user has TokenPocket Extension installed, and false otherwise.

### Methods <a href="#methods" id="methods"></a>

#### ethereum.isConnected() <a href="#ethereum-isconnected" id="ethereum-isconnected"></a>

{% hint style="success" %}
Tip

Note that this method has nothing to do with the user's accounts

You may often encounter the word "connected" in reference to whether a Web3.0 site can access the user's accounts. In the provider interface, however, "connected" and "disconnected" refer to whether the provider can make RPC requests to the current chain.
{% endhint %}

```javascript
ethereum.isConnected(): boolean;
```

Returns `true` if the provider is connected to the current chain, and `false` otherwise.

If the provider is not connected, the page will have to be reloaded for reconnection. Please see the [connect](#connect) and [disconnect](#disconnect) events for more information.

#### ethereum.request(args) <a href="#ethereum-request-args" id="ethereum-request-args"></a>

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

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

Use request to submit RPC requests to Ethereum via TokenPocket Extension. It returns a Promise that resolves to the result of the RPC method call.

The params and return value will vary by RPC method. In practice, if a method has any params, they are almost always of type Array\<any>.

If the request fails for any reason, the Promise will reject with an [Ethereum RPC Error](#errors).

TokenPocket Extension supports most standardized Ethereum RPC methods, in addition to a number of methods that may not be supported by other wallets. See the TokenPocket Extension [RPC API documentation](https://help.tokenpocket.pro/developer-en/extension-wallet/api-reference/rpc-api) for details.

**Example**

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

ethereum
  .request({
    method: 'eth_sendTransaction',
    params,
  })
  .then((result) => {
    // The result varies by RPC method.
    // For example, this method will return a transaction hash hexadecimal string on success.
  })
  .catch((error) => {
    // If the request fails, the Promise will reject with an error.
  });
```

### Events

TokenPocket Extension provider implements the[ Node.jsEventEmitte](https://nodejs.org/api/events.html)r API. This section details the events emitted via that API. There are innumerable EventEmitter guides elsewhere, but you can listen for events like this:

```javascript
ethereum.on('accountsChanged', (accounts) => {
  // Handle the new accounts, or lack thereof.
  // "accounts" will always be an array, but it can be empty.
});

ethereum.on('chainChanged', (chainId) => {
  // Handle the new chain.
  // Correctly handling chain changes can be complicated.
  // We recommend reloading the page unless you have good reason not to.
  window.location.reload();
});
```

Also, don't forget to remove listeners once you have done listening to them (for example on component unmount in React):

```javascript
function handleAccountsChanged(accounts) {
  // ...
}

ethereum.on('accountsChanged', handleAccountsChanged);

// Later

ethereum.removeListener('accountsChanged', handleAccountsChanged);
```

The first argument of the `ethereum.removeListener` is the event name and the second argument is the reference to the same function which has passed to `ethereum.on` for the event name mentioned in the first argument.

#### **connect**

```javascript
interface ConnectInfo {
  chainId: string;
}
ethereum.on('connect', handler: (connectInfo: ConnectInfo) => void);
```

The TokenPocket Extension provider emits this event when it first becomes able to submit RPC requests to a chain. We recommend using a connect event handler and the [ethereum.isConnected() method](#ethereum-isconnected) in order to determine when/if the provider is connected.

#### **disconnect**

```javascript
ethereum.on('disconnect', handler: (error: ProviderRpcError) => void);
```

The TokenPocket Extension provider emits this event if it becomes unable to submit RPC requests to any chain. In general, this will only happen due to network connectivity issues or some unforeseen error.

Once disconnect has been emitted, the provider will not accept any new requests until the connection to the chain has been re-restablished, which requires reloading the page. You can also use the [ethereum.isConnected() method](https://docs.metamask.io/guide/ethereum-provider.html#ethereum-isconnected) to determine if the provider is disconnected.

#### **Accounts changed**

```javascript
ethereum.on('accountsChanged', handler: (accounts: Array<string>) => void);
```

The TokenPocket Extension provider emits this event whenever the return value of the eth\_accounts RPC method changes. eth\_accounts returns an array that is either empty or contains a single account address. The returned address, if any, is the address of the most recently used account that the caller is permitted to access. Callers are identified by their URL origin, which means that all sites with the same origin share the same permissions.

This means that accountsChanged will be emitted whenever the user's exposed account address changes.

#### **Chain changed**

{% hint style="success" %}
Tip

See the [Chain IDs section](#chain-ids) for TokenPocket Extension's default chains and their chain IDs.
{% endhint %}

```javascript
ethereum.on('chainChanged', handler: (chainId: string) => void);
```

#### **Message**

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

ethereum.on('message', handler: (message: ProviderMessage) => void);
```

The TokenPocket Extension provider emits this event when it receives some message that the consumer should be notified of. The kind of message is identified by the type string.

RPC subscription updates are a common use case for the `message` event. For example, if you create a subscription using `eth_subscribe`, each subscription update will be emitted as a message event with a type of `eth_subscribe`

### Errors <a href="#errors" id="errors"></a>

All errors thrown or returned by the TokenPocket Extension provider follow this interface:

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

The [ethereum.request(args) method](#ethereum-request-args) throws errors eagerly. You can often use the error code property to determine why the request failed. Common codes and their meaning include:

* `4001`
  * The request was rejected by the user
* `-32602`
  * The parameters were invalid
* `-32603`
  * Internal error

For the complete list of errors, please see [EIP-1193 ](https://eips.ethereum.org/EIPS/eip-1193#provider-errors)and [EIP-1474](https://eips.ethereum.org/EIPS/eip-1474#error-codes)

{% hint style="info" %}
Tip

The [eth-rpc-errors](https://npmjs.com/package/eth-rpc-errors) package implements all RPC errors thrown by the TokenPocket Extension provider, and can help you identify their meaning
{% endhint %}

### **Legacy** API <a href="#legacy-api" id="legacy-api"></a>

{% hint style="warning" %}
WARNING

You should never rely on any of these methods, properties, or events in practice.
{% endhint %}

This section documents our legacy provider API. TokenPocket Extension only supported this API before the provider API was standardized via  [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) in 2020. Because of this, you may find Web3.0 sites that use this API, or other providers that implement it.

### **Legacy Properties**

#### ethereum.chainId（**DEPRECATED**） <a href="#ethereum-chainid-deprecated" id="ethereum-chainid-deprecated"></a>

{% hint style="warning" %}
WARNING

This property is non-standard, and therefore deprecated.

If you need to retrieve the current chain ID, use [ethereum.request({ method: 'eth\_chainId' })](#ethereum-request-args). See also the [chainChanged](#chain-changed) event for more information about how to handle chain IDs.

The value of this property can change at any time.
{% endhint %}

A hexadecimal string representing the current chain ID

#### ethereum.networkVersion（**DEPRECATED**） <a href="#ethereum-networkversion-deprecated" id="ethereum-networkversion-deprecated"></a>

{% hint style="danger" %}
WARNING

You should always prefer the chain ID over the network ID.

If you must get the network ID, use [ethereum.request({ method: 'net\_version' })](#ethereum-request-args).

The value of this property can change at any time.
{% endhint %}

A decimal string representing the current blockchain's network ID.。

#### ethereum.selectedAddress（**DEPRECATED**） <a href="#ethereum-selectedaddress-deprecated" id="ethereum-selectedaddress-deprecated"></a>

{% hint style="warning" %}
WARNING

Use [ethereum.request({ method: 'eth\_accounts' })](#ethereum-request-args) instead.

The value of this property can change at any time.
{% endhint %}

Returns a hexadecimal string representing the user's "currently selected" address.

The "currently selected" address is the first item in the array returned by `eth_accounts`

### **Legacy Methods**

#### ethereum.enable()（**DEPRECATED**） <a href="#ethereum-enable-deprecated" id="ethereum-enable-deprecated"></a>

{% hint style="warning" %}
WARNING

Use [ethereum.request({ method: 'eth\_requestAccounts' })](#ethereum-request-args) instead.
{% endhint %}

#### ethereum.sendAsync()（**DEPRECATED**） <a href="#ethereum-sendasync-deprecated" id="ethereum-sendasync-deprecated"></a>

{% hint style="warning" %}
WARNING

Use [ethereum.request()](#ethereum-request-args) instead.
{% endhint %}

```javascript
interface JsonRpcRequest {
  id: string | undefined;
  jsonrpc: '2.0';
  method: string;
  params?: Array<any>;
}

interface JsonRpcResponse {
  id: string | undefined;
  jsonrpc: '2.0';
  method: string;
  result?: unknown;
  error?: Error;
}

type JsonRpcCallback = (error: Error, response: JsonRpcResponse) => unknown;

ethereum.sendAsync(payload: JsonRpcRequest, callback: JsonRpcCallback): void;
```

This is the ancestor of `ethereum.request`. It only works for JSON-RPC methods, and takes a JSON-RPC request payload object and an error-first callback function as its arguments.

See the [Ethereum JSON-RPC API ](https://eips.ethereum.org/EIPS/eip-1474)for details.

#### ethereum.send()（DEPRECATED）

{% hint style="warning" %}
WARNING

Use [ethereum.request()](#ethereum-request-args) instead.
{% endhint %}

```typescript
ethereum.send(
  methodOrPayload: string | JsonRpcRequest,
  paramsOrCallback: Array<unknown> | JsonRpcCallback,
): Promise<JsonRpcResponse> | void;
```

This method behaves unpredictably and should be avoided at all costs. It is essentially an overloaded version of [ethereum.sendAsync()](#ethereum-sendasync-deprecated).

`ethereum.send()` can be called  in three different ways:

```typescript
// 1.
ethereum.send(payload: JsonRpcRequest, callback: JsonRpcCallback): void;

// 2.
ethereum.send(method: string, params?: Array<unknown>): Promise<JsonRpcResponse>;

// 3.
ethereum.send(payload: JsonRpcRequest): unknown;
```

You can think of these signatures as follows:

1. This signature is exactly like`ethereum.sendAsync()`
2. This signature is like an [ethereum.sendAsync()](#ethereum-sendasync-deprecated) with method and params as arguments, instead of a JSON-RPC payload and callback
3. &#x20;This signature enables you to call the following RPC methods synchronously:
   * `eth_accounts`
   * `eth_coinbase`
   * `eth_uninstallFilter`
   * `net_version`
