-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathRateLimiter.sol
More file actions
56 lines (42 loc) · 1.81 KB
/
Copy pathRateLimiter.sol
File metadata and controls
56 lines (42 loc) · 1.81 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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@nilfoundation/smart-contracts/contracts/NilBase.sol";
contract RateLimiter is NilBase {
uint256 public constant RATE_LIMIT_PERIOD = 1 hours;
uint256 public constant MAX_REQUESTS_PER_PERIOD = 5;
mapping(address => uint256) public lastRequestTimestamp;
mapping(address => uint256) public requestsInCurrentPeriod;
event RequestProcessed(address indexed user, uint256 timestamp);
event PeriodReset(address indexed user, uint256 timestamp);
modifier rateLimited() {
require(_checkRateLimit(msg.sender), "Rate limit exceeded");
_;
}
function _checkRateLimit(address user) internal returns (bool) {
uint256 currentPeriod = block.timestamp / RATE_LIMIT_PERIOD;
uint256 lastPeriod = lastRequestTimestamp[user] / RATE_LIMIT_PERIOD;
if (currentPeriod > lastPeriod) {
requestsInCurrentPeriod[user] = 0;
emit PeriodReset(user, block.timestamp);
}
if (requestsInCurrentPeriod[user] >= MAX_REQUESTS_PER_PERIOD) {
return false;
}
requestsInCurrentPeriod[user]++;
lastRequestTimestamp[user] = block.timestamp;
emit RequestProcessed(user, block.timestamp);
return true;
}
function processRequest() external rateLimited returns (bool) {
// Simulated processing logic
return true;
}
function getRemainingRequests(address user) external view returns (uint256) {
uint256 currentPeriod = block.timestamp / RATE_LIMIT_PERIOD;
uint256 lastPeriod = lastRequestTimestamp[user] / RATE_LIMIT_PERIOD;
if (currentPeriod > lastPeriod) {
return MAX_REQUESTS_PER_PERIOD;
}
return MAX_REQUESTS_PER_PERIOD - requestsInCurrentPeriod[user];
}
}