[Ethereum] How to add burn function to an ERC20 and ICO smart contract

contract-development

I have found and deployed an ERC20 smart contract with a crowdsale function.
I could set up:

  • the number of initial tokens which were minted on my address when I deployed the contract
  • the number of tokens reserved to be minted in the crowdsale
  • the price of crowdsale: number of tokens / 1 ETH

I tested it and it's working as supposed. All great.
But now I thought some more and I want a burn function to it. I want to burn 3% from each transaction until total supply reach a specific number or a percentage from the initial supply.
I am not a developer, I just found the code, and I'm afraid to add new functions.
I think the contract is not upgradeable but I am willing the deploy another one with the burn function added.

Can someone help me with the code for the burn functions and explain me where exactly should I insert them in the initial code? Thank you!

Best Answer

Something like this should do it:

function burn(uint256 _value) public returns (bool) {
   
   // Requires that the message sender has enough tokens to burn
   require(_value <= balances[msg.sender]);

   // Subtracts _value from callers balance and total supply
   balances[msg.sender] = balances[msg.sender].sub(_value);
   totalSupply_ = totalSupply_.sub(_value);

   // Emits burn and transfer events, make sure you have them in your contracts
   emit Burn(_who, _value);
   emit Transfer(msg.sender, address(0),_value);

   // Since you cant actually burn tokens on the blockchain, sending to address 0, which none has the private keys to, removes them from the circulating supply
   return true;
}

This function makes it so that anyone can burn their tokens. If you do not want that, add something like msg.sender == _owner (you need to define a contract owner for this). You can get the Burn and Transfer events from OpenZeppelin.

Related Topic