Rate Limit
Background
The rate limit package was designed to provide cooldown functionality on-chain. This works great for:
- Daily Rewards
- Tower Defense Games
- Simulation Games
- Minting Applications
Rate limit is great for when you want to ensure that functions are being called only once per period.
Installation
npm add @dirtroad/sediment
yarn add @dirtroad/sediment
pnpm add @dirtroad/sediment
Using Rate Limit
// SPDX-License-Identifier: MITpragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";import "@dirtroad/sediment/contracts/authority/Authority.sol";import "@dirtroad/sediment/contracts/security/RateLimit.sol";
contract Freemium is Authority, RateLimit {
using SafeERC20 for IERC20;
IERC20 public paymentToken;
event Consume();
constructor(IERC20 _paymentToken) RateLimit(60 minutes) { paymentToken = _paymentToken; }
function consumeForFree() public checkLimit(_msgSender()) { emit Consume(); }
function consume() external { if (cooldown + uint64(block.timestamp) > limits[_msgSender()]) { consumeForFree(); } else { paymentToken.safeTransferFrom(_msgSender(), address(this), 1 * 10 ** 18); emit Consume(); } }
function withdraw() external onlyRole(MANAGER_ROLE) { paymentToken.safeTransferFrom(address(this), _msgSender(), paymentToken.balanceOf(address(this))); }}
API
Solidity API
RateLimit
cooldown
uint64 cooldown
limits
mapping(address => uint64) limits
checkLimit
modifier checkLimit(address user)
constructor
constructor(uint256 _cooldownInSeconds) public