I was following a tutorial that can buy erc20 tokens and I'm now stuck with transferring tokens to a buyer account which I need more clarification. So basically, a buyer account is trying to purchase some tokens. That's it.
For example, there's a contract that implements erc20 functions
contract DappToken {
//...
mapping(address => uint256) public balanceOf;
function DappToken (uint256 _initialSupply) public {
balanceOf[msg.sender] = _initialSupply;
totalSupply = _initialSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
}
and there's another contract that takes DappToken
contract as a parameter of its constructor.
contract DappTokenSale {
//...
function DappTokenSale(DappToken _tokenContract, uint256 _tokenPrice) public {
admin = msg.sender;
tokenContract = _tokenContract;
tokenPrice = _tokenPrice;
}
function buyTokens(uint256 _numberOfTokens) public payable {
require(msg.value == multiply(_numberOfTokens, tokenPrice));
require(tokenContract.balanceOf(this) >= _numberOfTokens);
require(tokenContract.transfer(msg.sender, _numberOfTokens));
tokensSold += _numberOfTokens;
Sell(msg.sender, _numberOfTokens);
}
}
Here's my question, how does a buyer pass below requirement in buyTokens
function?
require(tokenContract.transfer(msg.sender, _numberOfTokens));
My understanding is..
- When the buyer tries to buy tokens, it will call
transfer
function inDappToken
contract passing buyer's account address (msg.sender
) and the number of tokens to purchase (_numberOfTokens
). transfer
function inDappToken
contract will check if the buyer has existing balance.require(balanceOf[msg.sender] >= _value);
But I don't understand why there's a check to see if a buyer has existing balance? What if it was the buyer's first time purchasing the tokens? then the buyer won't have existing tokens in balanceOf
variable initially.
or is the msg.sender
in transfer
function a DappTokenSale
's contract address?