Ethereum JSON-RPC方法
api地址
重要的api有
- eth_accounts
-
- eth_call
-
- eth_getBalance
-
- eth_sendTransaction
-
- eth_sign
有些接口是需要账户授权才可以调用成功
请求用户提供要被识别的以太坊地址。返回Promise 解析以太坊地址字符串数组。如果用户拒绝请求,Promise将拒绝并返回4001错误。
没拿到地址要重新请求才行。
- document.getElementById('connectButton', connect);
-
- function connect() {
- ethereum
- .request({ method: 'eth_requestAccounts' })
- .then(handleAccountsChanged)
- .catch((error) => {
- if (error.code === 4001) {
- // EIP-1193 userRejectedRequest error
- console.log('Please connect to MetaMask.');
- } else {
- console.error(error);
- }
- });
- }
注:移动端暂不可用
- document.getElementById('requestPermissionsButton', requestPermissions);
-
- function requestPermissions() {
- ethereum
- .request({
- method: 'wallet_requestPermissions',
- params: [{ eth_accounts: {} }],
- })
- .then((permissions) => {
- const accountsPermission = permissions.find(
- (permission) => permission.parentCapability === 'eth_accounts'
- );
- if (accountsPermission) {
- console.log('eth_accounts permission successfully requested!');
- }
- })
- .catch((error) => {
- if (error.code === 4001) {
- // EIP-1193 userRejectedRequest error
- console.log('Permissions needed to continue.');
- } else {
- console.error(error);
- }
- });
- }
参数:数组
0:加密的消息
1:可以解密该消息在账户
- ethereum
- .request({
- method: 'eth_decrypt',
- params: [encryptedMessage, accounts[0]],
- })
- .then((decryptedMessage) =>
- console.log('The decrypted message is:', decryptedMessage)
- )
- .catch((error) => console.log(error.message));
参数:数组
0:指定账户
- let encryptionPublicKey;
-
- ethereum
- .request({
- method: 'eth_getEncryptionPublicKey',
- params: [accounts[0]], // you must have access to the specified account
- })
- .then((result) => {
- encryptionPublicKey = result;
- })
- .catch((error) => {
- if (error.code === 4001) {
- // EIP-1193 userRejectedRequest error
- console.log("We can't encrypt anything without the key.");
- } else {
- console.error(error);
- }
- });
加密。使用eth-sig-util
项目地址
https://github.com/ethereumjs/ethereumjs-util
- const ethUtil = require('ethereumjs-util');
-
- const encryptedMessage = ethUtil.bufferToHex(
- Buffer.from(
- JSON.stringify(
- sigUtil.encrypt(
- encryptionPublicKey,
- { data: 'Hello world!' },
- 'x25519-xsalsa20-poly1305'
- )
- ),
- 'utf8'
- )
- );
参数:数组
0:AddEthereumChainParameter
- 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.
- }
AddEthereumChainParameter参数说明
-- chainId:链id(hex)
-- chainName:链名称
-- nativeCurrency:币信息:name:名称 symbol:符号 decimals:精度
-- rpcUrls:数组。rpc url
-- blockExplorerUrls:浏览器
方法调用时,返回null代表添加成功。例如添加heco链
- //添加链
- async function addChain() {
- await ethereum.request({
- method: 'wallet_addEthereumChain',
- params: [{
- chainId: '0x80',
- rpcUrls: ['https://http-mainnet.hecochain.com'],
- chainName:'Huobi ECO Chain Mainnet',
- nativeCurrency:
- {
- name:'HT',
- decimals:18,
- symbol:'HT'
- },
- blockExplorerUrls:['https://hecoinfo.com']
-
- }],
- });
- }
参数:数组
- interface SwitchEthereumChainParameter {
- chainId: string; // A 0x-prefixed hexadecimal string
- }
SwitchEthereumChainParameter 参数
-- chainId 链id(hex)
返回null代表成功,返回4902,代表没有添加该链到metamask,需要添加链,配合wallet_addEthereumChain一起使用
配合使用
- async function switchChain() {
- try {
- await ethereum.request({
- method: 'wallet_switchEthereumChain',
- params: [{ chainId: '0x80' }],
- });
- } catch (switchError) {
- // This error code indicates that the chain has not been added to MetaMask.
- if (switchError.code === 4902) {
- try {
- await ethereum.request({
- method: 'wallet_addEthereumChain',
- params: [{ chainId: '0x80', rpcUrls: ['https://http-mainnet.hecochain.com']}],
- });
- } catch (addError) {
- // handle "add" error
- }
- }
- // handle other "switch" errors
- }
- }
注册钱包后,重定向到站点
参数:WatchAssetParams
- 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 5 characters
- decimals: number; // The number of token decimals
- image: string; // A string url of the token logo
- };
- }
返回:Boolean - 如果添加令牌,则为true,否则为false。
- ethereum
- .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)