【问题标题】:Gas required exceeds limit: 3000000.所需气体超过限制:3000000。
【发布时间】:2018-02-24 07:12:12
【问题描述】:
pragma solidity ^0.4.16;

contract createNewToken {
    uint256 total_ether_to_send;
    address private owner;

    //constructor
    function createNewToken() public{
        owner = msg.sender;
    }

    // client request for tokens by sending ether.
    function requestForToken() public payable{
        address sender = msg.sender;
        uint value = msg.value;
        total_ether_to_send = value;
        require(sender.balance >= total_ether_to_send);
        owner.transfer(total_ether_to_send);

        total_ether_to_send = value / 2;
        require(owner.balance >= total_ether_to_send);
        sender.transfer(total_ether_to_send);
    } 
}

我已经在 Remix IDE 中可靠地编写了这段代码。合约已成功创建,但当我使用它时,它给了我一个错误,说 “所需的气体超出限制:3000000。重要的气体估计也可能是合约代码中存在问题的迹象。请检查循环并确定您没有向非应付函数发送值”。我没有编写太多代码,但它仍然给了我这个错误。有人可以帮忙吗?

【问题讨论】:

  • 这个问题更适合ethereum.stackexchange.com

标签: blockchain ethereum solidity smartcontracts remix


【解决方案1】:

首先,您的msg.value 已经发送到您的方法,因此您无需检查发件人余额:require(sender.balance >= total_ether_to_send);

第二,你的合约中没有接收以太币的后备功能。

第三,您尝试将 100% msg.value 发送给所有者,然后将 50% 的 msg.value 发送回发件人。显然,如果您的合约没有任何额外资金,您就不能花费 150% 的 msg.value。这是工作代码的示例:

function requestForToken() public payable{
    address sender = msg.sender;
    uint value = msg.value;
    total_ether_to_send = value / 2;
    require(this.balance >= total_ether_to_send);
    owner.transfer(total_ether_to_send);

    require(this.balance >= total_ether_to_send);
    sender.transfer(total_ether_to_send);
} 

function() payable {}

【讨论】:

  • 我得到了你的第一个和第二个,但不能接受第三个。它的150%如何。首先我排除了 100%,然后退还了 50%(可以说是折扣)。我想写一份我接受以太币并向他们提供我的代币的合同。我想我必须写这些类型的行。我也尝试过类似 total_ether_to_send = msg.value token_name / token_symbol 之类的东西,但尽管我创建了一个新令牌,但这不起作用。我想发送一些代币以换取一些以太币。所以我开始使用这种类型的代码,但它们效果不佳。你能帮助如何发送令牌
  • @Harsh 您正在从您的智能合约向所有者发送 100% 的 msg.value。在此操作之后,您的合约中有 0% 的 msg.value 可用,而您仍在尝试发送 50% 的 msg.value。把它想象成发送者向你的合约发送了 100 wei。你将 100 wei 从合约转移给所有者。之后,当合约余额为 0 时,您尝试从合约向发送者发送 50 wei。
  • 知道了,但不发送 sender.transfer(50) 将再次从所有者帐户退回资金。或者它会使用合约账户。如果它来自合同帐户,那么我如何将其从所有者帐户发送给发件人。那么发送代币呢?谢谢回复。非常感谢。 @罗马
  • @Harsh 它将使用合约的余额。如果您想获得 50% 的折扣,只需向发送者提供 2 倍的代币即可。顺便说一句,在众筹中发送代币,您可以使用例如balances[msg.sender] += msg.value / tokenPrice,其中tokenPrice 为wei。
猜你喜欢
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多