2

This question already has an answer here:

I read in a lot of places that the fallback function only has a gas stipend of 2300 and nothing should be done in there except logging.

But then, I see contracts like crowdsales with the following code:

// fallback function can be used to buy tokens
  function () payable {
    buyTokens(msg.sender);
  }

  // low level token purchase function
  function buyTokens(address beneficiary) public payable {
    require(beneficiary != address(0));
    require(validPurchase());

    uint256 weiAmount = msg.value;

    // calculate token amount to be created
    uint256 tokens = weiAmount.mul(rate);

    // update state
    weiRaised = weiRaised.add(weiAmount);

    token.mint(beneficiary, tokens);
    TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);

    forwardFunds();
  }

How is it possible that buyTokens function gets successfully called by the fallback function if it definitively will cost more than the allowed 2300 gas?

marked as duplicate by SteveJaxon, Malone, Richard Horrocks, Achala Dissanayake, Badr Bellaj Nov 10 '17 at 23:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    When called directly from a transaction the gas stipend does not apply. It only applies when fallback is called from another contract trough the transfer function. – Ismael Nov 9 '17 at 15:13
  • So, if someone wanted to send ether to this contract to buy tokens, they could just send to the address through any wallet, while also sending enough gas along with the transaction, right? – ETHQuestion Nov 9 '17 at 15:42
  • Yes, you are correct, when you make a transfer from a wallet to a crowdsale contract the stipend limit does not apply. – Ismael Nov 11 '17 at 5:59

Browse other questions tagged or ask your own question.