1

我是智能合约开发的初学者。我正在使用 openZeppelin、truffle 和 Ganache 来开发一些非常基本的代币和众筹合约。当我尝试buytoken()从 Truffle 控制台中的众筹合约中调用该方法时遇到了一个错误。有人可以帮我解决问题吗?迁移和部署合约时没有问题。

contract Crowdsale {
    using SafeMath for uint256;

// The token being sold
    ERC20 public token;

// Address where funds are collected
    address public wallet;

// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;

// Amount of wei raised
    uint256 public weiRaised;

/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
    event TokenPurchase(
        address indexed purchaser,
        address indexed beneficiary,
        uint256 value,
        uint256 amount
);

/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
    constructor(uint256 _rate, address _wallet, ERC20 _token) public {
        require(_rate > 0);
        require(_wallet != address(0));
        require(_token != address(0));

        rate = _rate;
        wallet = _wallet;
        token = _token;
}

// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------

/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {

}

/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
    function buyTokens(address _beneficiary, uint256 amount) public payable {

        uint256 weiAmount = amount.mul(rate);

        token.transfer(_beneficiary, weiAmount);

}

下面列出了 truffle 控制台命令:

myToken.deployed().then(function(i){BT = i})
myCrowdsale.deployed().then(function(i){BTC = i})
BT.transferOwnership(BTC.address)
purchaser = web3.eth.accounts[2]
BTC.buyTokens(purchaser,web3.toWei(5, "ether") )
4

1 回答 1

1

在实施 a 时payable,支付的金额不能作为参数,而是在msg.value. 否则,如果我使用以下方法调用该方法,则您不会发送任何以太币,和/或可以被利用:5 etherasamount但我只发送1 wei.

function buyTokens(address _beneficiary) public payable {

        uint256 weiAmount = msg.value.mul(rate);

        token.transfer(_beneficiary, weiAmount);

}

Furthermore, if the beneficiary address is the same that buys the token, you can use: msg.sender

And the method must be called like this:

BTC.buyTokens(purchaser, { value: web3.toWei(5, "ether"), from: purchaser });

or using msg.sender

BTC.buyTokens({ value: web3.toWei(5, "ether"), from: purchaser });

If you don't use: from the ethers will be sent by the default account, which is not purchaser in your case.

于 2018-06-22T12:55:33.313 回答