-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauctionfixed.sol
More file actions
96 lines (73 loc) · 2.88 KB
/
auctionfixed.sol
File metadata and controls
96 lines (73 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Auction {
address payable public beneficiary;
uint public auctionEndTime;
address public highestBidder;
uint public highestBid;
// Mapping to track pending returns for outbid bidders
mapping(address => uint) public pendingReturns;
// Track if auction has ended
bool private ended;
event HighestBidIncreased(address bidder, uint amount);
event AuctionEnded(address winner, uint amount);
constructor(uint _biddingTime, address payable _beneficiary) {
beneficiary = _beneficiary;
auctionEndTime = block.timestamp + _biddingTime;
}
function bid() public payable {
// Check if auction has ended
if(block.timestamp > auctionEndTime) {
revert("The auction has ended");
}
// Check if bid is high enough
if(msg.value <= highestBid) {
revert("Sorry, the bid is not high enough");
}
// Store previous highest bid for withdrawal
if(highestBid != 0) {
pendingReturns[highestBidder] += highestBid;
}
// Update highest bidder and bid
highestBidder = msg.sender;
highestBid = msg.value;
emit HighestBidIncreased(msg.sender, msg.value);
}
// Withdraw bids that were overbid
function withdraw() public returns(bool) {
uint amount = pendingReturns[msg.sender];
if(amount > 0) {
// Set to zero before sending to prevent re-entrancy attacks
pendingReturns[msg.sender] = 0;
// Use call instead of send for better error handling
(bool success, ) = payable(msg.sender).call{value: amount}("");
if(!success) {
// Restore the pending amount if transfer fails
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
function auctionEnd() public {
// Check if auction time has passed
if(block.timestamp < auctionEndTime) {
revert("The auction has not ended yet");
}
// Check if already ended
if(ended) {
revert("The auction is already over!");
}
// Mark as ended
ended = true;
emit AuctionEnded(highestBidder, highestBid);
// Transfer the highest bid to beneficiary
beneficiary.transfer(highestBid);
}
// Helper function to check time remaining
function getTimeRemaining() public view returns(uint) {
if(block.timestamp >= auctionEndTime) {
return 0;
}
return auctionEndTime - block.timestamp;
}