METAMASK - 注入 - 用户如何使用元掩码 API 支付 ETH 的自定义价值?

问题描述

  1. 我想让用户可以选择自己的以太币价值。如何做到这一点?
  2. 按下连接到元掩码时更改网络的效率如何(例如,当用户按下此按钮时,元掩码应将网络更改为币安智能链 (ID 56))

这是我的代码

        <!DOCTYPE html>
        <html>
        <head>
        <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
        </head>
        <body>
        <div>
        <button class="enableEthereumButton btn">Enable Ethereum</button>
        <button class="sendEthButton btn">Send Eth</button>
        <div id="status"></div>
        </div>
        <script type="text/javascript">

        // Running on the page,in the browser
        if (typeof window.ethereum !== 'undefined') {
          console.log('MetaMask is installed!');
        }   
        if (!ethereum || !ethereum.isMetaMask) {
          throw new Error('Please install MetaMask.')
        }   
        /*********************************************************/
        /* Handle chain (network) and chainChanged,per EIP 1193 */
        /*********************************************************/

        // Do this:
        ethereum.on('chainChanged',(chainId) => {
          /* handle the chainId */
        });
        const ethereumButton = document.querySelector('.enableEthereumButton');
        const sendEthButton = document.querySelector('.sendEthButton');

        let accounts = [];

        //Sending Ethereum to an address
        sendEthButton.addEventListener('click',() => {
          ethereum
            .request({
              method: 'eth_sendTransaction',params: [
                {
                  from: accounts[0],to: '0x6adress.................',value: '0x00',gasPrice: '0x0000001F6EA08600',gas: '0x0001ADB0',},],})
            .then((txHash) => console.log(txHash))
            .catch((error) => console.error);
        });

        ethereumButton.addEventListener('click',() => {
          getAccount();
        });

        async function getAccount() {
          accounts = await ethereum.request({ method: 'eth_requestAccounts' });
        }
        </script>
        </body>
        </html>

Metamask screenshot

解决方法

为该值添加一个输入字段并将其传递给您的参数。这是基本的 html 表单 + javascript 交互,并非特定于 web3,因此有关如何执行此操作的更多信息,我会在此处查看 https://www.w3schools.com/html/html_forms.asp

要读取用户在您的应用中连接的网络,您可以监听链更改事件:https://docs.metamask.io/guide/ethereum-provider.html#events

如果他们没有连接到您的应用支持的网络,您应该向用户显示通知。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...