• MetaMask-RPC API


    Ethereum JSON-RPC方法

    api地址

    JSON-RPC API | ethereum.org

    重要的api有

    1. eth_accounts
    2. eth_call
    3. eth_getBalance
    4. eth_sendTransaction
    5. eth_sign

    权限

    有些接口是需要账户授权才可以调用成功

    eth_requestAccounts:返回地址

    请求用户提供要被识别的以太坊地址。返回Promise 解析以太坊地址字符串数组。如果用户拒绝请求,Promise将拒绝并返回4001错误。

    没拿到地址要重新请求才行。

    1. document.getElementById('connectButton', connect);
    2. function connect() {
    3. ethereum
    4. .request({ method: 'eth_requestAccounts' })
    5. .then(handleAccountsChanged)
    6. .catch((error) => {
    7. if (error.code === 4001) {
    8. // EIP-1193 userRejectedRequest error
    9. console.log('Please connect to MetaMask.');
    10. } else {
    11. console.error(error);
    12. }
    13. });
    14. }

    wallet_getPermissions:获取调用者钱包授权数组

    注:移动端暂不可用

    wallet_requestPermissions:请求权限

    1. document.getElementById('requestPermissionsButton', requestPermissions);
    2. function requestPermissions() {
    3. ethereum
    4. .request({
    5. method: 'wallet_requestPermissions',
    6. params: [{ eth_accounts: {} }],
    7. })
    8. .then((permissions) => {
    9. const accountsPermission = permissions.find(
    10. (permission) => permission.parentCapability === 'eth_accounts'
    11. );
    12. if (accountsPermission) {
    13. console.log('eth_accounts permission successfully requested!');
    14. }
    15. })
    16. .catch((error) => {
    17. if (error.code === 4001) {
    18. // EIP-1193 userRejectedRequest error
    19. console.log('Permissions needed to continue.');
    20. } else {
    21. console.error(error);
    22. }
    23. });
    24. }

    其他的RPC方法

    eth_decrypt 消息解密

    参数:数组

    0:加密的消息

    1:可以解密该消息在账户

    1. ethereum
    2. .request({
    3. method: 'eth_decrypt',
    4. params: [encryptedMessage, accounts[0]],
    5. })
    6. .then((decryptedMessage) =>
    7. console.log('The decrypted message is:', decryptedMessage)
    8. )
    9. .catch((error) => console.log(error.message));

    eth_getEncryptionPublicKey 获取加密公钥

    参数:数组

    0:指定账户

    1. let encryptionPublicKey;
    2. ethereum
    3. .request({
    4. method: 'eth_getEncryptionPublicKey',
    5. params: [accounts[0]], // you must have access to the specified account
    6. })
    7. .then((result) => {
    8. encryptionPublicKey = result;
    9. })
    10. .catch((error) => {
    11. if (error.code === 4001) {
    12. // EIP-1193 userRejectedRequest error
    13. console.log("We can't encrypt anything without the key.");
    14. } else {
    15. console.error(error);
    16. }
    17. });

    加密。使用eth-sig-util

    项目地址

    https://github.com/ethereumjs/ethereumjs-util

    1. const ethUtil = require('ethereumjs-util');
    2. const encryptedMessage = ethUtil.bufferToHex(
    3. Buffer.from(
    4. JSON.stringify(
    5. sigUtil.encrypt(
    6. encryptionPublicKey,
    7. { data: 'Hello world!' },
    8. 'x25519-xsalsa20-poly1305'
    9. )
    10. ),
    11. 'utf8'
    12. )
    13. );

    wallet_addEthereumChain 弹窗确认添加链到metamask

    参数:数组

    0:AddEthereumChainParameter

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

    AddEthereumChainParameter参数说明

    -- chainId:链id(hex)

    -- chainName:链名称

    -- nativeCurrency:币信息:name:名称 symbol:符号 decimals:精度

    -- rpcUrls:数组。rpc url

    -- blockExplorerUrls:浏览器

    方法调用时,返回null代表添加成功。例如添加heco链

    1. //添加链
    2. async function addChain() {
    3. await ethereum.request({
    4. method: 'wallet_addEthereumChain',
    5. params: [{
    6. chainId: '0x80',
    7. rpcUrls: ['https://http-mainnet.hecochain.com'],
    8. chainName:'Huobi ECO Chain Mainnet',
    9. nativeCurrency:
    10. {
    11. name:'HT',
    12. decimals:18,
    13. symbol:'HT'
    14. },
    15. blockExplorerUrls:['https://hecoinfo.com']
    16. }],
    17. });
    18. }

    wallet_switchEthereumChain 切换链

    参数:数组

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

    SwitchEthereumChainParameter 参数

    -- chainId 链id(hex)

    返回null代表成功,返回4902,代表没有添加该链到metamask,需要添加链,配合wallet_addEthereumChain一起使用

    配合使用

    1. async function switchChain() {
    2. try {
    3. await ethereum.request({
    4. method: 'wallet_switchEthereumChain',
    5. params: [{ chainId: '0x80' }],
    6. });
    7. } catch (switchError) {
    8. // This error code indicates that the chain has not been added to MetaMask.
    9. if (switchError.code === 4902) {
    10. try {
    11. await ethereum.request({
    12. method: 'wallet_addEthereumChain',
    13. params: [{ chainId: '0x80', rpcUrls: ['https://http-mainnet.hecochain.com']}],
    14. });
    15. } catch (addError) {
    16. // handle "add" error
    17. }
    18. }
    19. // handle other "switch" errors
    20. }
    21. }

    wallet_registerOnboarding 注册重载站点

    注册钱包后,重定向到站点

    wallet_watchAsset 资产监听,代币添加

    参数:WatchAssetParams

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

    返回:Boolean - 如果添加令牌,则为true,否则为false。

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

  • 相关阅读:
    源码安装部署drbd9
    猿创征文|Linux centos7下利用docker快速部署SQLserver测试学习环境
    Tomcat调优【精简版】
    Java 如何让HashMap集合按照value进行排序呢?
    cadence SPB17.4 - allegro - Allegro2Altium.bat 初探
    集合{Collection集合 迭代器 ArrayList集合 LinkedList集合 HashMap集合 }(一)
    【动态规划刷题 18】(hard)回文子串&& (hard)最长回文子串
    基于Servlet+jsp+mysql开发javaWeb学生管理系统(学生信息、学生选课、学生成绩、学生签到考勤)
    第三方软件测试服务有哪些形式?选择时如何避雷?
    C语言错误:计算字符串中特定单词的出现次数
  • 原文地址:https://blog.csdn.net/dandelionLYY/article/details/126098072