# Ethereum(EVM)

Bitget Wallet injects a global API into websites visited by its users at window?.bitkeep?.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.

# Detect the Ethereum provider

function getProvider() {
  const provider = window.bitkeep && window.bitkeep.ethereum;
  if (!provider) {
    window.open('https://web3.bitget.com/en/wallet-download?type=2');
    throw "Please go to our official website to download!!"
  }
  return provider;
}
1
2
3
4
5
6
7
8

# Basic Usage

For any non-trivial Ethereum web application — a.k.a. dapp, web3 site etc. — to work, you will have to:

  1. Detect the Ethereum provider (window?.bitkeep?.ethereum)
  2. Detect which Ethereum network the user is connected to
  3. Get the user's Ethereum account(s)

You can refer to eth-requestaccounts or address-conflicts-when-switching-network code snippet

The provider API is all you need to create a full-featured web3 application.

You can refer a third-party base about Web3.0 login to support Bitget Wallet quickly, such as:

Note

You can use third-party libraries in conjunction with window.bitkeep.ethereum

//npm install bitkeep-web3modal  
// fork from https://github.com/WalletConnect/web3modal  https://github.com/WalletConnect/web3modal/issues/574
import web3modal from 'bitkeep-web3modal';
const web3Modal = new Web3Modal({
  network: 'mainnet', // optional
  cacheProvider: true, // optional
  providerOptions: {
    bitkeep: {
      package: true,
    },
    walletconnect: {
      display: {
        logo: 'data:image/gif;base64,INSERT_BASE64_STRING',
        name: 'Mobile',
        description: 'Scan qrcode with your mobile wallet',
      },
      package: WalletConnectProvider,
      options: {
        infuraId: 'INFURA_ID', // required
      },
    },
  }, // required
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# Chain IDs

These are the IDs of the Ethereum chains that Bitget Wallet supports by default. Consult chainid.network (opens new window)for more.

Hex Decimal Network Hex Decimal Network
0x1 1 Ethereum 0xa 10 Optimism
0x18 24 KardiaChain 0x19 25 Cronos
0x38 56 BNB Chain 0x39 57 Syscoin
0x3d 61 Ethereum Classic 0x42 66 OKX Chain
0x52 82 Meter Mainnet 0x56 86 GateChain
0x58 88 TomoChain 0x64 100 Gnosis Chain
0x6a 106 Velas 0x73 115 Lucky Chain
0x7a 122 Fuse 0x80 128 Heco
0x89 137 Polygon 0xc7 199 BitTorrent
0xfa 250 Fantom 0x120 288 Boba Network
0x141 321 KCC 0x334 820 Callisto Mainnet
0x3e6 998 Lucky Network 0x500 1280 HALO
0x505 1285 Moonriver 0x71a 1818 CUBE
0x7e3 2019 ClassZZ 0x868 2152 Findora
0x8ae 2222 Kava 0x1251 4689 IoTeX
0x2019 8217 KLAY 0x2710 10000 smartBCH
0x4b82 19330 TRUE 0x4ef4 20212 ZSC
0x7f08 32520 Bitgert 0xa4b1 42161 Arbitrum
0xa4ec 42220 Celo 0xa516 42262 Oasis Emerald
0xa86a 43114 AVAX-C 0x116e2 71394 Nervos CKB EVM
0x335f9 210425 PlatON 0x3e900 256256 Caduceus
0xa3488 668808 ASM 0x4e454152 1313161554 Aurora
0x63564c40 1666600000 Harmony

# isConnected()

Note

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 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.

const Provider = getProvider();
Provider.isConnected();
1
2

# request(args)

  const Provider = getProvider();
  interface RequestArguments {
    method: string;
    params?: unknown[] | object;
  }
  Provider.request(args: RequestArguments): Promise<unknown>;
1
2
3
4
5
6

# eth_requestAccounts

Note

EIP-1102 This method is specified by EIP-1102 (opens new window). It is equivalent to the deprecated bitkeep.ethereum.enable() provider API method.

Under the hood, it calls wallet_requestPermissions for the eth_accounts permission. Since eth_accounts is currently the only permission, this method is all you need for now.

Returns

string[] - An array of a single, hexadecimal Ethereum address string.

Description

Requests that the user provides an Ethereum address to be identified by. Returns a Promise that resolves to an array of a single Ethereum address string. If the user denies the request, the Promise will reject with a 4001 error.

The request causes a Bitget Wallet popup to appear. You should only request the user's accounts in response to user action, such as a button click. You should always disable the button that caused the request to be dispatched, while the request is still pending.

If you can't retrieve the user's account(s), you should encourage the user to initiate an account request.

  • eth_accounts
    • Get user
  • eth_chainId
    • Get chainid(Hex)
const Provider = getProvider();
function connect() {
  Provider.request({ method: 'eth_requestAccounts' })
    .then(handleAccountsChainChanged) // address or chainId changed
    .catch((error) => {
      if (error.code === 4001) {
        // EIP-1193 userRejectedRequest error
        console.log('Please connect to Bitkeep.');
      } else {
        console.error(error);
      }
    });
}
//if used injected
const accounts = await Provider.request({ method: 'eth_requestAccounts' });
handleAccountsChainChanged(); // updated address or chainID,refer to accountsChanged/chainChanged(events)
const [address] = await Provider.request({ method: 'eth_accounts' }); // [0x1e805A9aB0FB007B4b9D44d598C6404cE292F20D]
const chainId = await Provider.request({ method: 'eth_chainId' }); // 0x1
//if used web3
import Web3 from 'web3';
const accounts = await Provider.request({ method: 'eth_requestAccounts' });
//  [0x1e805A9aB0FB007B4b9D44d598C6404cE292F20D]
const web3 = new Web3(Provider);
handleAccountsChainChanged(); // updated address or chainID, refer to accountsChanged/chainChanged(events)
const accounts = await web3.eth.getAccounts(); // [0x1e805A9aB0FB007B4b9D44d598C6404cE292F20D]
const chainId = await web3.eth.getChainId(); // 0x1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

# wallet_watchAsset

EIP-747

This method is specified by EIP-747 (opens new window)

Parameters

  • WatchAssetParams - The metadata of the asset to watch.
  interface WatchAssetParams {
    type: 'ERC20'; // In the future, other standards will be supported
    options: {
      address: string; // The address of the token contract
      'symbol': string; // A ticker symbol or shorthand, up to 11 characters
      decimals: number; // The number of token decimals
      image: string; // A string url of the token logo
    };
}
1
2
3
4
5
6
7
8
9

Returns

boolean - true if the the token was added, false otherwise

Description

Requests that the user tracks the token in Bitget Wallet. Returns a boolean indicating if the token was successfully added.

Most Ethereum wallets support some set of tokens, usually from a centrally curated registry of tokens. wallet_watchAsset enables web3 application developers to ask their users to track tokens in their wallets, at runtime. Once added, the token is indistinguishable from those added via legacy methods, such as a centralized registry.

  const Provider = getProvider();
  Provider
    .request({
      method: 'wallet_watchAsset',
      params: {
        type: 'ERC20',
        options: {
          address: '0xb60e8dd61c5d32be8058bb8eb970870f07233155',
          symbol: 'FOO',
          decimals: 18,
          image: 'https://foo.io/token-image.svg',
        },
      },
    })
    .then((success) => {
      if (success) {
        console.log('FOO successfully added to wallet!');
      } else {
        throw new Error('Something went wrong.');
      }
    })
    .catch(console.error);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# wallet_switchEthereumChain/wallet_addEthereumChain

  • wallet_addEthereumChain

    Creates a confirmation asking the user to add the specified chain to Bitget Wallet. The user may choose to switch to the chain once it has been added.

    Parameters:

    For the rpcUrls and blockExplorerUrls arrays, at least one element is required, and only the first element will be used.

    interface AddEthereumChainParameter {
      chainId: string; // A 0x-prefixed hexadecimal string
      chainName: string;
      nativeCurrency: {
        name: string,
        symbol: string, // 2-6 characters long
        decimals: 18,
      };
      rpcUrls: string[];
      blockExplorerUrls?: string[];
      iconUrls?: string[]; // Currently ignored.
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12

    Returns

    null - The method returns null if the request was successful, and an error otherwise.

    Usage with wallet_switchEthereumChain

    We recommend using this method with wallet_addEthereumChain:

    const Provider = getProvider();
    try {
      await Provider.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: '0xf00' }],
      });
    } catch (switchError) {
      // This error code indicates that the chain has not been added to Bitkeep.
      if (switchError.code === 4902) {
        try {
          await ethereum.request({
            method: 'wallet_addEthereumChain',
            params: [
              {
                chainId: '0xf00',
                chainName: '...',
                rpcUrls: ['https://...'] /* ... */,
              },
            ],
          });
        } catch (addError) {
          // handle "add" error
        }
      }
      // handle other "switch" errors
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
  • wallet_switchEthereumChain

    Creates a confirmation asking the user to switch to the chain with the specified chainId.

    Parameters:

    For the rpcUrls and blockExplorerUrls arrays, at least one element is required, and only the first element will be used.

    interface SwitchEthereumChainParameter {
      chainId: string; // A 0x-prefixed hexadecimal string
    }
    
    1
    2
    3

    Returns

    null - The method returns null if the request was successful, and an error otherwise.

    If the error code (error.code) is 4902, then the requested chain has not been added by Bitget Wallet, and you have to request to add it via wallet_addEthereumChain.

    Description

    As with any method that causes a confirmation to appear, wallet_switchEthereumChain should only be called as a result of direct user action, such as the click of a button.

    Bitget Wallet will automatically reject the request under the following circumstances:

    • If the chain ID is malformed
    • If the chain with the specified chain ID has not been added to Bitget Wallet

# sendTransaction(Transfer)

const Provider = getProvider();
const transactionParameters = {
  nonce: '0x00', // ignored by Bitkeep
  gasPrice: '0x09184e72a000', // customizable by user during Bitkeep confirmation.
  gas: '0x2710', // customizable by user during Bitkeep confirmation.
  to: '0x0000000000000000000000000000000000000000', // Required except during contract publications.
  from: Provider.selectedAddress, // must match user's active address.
  value: '0x00', // Only required to send ether to the recipient from the initiating external account.
  data:
    '0x7f7465737432000000000000000000000000000000000000000000000000000000600057', // Optional, but used for defining smart contract creation and interaction.
  chainId: '0x3', // Used to prevent transaction reuse across blockchains. Auto-filled by Bitkeep.
};
// txHash is a hex string
// As with any RPC call, it may throw an error
const txHash = await Provider.request({
  method: 'eth_sendTransaction',
  params: [transactionParameters],
});
// if used web3
const accounts = await Provider.request({ method: 'eth_requestAccounts' });
const web3 = new Web3(Provider);
const result = await web3.eth.sendTransaction({
  from: Provider.selectedAddress,
  to: '0x0000000000000000000000000000000000000000',
  value: web3.utils.toWei('1', 'ether'),
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# Ethereum JSON-RPC Methods

For the Ethereum JSON-RPC API, please see the Ethereum wiki (opens new window). How to use reference to API Playground (opens new window).


  const Provider = getProvider();
  await Provider.request({method:"eth_accounts", params:[]})
  await Provider.request({method:"eth_getBalance", params:[]})
1
2
3
4
5
6

# Event listeners

Notify when address and network changed . used eventemitter3 (opens new window)

const Provider = getProvider();
// reomove all listeners
Provider.removeAllListeners();
function handleAccountsChainChanged() {
  Provider.on('accountsChanged', ([address]) => {
    // Handle the new accounts, or lack thereof.
    // "accounts" will always be an array, but it can be empty.
    alert('address changed');
  });
  Provider.on('chainChanged', async (chainId) => {
    // Handle the new chain.
    // Correctly handling chain changes can be complicated.
    // We recommend reloading the page unless you have good reason not to.
    alert('chainid changed');
  });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Also, don't forget to remove listeners once you are done listening to them (for example on component unmount in React). Prevent multiple listening, and clear it before listening removeAllListeners.

const Provider = getProvider();
function handleAccountsChanged(accounts) {
  // ...
}
Provider.on('accountsChanged', handleAccountsChanged);
//remove
Provider.removeAllListeners(); //remove all
Provider.removeListener('accountsChanged', handleAccountsChanged); // only remove accountsChanged
1
2
3
4
5
6
7
8
9

accountsChanged

The Bitget Wallet 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.

  const Provider = getProvider();
  Provider.on('accountsChanged', handler: (accounts: Array<string>) => void);
1
2

chainChanged The BitKeep provider emits this event when the currently connected chain changes.

All RPC requests are submitted to the currently connected chain. Therefore, it's critical to keep track of the current chain ID by listening for this event.

We strongly recommend reloading the page on chain changes, unless you have good reason not to.

  const Provider = getProvider();
  Provider.on('accountsChanged', handler: (accounts: Array<string>) => void);
1
2

# Signing Data

  • eth_sign
  • personal_sign
  • eth_signTypedData
  • eth_signTypedData_v3
  • eth_signTypedData_v4

You can refer to docs

# Errors

All errors thrown or returned by the Bitget Wallet provider follow this interface:

interface ProviderRpcError extends Error {
  message: string;
  code: number;
  data?: unknown;
}
1
2
3
4
5

The ethereum.request(args) method 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
  • -32603
    • Internal error or The parameters were invalid

# npm package

# use Onboard

Note:

onboard (opens new window) Onboard supports Bitget Wallet by default and can be used directly. This is a simple example

Check the official demo (opens new window)

# Install

Install npm package

yarn add @web3-onboard/core @web3-onboard/injected-wallets ethers
1

Then initialize in the application

import Onboard from '@web3-onboard/core'
import injectedModule, { ProviderLabel } from '@web3-onboard/injected-wallets'
import { ethers } from 'ethers'
const MAINNET_RPC_URL = 'https://mainnet.infura.io/v3/<INFURA_KEY>'
const injected = injectedModule({
  // do a manual sort of injected wallets so that BitKeep ordered first
  sort: wallets => {
    const bitKeep = wallets.find(
      ({ label }) => label === ProviderLabel.BitKeep
    )
    return (
      [
      bitKeep,
        ...wallets.filter(
          ({ label }) =>
            label !== ProviderLabel.BitKeep
        )
      ]
        // remove undefined values
        .filter(wallet => wallet)
    )
  },
})
const appMetadata = {
  name: 'BitKeep',
  icon: `<svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_2029_330)">
<rect width="36" height="36" rx="18" fill="#54FFF5"/>
<g filter="url(#filter0_f_2029_330)">
<path d="M1.8957 27.9279C-4.1242 44.8644 28.0774 40.0809 44.9307 35.5721C62.1794 29.8479 50.2574 4.6153 37.8864 4.05686C25.5154 3.49843 39.4203 15.7243 28.9118 19.2162C18.4033 22.7081 9.42056 6.75722 1.8957 27.9279Z" fill="white"/>
</g>
<g filter="url(#filter1_f_2029_330)">
<path d="M12.0251 -6.44486C8.86728 -15.0727 -2.37922 -3.37541 -7.60774 3.55172C-12.5951 11.0869 0.423192 17.5984 5.52949 14.0667C10.6358 10.5349 1.09329 9.84779 4.13027 5.25529C7.16725 0.662788 15.9724 4.33996 12.0251 -6.44486Z" fill="#00FFF0" fill-opacity="0.67"/>
</g>
<g filter="url(#filter2_f_2029_330)">
<path d="M13.5675 31.6991C9.2602 17.2063 -9.29274 24.8386 -18.0308 30.4663C-26.4361 37.1299 -6.47874 56.2979 1.8102 55.3174C10.0991 54.3369 -4.83915 45.9925 0.279432 41.9292C5.39801 37.8658 18.9515 49.8152 13.5675 31.6991Z" fill="#9D81FF"/>
</g>
<g filter="url(#filter3_f_2029_330)">
<path d="M39.6731 -15.0985C30.3816 -26.1625 17.0806 -17.0133 11.5916 -11.0557C6.78848 -4.31133 31.5386 8.04621 38.4077 5.92842C45.2767 3.81064 29.0407 -0.571508 31.9636 -4.68304C34.8865 -8.79457 51.2875 -1.26834 39.6731 -15.0985Z" fill="#4D94FF"/>
</g>
<path fill-rule="evenodd" clip-rule="evenodd" d="M13.1047 21.4925H19.2197L12.2637 14.4916L19.3092 7.49057L21.2281 5.625H14.8809L6.79724 13.7499C6.38929 14.1594 6.39139 14.8221 6.80142 15.2295L13.1047 21.4925ZM16.7808 14.508H16.7337L16.7803 14.5074L16.7808 14.508ZM16.7808 14.508L23.7363 21.5084L16.6908 28.5094L14.7719 30.375H21.1191L29.2027 22.2506C29.6107 21.8411 29.6086 21.1784 29.1986 20.771L22.8953 14.508H16.7808Z" fill="black"/>
</g>
<defs>
<filter id="filter0_f_2029_330" x="-12.6901" y="-9.80709" width="80.0941" height="63.4814" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
<feGaussianBlur stdDeviation="6.92308" result="effect1_foregroundBlur_2029_330"/>
</filter>
<filter id="filter1_f_2029_330" x="-22.5718" y="-23.3422" width="49.4432" height="52.2431" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
<feGaussianBlur stdDeviation="6.92308" result="effect1_foregroundBlur_2029_330"/>
</filter>
<filter id="filter2_f_2029_330" x="-33.9015" y="9.51127" width="62.5572" height="59.6884" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
<feGaussianBlur stdDeviation="6.92308" result="effect1_foregroundBlur_2029_330"/>
</filter>
<filter id="filter3_f_2029_330" x="-2.86834" y="-34.1391" width="60.4956" height="54.1552" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
<feGaussianBlur stdDeviation="6.92308" result="effect1_foregroundBlur_2029_330"/>
</filter>
<clipPath id="clip0_2029_330">
<rect width="36" height="36" rx="18" fill="white"/>
</clipPath>
</defs>
</svg>
  `,
  description: 'The multi-chain wallet chosen by 10 million users',
  recommendedInjectedWallets: [
    { name: 'BitKeep', url: 'https://web3.bitget.com/en/wallet-download?type=2' },
  ]
}
const onboard = Onboard({
  wallets: [injected],
  chains: [
    {
      id: '0x1',
      token: 'ETH',
      label: 'Ethereum Mainnet',
      rpcUrl: MAINNET_RPC_URL
    }
  ],
  appMetadata
})
const wallets = await onboard.connectWallet()
console.log(wallets)
if (wallets[0]) {
  // create an ethers provider with the last connected wallet provider
  const ethersProvider = new ethers.providers.Web3Provider(wallets[0].provider, 'any')
    // if using ethers v6 this is:
    // ethersProvider = new ethers.BrowserProvider(wallet.provider, 'any')
  const signer = ethersProvider.getSigner()
  // send a transaction with the ethers provider
  const txn = await signer.sendTransaction({
    to: '0x',
    value: 100000000000000
  })
  const receipt = await txn.wait()
  console.log(receipt)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

# Using web3modal v1

Note:

web3modal v1 (opens new window), While v1 supports BitKeep Wallet by default, official guidelines recommend not to use this version

Check out the officialdemo (opens new window) We've provided a simpledemo (opens new window)

# Installation

Install the npm package

yarn add web3modal
1

Next, initialize it within the application.

import Web3 from "web3";
import Web3Modal from "web3modal";
const providerOptions = {
  /* See Provider Options Section */
};
const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});
const provider = await web3Modal.connectTo('bitkeep');
const web3 = new Web3(provider);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Last Updated: 9/7/2023, 3:02:36 PM