Farouk YD
Farouk YD

Reputation: 102

How to receive ETH in a smart contract

i am working on an ico and i got this code, the crowdsale was with dai token but i want to work with ether, how can i do that ?

IERC20 public dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);
function buy(uint etherAmount)
    external
    icoActive() {
    require(
      etherAmount >= minPurchase && etherAmount <= maxPurchase, 
      'have to buy between minPurchase and maxPurchase'
    );
    uint tokenAmount = etherAmount.div(price);
    
    require(
      tokenAmount <= availableTokens, 
      'Not enough tokens left for sale'
    );
    dai.transferFrom(msg.sender, address(this), etherAmount);
    token.mint(address(this), tokenAmount);
    sales[msg.sender] = Sale(
        msg.sender,
        tokenAmount,
        false
    );
}

Upvotes: 0

Views: 5025

Answers (2)

Jonathan
Jonathan

Reputation: 61

You need to have receive() fallback function to receive ETH in your smart contract.

Add this function to your smart contract.

receive() external payable {}

Upvotes: 1

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83526

You can use a payable function modifier. See documentation how to receive Ether in smart contracts.

Upvotes: 1

Related Questions