- Extend the ERC20 contract to create a new burnable token contract:
pragma solidity ^0.4.23;
import "./ERC20.sol";
contract Burnable is ERC20 {
...
}
- Create a function that can be called by the user to burn some tokens:
function burn(uint256 _value) public { }
- Verify whether the sender has enough balance to burn:
require(_value <= balances[msg.sender]);
- While burning tokens, subtract the number of tokens burnt from the balance of the current holder and from total supply:
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
- Emit an event for every token burning transaction. Create a burn event with the sender address and value as parameters:
// Event declaration
event Burn(address indexed burner, uint256 value);
// Emit the event during burning process
emit Burn(msg.sender, _value);
- It is also recommended to emit the transfer function that marks a transfer to the null address. Transferring a token to the null address makes it unusable:
emit Transfer(msg.sender, address(0), _value);
- Modify the contract further by creating an internal function that allows other contracts to burn tokens for users. This can improve the reusability of the function:
pragma solidity ^0.4.23;
import "./ERC20.sol";
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
/**
* @dev Internal function for burning tokens.
* @param _user Address to burn the tokens from.
* @param _value Amount of token to be burned.
*/
function _burn(address _user, uint256 _value) internal {
require(_value <= balances[_user]);
balances[_user] = balances[_user].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_user, _value);
emit Transfer(_user, address(0), _value);
}
}