#21DaysSolidityChallenge Day 5: Adding Transparency to Your Token Contract with Events in Solidity

Solidity Academy
Coinmonks

--

🚀 Buy me a coffee! ☕ http://buymeacoffee.com/solidity

👋 Welcome to Day 5 of our Solidity Code Challenge series! In today’s challenge, we’re going to enhance your ERC-20 token contract by incorporating events. Events are an essential tool in Ethereum smart contract development that provide transparency and allow external applications to react to specific contract actions.

#21DaysSolidityChallenge 21 Days Solidity Coding Challenge

Oh, this magical link is just sooo tempting! đŸȘ„✚ Click away, my dear friend. 😉

📣 Events in Ethereum: A Quick Overview

Before we dive into today’s challenge, let’s briefly discuss what events are and why they matter:

- Events: In Ethereum, events are used to notify external applications or users about specific activities that have occurred within a smart contract. They provide a transparent way to monitor contract behavior.

Now, let’s get started with the challenge!

Step 1: Setting Up Your Development Environment

Ensure you have the following tools and accounts ready:

1. Ethereum Wallet: You’ll need an Ethereum wallet like MetaMask to interact with the Ethereum blockchain.

2. Solidity Compiler: Have the Solidity compiler (solc) installed on your computer or use online Solidity development environments like Remix.

3. Test Network: Choose a test network (e.g., Ropsten, Rinkeby, or Kovan) to deploy and test your token contract without using real Ether.

4. Integrated Development Environment (IDE): Consider using an IDE like Visual Studio Code with Solidity extensions for a smoother coding experience.

Step 2: Enhancing Your Token Contract with Events

We’ll continue building upon your `MyToken.sol` contract from Day 4. In this step, you’ll add events for token transfers, approvals, and role changes.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol";
contract MyToken is ERC20Pausable, Ownable {
event TokensMinted(address indexed minter, address indexed to, uint256 amount);
event TokensBurned(address indexed burner, uint256 amount);
event MinterRoleGranted(address indexed owner, address indexed minter);
event MinterRoleRevoked(address indexed owner, address indexed minter);
event Paused(address account);
event Unpaused(address account);
constructor(uint256 initialSupply) ERC20("My Token", "MT") {
_mint(msg.sender, initialSupply * 10 ** uint256(decimals()));
}
function mint(address to, uint256 amount) public onlyMinter {
_mint(to, amount);
emit TokensMinted(msg.sender, to, amount);
}
function burn(uint256 amount) public onlyOwner {
_burn(msg.sender, amount);
emit TokensBurned(msg.sender, amount);
}
function grantMinterRole(address account) public onlyOwner {
_setupRole(DEFAULT_ADMIN_ROLE, account);
grantRole(MINTER_ROLE, account);
emit MinterRoleGranted(msg.sender, account);
}
function revokeMinterRole(address account) public onlyOwner {
revokeRole(MINTER_ROLE, account);
emit MinterRoleRevoked(msg.sender, account);
}
function pause() public onlyPauser {
_pause();
emit Paused(msg.sender);
}
function unpause() public onlyPauser {
_unpause();
emit Unpaused(msg.sender);
}
}

In this updated contract:

- We’ve added events for various contract actions:
— `TokensMinted`: This event is emitted when tokens are minted and includes the minter’s address, the recipient’s address, and the amount minted.

- `TokensBurned`: This event is emitted when tokens are burned and includes the burner’s address and the amount burned.

- `MinterRoleGranted`: This event is emitted when the minter role is granted and includes the owner’s address and the address receiving the minter role.

- `MinterRoleRevoked`: This event is emitted when the minter role is revoked and includes the owner’s address and the address losing the minter role.

- `Paused`: This event is emitted when token transfers are paused.

- `Unpaused`: This event is emitted when token transfers are resumed.

- We’ve also included `emit` statements within the respective functions to trigger these events when the corresponding actions occur.

Step 3: Compiling the Enhanced Token Contract

Compile your enhanced ERC-20 token contract using the Solidity compiler. Use the following command in your terminal:

solc - bin - abi MyToken.sol

This command generates the bytecode (`MyToken.bin`) and ABI (`MyToken.abi`) required for contract deployment.

Step 4: Deploying the Enhanced ERC-20 Token Contract

Deploy your enhanced ERC-20 token contract to a test network. Follow these steps:

1. Open your Ethereum wallet (e.g., MetaMask) and switch to the Ropsten network.

2. Acquire some test Ether for Ropsten from a faucet. You can find a faucet by searching “Ropsten faucet” online.

3. Deploy your contract using a tool like Remix or Truffle, or manually through a script.

- Go to Remix (https://remix.ethereum.org/).

- Click the “Solidity” tab.

- Create a new file, paste your enhanced contract code, and compile it.

- Switch to the “Deploy & Run Transactions” tab.

- Ensure your environment is set to “Injected Web3” (if you’re using MetaMask).

- Click the “Deploy” button.

4. Confirm the deployment in your wallet, and your contract will be deployed to the Ropsten network.

Step 5: Writing a Script to Listen for Events

Now that your contract is deployed and events are being emitted, you can write a JavaScript script to listen for these events and display them when they occur. Here’s a simple example using web3.js:

const Web3 = require('web3');
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL'); // Replace with your Ethereum node URL
const contractAddress = 'YOUR_CONTRACT_ADDRESS'; // Replace with your contract address
const contractABI = [
]; // Replace with your contract ABI
const myTokenContract = new web3.eth.Contract(contractABI, contractAddress);
// Listening for the TokensMinted event
myTokenContract.events.TokensMinted({})
.on('data', (event) => {
console.log('Tokens Minted:');
console.log('Minter:', event.returnValues.minter);
console.log('Recipient:', event.returnValues.to);
console.log('Amount:', event.returnValues.amount);
})
.on('error', console.error);
// Listening for other events (TokensBurned, MinterRoleGranted, MinterRoleRevoked, Paused, Unpaused) similarly


Replace `’YOUR_ETHEREUM_NODE_URL’`, `’YOUR_CONTRACT_ADDRESS’`, and `’contractABI’` with your Ethereum node URL, contract address, and ABI respectively.

This script listens for the `TokensMinted` event and displays the relevant information when the event is emitted. You can adapt it to listen for other events in a similar manner.

🎉 Congratulations! You‘ve successfully enhanced your token contract with events and created a script to listen for and display these events.

Conclusion 🌟

In this Day 5 challenge, you’ve added transparency to your ERC-20 token contract by incorporating events. Events are a crucial aspect of Ethereum smart contract development, providing insight into contract activities and enabling external applications to respond to contract events.

As you continue through the Solidity Code Challenge series, you’ll explore more advanced topics and build increasingly complex smart contracts. Keep up the great work, and embrace the power of Ethereum!

🚀 Happy coding! 🚀

📚 Resources 📚

--

--

Solidity Academy
Coinmonks
Writer for

Learn smart contract development and blockchain integration in depth. https://heylink.me/solidity/ SEND US Your Products to Review! solidity101@gmail.com