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=
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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