EVM
const provider = window.bitkeep.ethereum
const provider = window.bitkeep.ethereum
eth_requestAccounts
EIP-1102 This method is specified by EIP-1102. 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
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
wallet_watchAsset
EIP-747
This method is specified by EIP-747
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
};
}
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
};
}
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.
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);
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);
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.
jsinterface 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. }
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. }
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:
jstry { 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 }
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 }
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.
jsinterface SwitchEthereumChainParameter { chainId: string; // A 0x-prefixed hexadecimal string }
interface SwitchEthereumChainParameter { chainId: string; // A 0x-prefixed hexadecimal string }
Returns
null - The method returns null if the request was successful, and an error otherwise.
If the error code (
error.code
) is4902
, then the requested chain has not been added by Bitget Wallet, and you have to request to add it viawallet_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 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'),
});
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'),
});
Ethereum JSON-RPC Methods
For the Ethereum JSON-RPC API, please see the Ethereum wiki. How to use reference to API Playground.
await Provider.request({method:"eth_accounts", params:[]})
await Provider.request({method:"eth_getBalance", params:[]})
await Provider.request({method:"eth_accounts", params:[]})
await Provider.request({method:"eth_getBalance", params:[]})
Event listeners
Notify when address and network changed . used eventemitter3
// 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');
});
}
// 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');
});
}
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
.
function handleAccountsChanged(accounts) {
// ...
}
Provider.on('accountsChanged', handleAccountsChanged);
//remove
Provider.removeAllListeners(); //remove all
Provider.removeListener('accountsChanged', handleAccountsChanged); // only remove accountsChanged
function handleAccountsChanged(accounts) {
// ...
}
Provider.on('accountsChanged', handleAccountsChanged);
//remove
Provider.removeAllListeners(); //remove all
Provider.removeListener('accountsChanged', handleAccountsChanged); // only remove accountsChanged
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.
Provider.on('accountsChanged', handler: (accounts: Array<string>) => void);
Provider.on('accountsChanged', handler: (accounts: Array<string>) => void);
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.
Provider.on('accountsChanged', handler: (accounts: Array<string>) => void);
Provider.on('accountsChanged', handler: (accounts: Array<string>) => void);
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;
}
interface ProviderRpcError extends Error {
message: string;
code: number;
data?: unknown;
}
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