Goal: add events to a contract, emit on set()
, then find and interpret logs in Remix (including indexed topics).
indexed
parameters become searchable topics (filterable by frontends & APIs).Create SimpleStorageEvents.sol and paste:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorageEvents {
uint256 private storedData;
// Event with three indexed topics for fast filtering
event ValueChanged(
uint256 indexed oldValue,
uint256 indexed newValue,
address indexed setter
);
function set(uint256 x) public {
uint256 oldVal = storedData;
storedData = x;
emit ValueChanged(oldVal, x, msg.sender);
}
function get() public view returns (uint256) {
return storedData;
}
}
ValueChanged
with topics and data.
oldValue
, newValue
, setter
42
.On Ganache, you can also inspect the receipt in Ganache’s Transactions tab for the same event.
// Listen for events (ethers v6)
import { BrowserProvider } from "ethers";
const provider = new BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
const c = new ethers.Contract(addr, abi, signer);
c.on("ValueChanged", (oldV, newV, who, ev) => {
console.log("ValueChanged", oldV.toString(), newV.toString(), who);
});
Events are the preferred way to notify UIs of changes; avoid scanning storage in loops.
set()
, not just get()
.ValueChanged
event log.get()
returning your latest value.Next: ICE 4 – Frontend (ethers.js): build a tiny web page that connects to MetaMask and calls set/get, listening for events.