Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.7+commit.e28d00a7.js&optimize=false&runs=200&gist=
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract EventsContract {
// Represents the time when the bidding will end
uint biddingEnds = block.timestamp + 5 days;
struct HighestBidder {
address bidder;
string bidderName;
uint bid;
}
// Variable of type HighestBidder
HighestBidder public highestBidder;
// Events emitted by contract
// Whenever a high bid is received
event NewHighBid(address indexed who, string name, uint howmuch);
// High bid preceded by this event
event BidFailed(address indexed who, string name, uint howmuch);
// Ensures that bid can be received i.e, auction not ended
modifier timed {
if(block.timestamp < biddingEnds){
_;
} else {
/**throw an exception */
revert("Throw an exception");
}
}
constructor() {
// Starts the bidding at 1 ether
highestBidder.bid = 1 ether;
}
// Payable since ether should be coming along
// Timed, we need to end this bidding in 5 days
function bid(string memory bidderName) public payable timed {
if(msg.value > highestBidder.bid) {
highestBidder.bidder = msg.sender;
highestBidder.bidderName = bidderName;
highestBidder.bid = msg.value;
// Received a high bid - emit event
emit NewHighBid(msg.sender, bidderName, msg.value);
} else {
// Received bid less than high bid emit event
emit BidFailed(msg.sender, bidderName, msg.value);
// throwing exception would return the ethers
revert("Throw an exception");
}
}
}
@shoupn
Copy link
Author

shoupn commented Feb 5, 2022

This is an example of using modifiers/events and time in a contract. The struct is a common data structure used in solidity in this example using it to create the highestBidder object.

Notes about events

  • Part of the contract ABI
  • Must subscribe to the event in frontend/web application
  • Runs on all nodes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment