How ERC20 approve function works?

I’m not understanding how erc20 token contract and crowdsale contract works together.

If I set the total supply of tokens in an erc20 token contract why do I have to send it to the crowdsale contract? It wouldn’t be easier to discount from the holder account in erc20 contract?

I also have some doubts about how approve function works. It seems to me that anyone can call this function out of the contract and not onlyOwner. In that way, function approve has to be called in a crowdsale contract?

1 Like

I think in most of cases, Crowdsale contract is just the ERC20 contract, so if you have set the total supply, you need not transfer them to the Crowdsale contract.

Crowdsales are in OpenZeppelin Contracts 2.x (they were removed in 3.x). 
The documentation is here:

As for the approve(spender, amount) function, it seems like a delegate function, Sets amount as the allowance of spender over the caller’s tokens.


Hi @pedromtelho,

You could look at the following simple example where the entire supply of tokens is transferred to the Crowdsale contract to sell: Simple ERC20 Crowdsale

Though you could send what ever amount of tokens you need to the Crowdsale, it doesn’t have to be the total supply.

As for the approve function, the holder of the tokens needs to call approve to set an allowance for another contract to use/spend. See the following example: Example on how to use ERC20 token in another contract