如何在元掩码中添加方法 ID

问题描述

我已经使用 remix IDE 部署了智能合约,在 Ropsten 测试网络上使用 Injected Web3 启动。我可以在 solidity IDE 中成功调用 BuyTokens 函数,但是当尝试从其他地址交易购买带有元掩码的代币时会被恢复。我可以在 ropsten.etherscan explorer 上看到这些操作之间的区别 - 区别在于 Input Data 字段。 Metamask 交易的值为 0x,通过 remix 的交易是:

Function: buyTokens() ***

MethodID: 0xd0febe4c

代码

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.0;


contract Token {
    // Track how many tokens are owned by each address.
    mapping (address => uint256) public balanceOf;

    // Modify this section
    string public name = "DemoCoin";
    string public symbol = "DC";
    uint8 public decimals = 8;
    uint256 public totalSupply = 1000000000 * (uint256(10) ** decimals);
    address public owner;
    //uint scaler = 10e18; // == 1 ETH in wei
    //uint public coinPrice = 20; //initial price => 20 cents
    event Transfer(address indexed from,address indexed to,uint256 value);

    constructor()  {
        // Initially assign all tokens to the contract's creator.
        owner = msg.sender;
        balanceOf[msg.sender] = totalSupply;
        emit Transfer(address(0),msg.sender,totalSupply);
    }
    
    // Might be executed automaticlly
    // https://blog.chronologic.network/schedule-your-transaction-Now-using-mycrypto-and-myetherwallet-17b48166b412
    
    // function changeCoinPrice() public {
    //     uint newCoinPrice;
    //     require(msg.sender == address(0));
    //     coinPrice = newCoinPrice;
        
    // }
    
    function buyTokens() public payable {
        // msg.value in wei so 1ETH = 10e18
        // lets set 0.20 cents for 1 token
        uint paidamount;
        
        require(balanceOf[msg.sender] >= paidamount);
        require(balanceOf[owner] >= value);
        uint tokens;
        tokens = value/10e14;
        balanceOf[owner] -= tokens;
        balanceOf[msg.sender] += tokens;
        emit Transfer(owner,tokens);
    }
    
    function msgSenderBalancce() public view returns (uint) {
        return balanceOf[msg.sender];
    }
    
    function withDrawEth() public view {
        require(msg.sender == owner);
        
        
    }

}

为什么这些方法调用方式不同?以及如何在元掩码中添加方法 ID?还是我遗漏了什么,应该以其他方式处理?

解决方法

MetaMask 有一个非常基本的用户界面。它只允许转账 ETH 和标准化代币,但不显示任何调用其他合约功能的按钮。它还不允许在其 UI 中创建任何自定义按钮。

您需要将交易的 data 字段设置为 0xd0febe4c(有效执行 buyTokens() 函数)。

但是 - 它们也不允许在 UI 中手动指定 data 字段值,因此您需要使用 Ethereum 提供程序 API 对其进行预设。

  1. 您的网络应用 connects 到用户的 MetaMask 帐户。它会打开一个 MetaMask 窗口,用户需要手动确认连接。
  2. 网络应用程序 sends a request 到 MetaMask,指定具有 data 字段值的交易。
  3. 用户在其 MetaMask UI 中确认交易(现在包含 data 字段值 0xd0febe4c)。

相关问答

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