我是智能合约开发的初学者。我正在使用openZeppelin,松露和Ganache开发一些非常基本的令牌和众包合同。尝试从Truffle控制台的众包合同中调用buytoken()
方法时遇到错误。有人可以帮我解决问题吗?迁移和部署合同时没有问题。
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);
}
松露控制台命令如下:
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") )
答案 0 :(得分:1)
实施payable
时,支付的金额一定不能作为参数,而可以在msg.value
使用。否则,如果我用5 ether
作为amount
来调用该方法,但是我只发送1 wei
,则您不会发送任何以太币,并且/或者可能被利用。
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value.mul(rate);
token.transfer(_beneficiary, weiAmount);
}
此外,如果受益人地址与购买令牌的地址相同,则可以使用:msg.sender
该方法必须这样调用:
BTC.buyTokens(purchaser, { value: web3.toWei(5, "ether"), from: purchaser });
或使用msg.sender
BTC.buyTokens({ value: web3.toWei(5, "ether"), from: purchaser });
如果您不使用:from
,以太币将通过默认帐户发送,默认情况下不是purchaser
。