Skip to content

Rate Limit

Background

The rate limit package was designed to provide cooldown functionality on-chain. This works great for:

  1. Daily Rewards
  2. Tower Defense Games
  3. Simulation Games
  4. Minting Applications

Rate limit is great for when you want to ensure that functions are being called only once per period.

Installation

Terminal window
npm add @dirtroad/sediment

Using Rate Limit

Freemium.sol
// SPDX-License-Identifier: MIT
pragma 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