Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"src/reward-system/RewardManagerV1.1.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../interfaces/staking/IStakingStorage.sol";
import "../interfaces/staking/IStakingVault.sol";
import "../interfaces/reward/IRewardStrategy.sol";
import "../interfaces/reward/IRewardStrategyV1.1.sol";
import "./ClaimsJournal.sol";
import "./PoolManager.sol";
import "./FundingManager.sol";
import "../interfaces/reward/RewardErrors.sol";
/**
* @title RewardManager
* @author @Tudmotu & Gemini
* @notice A stateless orchestrator for all reward claims, inheriting funding logic.
* @dev This contract holds no state about users' claims. It reads from storage contracts,
* executes business logic from strategy contracts, and coordinates payments and state updates.
*/
contract RewardManagerV1_1 is
FundingManager,
Pausable,
RewardErrors,
ReentrancyGuard
{
using SafeERC20 for IERC20;
// --- Immutable contract dependencies ---
IStakingStorage public immutable stakingStorage;
ClaimsJournal public claimsJournal;
PoolManager public immutable poolManager;
mapping(uint256 poolId => mapping(uint256 strategyId => uint256))
public rewardAssignedToPool;
event RewardClaimed(
address indexed user,
bytes32 stakeId,
uint256 indexed poolId,
uint256 indexed strategyId,
uint256 rewardAmount,
uint16 claimDay
);
constructor(
address _admin,
address _manager,
address _multisig,
IStakingStorage _stakingStorage,
StrategiesRegistry _strategiesRegistry,
ClaimsJournal _claimsJournal,
PoolManager _poolManager
) FundingManager(_admin, _manager, _multisig, _strategiesRegistry) {
_grantRole(DEFAULT_ADMIN_ROLE, _admin);
_grantRole(MANAGER_ROLE, _manager);
stakingStorage = _stakingStorage;
claimsJournal = _claimsJournal;
poolManager = _poolManager;
}
function setClaimsJournal(
ClaimsJournal _newClaimsJournal
) external onlyRole(DEFAULT_ADMIN_ROLE) {
claimsJournal = _newClaimsJournal;
}
function assignRewardToPool(
uint256 _poolId,
uint256 _strategyId,
uint256 _amount
) external onlyRole(MANAGER_ROLE) {
require(
!poolManager.hasAnnounced(_poolId),
RewardErrors.PoolHasAlreadyBeenAnnounced()
);
rewardAssignedToPool[_poolId][_strategyId] = _amount;
}
function pause() external onlyRole(MANAGER_ROLE) {
_pause();
}
function unpause() external onlyRole(MANAGER_ROLE) {
_unpause();
}
function batchClaimReward(
bytes32[] calldata stakeIds,
uint256[] calldata poolIds,
uint256[] calldata strategyIds
) external {
require(
stakeIds.length == poolIds.length &&
stakeIds.length == strategyIds.length,
RewardErrors.InvalidInputArrays()
);
for (uint256 i = 0; i < stakeIds.length; i++) {
claimReward(stakeIds[i], poolIds[i], strategyIds[i]);
}
}
function batchCalculateReward(
bytes32[] calldata stakeIds,
uint256[] calldata poolIds,
uint256[] calldata strategyIds
) external view returns (uint256[] memory) {
uint256[] memory estimatedAmounts = new uint256[](stakeIds.length);
for (uint256 i = 0; i < stakeIds.length; i++) {
(estimatedAmounts[i]) = _calculateReward(
_getStakerFromId(stakeIds[i]),
stakeIds[i],
poolIds[i],
strategyIds[i]
);
}
return estimatedAmounts;
}
// ===================================================================
// USER CLAIM FUNCTIONS
// ===================================================================
function claimReward(
bytes32 stakeId,
uint256 poolId,
uint256 strategyId
) public nonReentrant whenNotPaused {
// --- 1. Data Fetching and Validation ---
(
address staker,
address strategyAddress,
uint256 layerId
) = _getDataAndValidate(stakeId, poolId, strategyId);
// --- 2. Reward Calculation ---
uint256 rewardAmount = _calculateReward(
staker,
stakeId,
poolId,
strategyId
);
require(rewardAmount > 0, RewardErrors.NoRewardToClaim());
// --- 3. Record Keeping ---
_recordClaim(staker, poolId, strategyId, layerId, stakeId);
// --- 4. Payout ---
_payout(staker, poolId, strategyId, strategyAddress, rewardAmount);
// --- 5. Emit Event ---
emit RewardClaimed(
staker,
stakeId,
poolId,
strategyId,
rewardAmount,
_getCurrentDay()
);
}
function calculateReward(
address staker,
bytes32 stakeId,
uint256 poolId,
uint256 strategyId
) external view returns (uint256) {
return _calculateReward(staker, stakeId, poolId, strategyId);
}
/**
* @notice This function is to be called by FrontEnd UI (mostly),
* in order to display list of Pool/stake pairs,
* and against each pair, the rewards the user can claim.
* Pools can have multiple layers, each layer can have multiple strategies.
* Some strategies on the same layer can be exclusive to each other.
* UI displays to the user a reward which can be claimed for each strategy.
* In case of exclusive strategies, UI displays two or more rewards,
* and when user clicks on the reward, FE disable other rewards,
* that can not be claimed after user confirmed the selection.
* Confirming selection will call `claimReward()` function for the
* chosen strategy.
*
* Use case example:
* For Pool 1 (cycle 1, 30 days) we have just 1 strategy:
* StandardRewardStrategy on layer 1:
* [1],
* [100], // amount of reward for pool
* [NORMAL]
*
* For Pool 4 (90 days) we have just 2 strategies on layer 0:
* FullStaking and Whitelisted:
* [4,5],
* [100,100], // Even if the rewards is the same, the conditions could be different
* [NORMAL, EXCLUSIVE]
*
* @param stakeId The ID of the stake.
* @param poolId The ID of the pool.
* @param layerId The ID of the layer.
* @return strategyIds An array of strategy IDs.
* @return amounts An array of amounts for each strategy.
* @return _exclusivity An array of exclusivity for each strategy.
*/
function calculateRewardsForPool(
bytes32 stakeId,
uint256 poolId,
uint256 layerId
)
external
view
returns (
uint256[] memory,
uint256[] memory,
PoolManager.StrategyExclusivity[] memory
)
{
(
uint256[] memory _strategyIds,
PoolManager.StrategyExclusivity[] memory _exclusivity
) = poolManager.getStrategiesFromLayer(poolId, layerId);
uint256[] memory amounts = new uint256[](_strategyIds.length);
address staker = _getStakerFromId(stakeId);
for (uint256 i = 0; i < _strategyIds.length; ++i) {
uint256 strategyId = _strategyIds[i];
(amounts[i]) = _calculateReward(
staker,
stakeId,
poolId,
strategyId
);
}
return (_strategyIds, amounts, _exclusivity);
}
function getCurrentDay() external view returns (uint16) {
return _getCurrentDay();
}
// ===================================================================
// V1.1 Functions
// ===================================================================
function batchClaimRewardWithSignature(
bytes32[] calldata stakeIds,
uint256[] calldata poolIds,
uint256[] calldata strategyIds,
bytes[] calldata signatures
) external {
require(
stakeIds.length == poolIds.length &&
stakeIds.length == strategyIds.length,
RewardErrors.InvalidInputArrays()
);
for (uint256 i = 0; i < stakeIds.length; i++) {
claimRewardWithSignature(
stakeIds[i],
poolIds[i],
strategyIds[i],
signatures[i]
);
}
}
function batchCalculateRewardWithSignature(
bytes32[] calldata stakeIds,
uint256[] calldata poolIds,
uint256[] calldata strategyIds,
bytes[] calldata signatures
) external view returns (uint256[] memory) {
uint256[] memory estimatedAmounts = new uint256[](stakeIds.length);
for (uint256 i = 0; i < stakeIds.length; i++) {
(estimatedAmounts[i]) = _calculateRewardWithSignature(
stakeIds[i],
poolIds[i],
strategyIds[i],
signatures[i]
);
}
return estimatedAmounts;
}
function claimRewardWithSignature(
bytes32 stakeId,
uint256 poolId,
uint256 strategyId,
bytes calldata signature
) public nonReentrant whenNotPaused {
// --- 1. Data Fetching and Validation ---
// we validate:
// - stake belongs to the caller
// - strategy exists
// - the stake doesn't violate the exclusivity rules
// - pool has started
// - (if pool is size dependent) pool is calculated
(
address staker,
address strategyAddress,
uint256 layerId
) = _getDataAndValidate(stakeId, poolId, strategyId);
// --- 2. Reward Calculation ---
// we validate (in the strategy contract):
// - signature is valid
// - stake has not been claimed yet
uint256 rewardAmount = _calculateRewardWithSignature(
stakeId,
poolId,
strategyId,
signature
);
require(rewardAmount > 0, RewardErrors.NoRewardToClaim());
// --- 3. Record Keeping ---
_recordClaim(staker, poolId, strategyId, layerId, stakeId);
// --- 4. Payout ---
_payout(staker, poolId, strategyId, strategyAddress, rewardAmount);
// --- 5. Emit Event ---
emit RewardClaimed(
staker,
stakeId,
poolId,
strategyId,
rewardAmount,
_getCurrentDay()
);
}
function calculateRewardWithSignature(
bytes32 stakeId,
uint256 poolId,
uint256 strategyId,
bytes calldata signature
) external view returns (uint256) {
return
_calculateRewardWithSignature(
stakeId,
poolId,
strategyId,
signature
);
}
/**
* @notice This function is to be called by FrontEnd UI (mostly),
* in order to display list of Pool/stake pairs,
* and against each pair, the rewards the user can claim.
* Pools can have multiple layers, each layer can have multiple strategies.
* Some strategies on the same layer can be exclusive to each other.
* UI displays to the user a reward which can be claimed for each strategy.
* In case of exclusive strategies, UI displays two or more rewards,
* and when user clicks on the reward, FE disable other rewards,
* that can not be claimed after user confirmed the selection.
* Confirming selection will call `claimReward()` function for the
* chosen strategy.
*
* Use case example:
* For Pool 1 (cycle 1, 30 days) we have just 1 strategy:
* StandardRewardStrategy on layer 1:
* [1],
* [100], // amount of reward for pool
* [NORMAL]
*
* For Pool 4 (90 days) we have just 2 strategies on layer 0:
* FullStaking and Whitelisted:
* [4,5],
* [100,100], // Even if the rewards is the same, the conditions could be different
* [NORMAL, EXCLUSIVE]
*
* @param stakeId The ID of the stake.
* @param poolId The ID of the pool.
* @param layerId The ID of the layer.
* @return strategyIds An array of strategy IDs.
* @return amounts An array of amounts for each strategy.
* @return _exclusivity An array of exclusivity for each strategy.
*/
function calculateRewardsWithSignatureForPool(
bytes32 stakeId,
uint256 poolId,
uint256 layerId,
bytes calldata signature
)
external
view
returns (
uint256[] memory,
uint256[] memory,
PoolManager.StrategyExclusivity[] memory
)
{
(
uint256[] memory _strategyIds,
PoolManager.StrategyExclusivity[] memory _exclusivity
) = poolManager.getStrategiesFromLayer(poolId, layerId);
uint256[] memory amounts = new uint256[](_strategyIds.length);
for (uint256 i = 0; i < _strategyIds.length; ++i) {
uint256 strategyId = _strategyIds[i];
(amounts[i]) = _calculateRewardWithSignature(
stakeId,
poolId,
strategyId,
signature
);
}
return (_strategyIds, amounts, _exclusivity);
}
function getPayloadForTesting(
bytes32 stakeId,
uint256 poolId,
uint256 strategyId
) external view returns (bytes memory) {
IStakingStorage.Stake memory stake = stakingStorage.getStake(stakeId);
PoolManager.Pool memory pool = poolManager.getPool(poolId);
uint16 lastClaimDay = claimsJournal.getLastClaimDay(
stakeId,
poolId,
strategyId
);
IRewardStrategyV1_1.PoolData memory poolData = IRewardStrategyV1_1
.PoolData({
weight: pool.totalPoolWeight > 0
? pool.totalPoolWeight
: poolManager.poolLiveWeight(poolId),
reward: rewardAssignedToPool[poolId][strategyId],
startDay: pool.startDay,
endDay: pool.endDay
});
return abi.encode(stakeId, stake, poolData, lastClaimDay);
}
/**
* @notice We calculate the reward for a stake with a signature.
*
* @dev We get the strategy contract & last claim day,
* @dev pack the data, and pass it to the strategy contract
* @dev to receive the calculated reward.
*
* @param stakeId The ID of the stake.
* @param poolId The ID of the pool.
* @param strategyId The ID of the strategy.
* @param signature The signature of the stake.
* @return estimatedAmount The estimated amount of reward.
*/
function _calculateRewardWithSignature(
bytes32 stakeId,
uint256 poolId,
uint256 strategyId,
bytes calldata signature
) internal view returns (uint256 estimatedAmount) {
IRewardStrategyV1_1 strategyContract = IRewardStrategyV1_1(
strategiesRegistry.getStrategyAddress(strategyId)
);
uint16 lastClaimDay = claimsJournal.getLastClaimDay(
stakeId,
poolId,
strategyId
);
bytes memory payload = _encodeCalculationData(
stakeId,
poolId,
strategyId,
lastClaimDay
);
estimatedAmount = strategyContract.calculateReward(payload, signature);
}
function _encodeCalculationData(
bytes32 stakeId,
uint256 poolId,
uint256 strategyId,
uint16 lastClaimDay
) internal view returns (bytes memory) {
IStakingStorage.Stake memory stake = stakingStorage.getStake(stakeId);
PoolManager.Pool memory pool = poolManager.getPool(poolId);
IRewardStrategyV1_1.PoolData memory poolData = IRewardStrategyV1_1
.PoolData({
weight: pool.totalPoolWeight > 0
? pool.totalPoolWeight
: poolManager.poolLiveWeight(poolId),
reward: rewardAssignedToPool[poolId][strategyId],
startDay: pool.startDay,
endDay: pool.endDay
});
return abi.encode(stakeId, stake, poolData, lastClaimDay);
}
// ===================================================================
// Internal Functions
// ===================================================================
/**
* @notice We extract and return data for further use,
* @notice but before that, we validate that stake:
* - belongs to the caller
* - strategy exists
* - the stake doesn't violate the exclusivity rules
* - pool has started
* - (if pool size dependent) pool is calculated
* @param stakeId The ID of the stake.
* @param poolId The ID of the pool.
* @param strategyId The ID of the strategy.
* @return staker
* @return strategyAddress
* @return layerId
*/
function _getDataAndValidate(
bytes32 stakeId,
uint256 poolId,
uint256 strategyId
)
internal
view
returns (address staker, address strategyAddress, uint256 layerId)
{
staker = _getStakerFromId(stakeId);
require(
staker == _msgSender(),
RewardErrors.NotStakeOwner(_msgSender(), staker)
);
strategyAddress = strategiesRegistry.getStrategyAddress(strategyId);
require(
strategyAddress != address(0),
RewardErrors.StrategyNotExist(strategyId)
);
layerId = poolManager.getStrategyLayer(poolId, strategyId);
_validateExclusivity(stakeId, poolId, layerId, strategyId);
IRewardStrategy.StrategyType strategyType = IRewardStrategy(
strategyAddress
).getStrategyType();
if (strategyType == IRewardStrategy.StrategyType.POOL_SIZE_DEPENDENT) {
require(
poolManager.isPoolCalculated(poolId),
RewardErrors.PoolNotInitializedOrCalculated(poolId)
);
} else {
require(
poolManager.hasStarted(poolId),
RewardErrors.PoolNotStarted(poolId)
);
}
}
/**
* @notice We validate that the stake doesn't violate the exclusivity rules:
* - if the strategy is exclusive, the stake doesn't have a claim yet
* - if the strategy is semi exclusive, the stake doesn't have a semi exclusive claim yet
* - if the strategy is normal, the stake doesn't have an exclusive or semi exclusive claim yet
* @dev one stake can have multiple stakes, so we validate each stakeId
* @param stakeId The ID of the stake.
* @param poolId The ID of the pool.
* @param layerId The ID of the layer.
* @param strategyId The ID of the strategy.
*/
function _validateExclusivity(
bytes32 stakeId,
uint256 poolId,
uint256 layerId,
uint256 strategyId
) internal view {
PoolManager.StrategyExclusivity strategyType = poolManager
.getStrategyExclusivity(poolId, layerId, strategyId);
ClaimsJournal.LayerClaimType layerClaimState = claimsJournal
.getLayerClaimState(_getStakerFromId(stakeId), poolId, layerId);
if (strategyType == PoolManager.StrategyExclusivity.EXCLUSIVE) {
require(
layerClaimState == ClaimsJournal.LayerClaimType.NORMAL,
RewardErrors.LayerAlreadyHasClaim(
layerId,
claimsJournal.getLastClaimDay(stakeId, poolId, strategyId)
)
);
} else {
require(
layerClaimState != ClaimsJournal.LayerClaimType.EXCLUSIVE,
RewardErrors.LayerAlreadyHasExclusiveClaim(
layerId,
claimsJournal.getLastClaimDay(stakeId, poolId, strategyId)
)
);
if (
strategyType == PoolManager.StrategyExclusivity.SEMI_EXCLUSIVE
) {
require(
layerClaimState !=
ClaimsJournal.LayerClaimType.SEMI_EXCLUSIVE,
RewardErrors.LayerAlreadyHasSemiExclusiveClaim(
layerId,
claimsJournal.getLastClaimDay(
stakeId,
poolId,
strategyId
)
)
);
}
}
}
function _calculateReward(
address staker,
bytes32 stakeId,
uint256 poolId,
uint256 strategyId
) internal view returns (uint256 estimatedAmount) {
IRewardStrategy strategyContract = IRewardStrategy(
strategiesRegistry.getStrategyAddress(strategyId)
);
IStakingStorage.Stake memory stake = stakingStorage.getStake(stakeId);
PoolManager.Pool memory pool = poolManager.getPool(poolId);
uint16 lastClaimDay = claimsJournal.getLastClaimDay(
stakeId,
poolId,
strategyId
);
uint256 liveWeight = poolManager.poolLiveWeight(poolId);
if (liveWeight == 0 && pool.totalPoolWeight == 0) return 0;
uint256 poolWeight = pool.totalPoolWeight > 0
? pool.totalPoolWeight
: liveWeight;
estimatedAmount = strategyContract.calculateReward(
staker,
stake,
poolWeight,
rewardAssignedToPool[poolId][strategyId],
pool.startDay,
pool.endDay,
lastClaimDay
);
}
function _payout(
address staker,
uint256 poolId,
uint256 strategyId,
address strategyAddress,
uint256 rewardAmount
) internal {
_decreaseStrategyBalance(poolId, strategyId, rewardAmount);
address rewardToken = IRewardStrategy(strategyAddress).getRewardToken();
IERC20(rewardToken).safeTransfer(staker, rewardAmount);
}
function _recordClaim(
address staker,
uint256 poolId,
uint256 strategyId,
uint256 layerId,
bytes32 stakeId
) internal {
PoolManager.StrategyExclusivity strategyType = poolManager
.getStrategyExclusivity(poolId, layerId, strategyId);
ClaimsJournal.LayerClaimType claimType;
if (strategyType == PoolManager.StrategyExclusivity.NORMAL) {
claimType = ClaimsJournal.LayerClaimType.NORMAL;
} else if (
strategyType == PoolManager.StrategyExclusivity.SEMI_EXCLUSIVE
) {
claimType = ClaimsJournal.LayerClaimType.SEMI_EXCLUSIVE;
} else {
claimType = ClaimsJournal.LayerClaimType.EXCLUSIVE;
}
claimsJournal.recordClaim(
staker,
poolId,
layerId,
strategyId,
stakeId,
claimType,
_getCurrentDay()
);
}
function _getStakerFromId(bytes32 stakeId) internal pure returns (address) {
return address(uint160(uint256(stakeId) >> 96));
}
function _getCurrentDay() internal view returns (uint16) {
return uint16(block.timestamp / 1 days);
}
}
"
},
"node_modules/@openzeppelin/contracts/access/AccessControl.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
"
},
"node_modules/@openzeppelin/contracts/utils/Pausable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
"
},
"node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
"
},
"node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
},
"node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
"
},
"src/interfaces/staking/IStakingStorage.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
/**
* @title IStakingStorage Interface
* @notice Unified interface for consolidated staking storage
*/
interface IStakingStorage {
enum Sign {
POSITIVE,
NEGATIVE
}
struct Stake {
uint128 amount;
uint16 stakeDay;
uint16 unstakeDay;
uint16 daysLock;
uint16 flags; // 2 bytes - pack multiple booleans
}
struct StakerInfo {
uint128 totalStaked;
uint128 totalRewarded; // TODO: remove?
uint128 totalClaimed; // TODO: remove?
uint16 stakesCounter;
uint16 activeStakesNumber;
uint16 lastCheckpointDay;
}
struct DailySnapshot {
uint128 totalStakedAmount;
uint16 totalStakesCount;
}
// Events
event Staked(
address indexed staker,
bytes32 indexed stakeId,
uint128 amount,
uint16 indexed stakeDay,
uint16 daysLock,
uint16 flags
);
event Unstaked(
address indexed staker,
bytes32 indexed stakeId,
uint16 indexed unstakeDay,
uint128 amount
);
event CheckpointCreated(
address indexed staker,
uint16 indexed day,
uint128 balance,
uint16 stakesCount
);
// Stake Management
function createStake(
address staker,
uint128 amount,
uint16 daysLock,
uint16 flags
) external returns (bytes32 stakeId);
function removeStake(address staker, bytes32 stakeId) external;
function getStake(bytes32 stakeId) external view returns (Stake memory);
function isActiveStake(bytes32 stakeId) external view returns (bool);
// Staker Management
function getStakerInfo(
address staker
) external view returns (StakerInfo memory);
function getStakerBalance(address staker) external view returns (uint128);
function getStakerBalanceAt(
address staker,
uint16 targetDay
) external view returns (uint128);
function batchGetStakerBalances(
address[] calldata stakers,
uint16 targetDay
) external view returns (uint128[] memory);
// Global Statistics
function getDailySnapshot(
uint16 day
) external view returns (DailySnapshot memory);
function getCurrentTotalStaked() external view returns (uint128);
// Pagination
function getStakersPaginated(
uint256 offset,
uint256 limit
) external view returns (address[] memory);
function getTotalStakersCount() external view returns (uint256);
function getStakerStakeIds(
address staker
) external view returns (bytes32[] memory);
}
"
},
"src/interfaces/staking/IStakingVault.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
interface IStakingVault {
// Core functions
function stake(uint128 amount, uint16 daysLock) external returns (bytes32 stakeId);
function unstake(bytes32 stakeId) external;
/**
* @notice Stake tokens from a claim with a timelock period in days
* @param staker The address of the staker
* @param amount The amount to stake
* @param daysLock The timelock period in days
* @return stakeId The ID of the created stake
*/
function stakeFromClaim(address staker, uint128 amount, uint16 daysLock) external returns (bytes32 stakeId);
}
"
},
"src/interfaces/reward/IRewardStrategy.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IStakingStorage} from "../staking/IStakingStorage.sol";
interface IRewardStrategy {
enum StrategyType {
POOL_SIZE_INDEPENDENT, // Can calculate anytime (APR-style)
POOL_SIZE_DEPENDENT // Requires BE calculation after pool ends - how much were staked during the pool
}
// --- CONFIGURATION VIEW FUNCTIONS ---
function getName() external view returns (string memory);
function getRewardToken() external view returns (address);
function getStrategyType() external view returns (StrategyType);
/**
* @notice Calculates reward for POOL_SIZE_DEPENDENT strategies.
*/
function calculateReward(
address user,
IStakingStorage.Stake calldata stake,
uint256 totalPoolWeight,
uint256 totalRewardAmount,
uint16 poolStartDay,
uint16 poolEndDay,
uint16 lastClaimDay
) external view returns (uint256);
}
"
},
"src/interfaces/reward/IRewardStrategyV1.1.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IStakingStorage} from "../staking/IStakingStorage.sol";
interface IRewardStrategyV1_1 {
enum StrategyType {
POOL_SIZE_INDEPENDENT, // Can calculate anytime (APR-style)
POOL_SIZE_DEPENDENT // Requires BE calculation after pool ends - how much were staked during the pool
}
struct PoolData {
uint256 weight;
uint256 reward;
uint16 startDay;
uint16 endDay;
}
// --- CONFIGURATION VIEW FUNCTIONS ---
function getName() external view returns (string memory);
function getRewardToken() external view returns (address);
function getStrategyType() external view returns (StrategyType);
function calculateReward(
bytes calldata payload,
bytes calldata signature
) external view returns (uint256);
function calculateReward(
address staker,
IStakingStorage.Stake calldata stake,
uint256 totalPoolWeight,
uint256 totalRewardAmount,
uint16 poolStartDay,
uint16 poolEndDay,
uint16 lastClaimDay
) external view returns (uint256);
}
"
},
"src/reward-system/ClaimsJournal.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "../interfaces/reward/RewardErrors.sol";
/**
* @title ClaimsJournal
* @notice Stores all user claim history for both DIRECT and SHARED_POOL rewards.
* @dev This contract is the single source of truth for the RewardManager to determine
* if a user is eligible for a future claim based on their past actions.
* It knows nothing about reward logic; it is a simple, append-only ledger.
*/
contract ClaimsJournal is AccessControl, RewardErrors {
bytes32 constant REWARD_MANAGER_ROLE = keccak256("REWARD_MANAGER_ROLE");
enum LayerClaimType {
NORMAL,
EXCLUSIVE,
SEMI_EXCLUSIVE
}
event LayerStateUpdated(
address indexed user,
uint256 indexed poolId,
uint256 indexed layerId,
LayerClaimType newStateType
);
event ClaimRecorded(
bytes32 indexed stakeId,
uint256 indexed strategyId,
uint256 claimDay
);
// Tracks the state of a user's claim on a specific layer of a pool.
// User Address => Pool ID => Layer ID => Claim Type
mapping(address userAddress => mapping(uint256 poolId => mapping(uint256 layerId => LayerClaimType)))
public layerClaimState;
// Tracks the last day a reward was claimed for a specific stake and a DIRECT strategy.
// Stake ID => Strategy ID => Day
mapping(bytes32 stakeId => mapping(uint256 poolId => mapping(uint256 strategyId => uint16 claimDay)))
public claimDates;
constructor(address _admin) {
_grantRole(DEFAULT_ADMIN_ROLE, _admin);
}
/**
* @notice Records a claim, updating the state for the given user, pool, and strategy.
* @dev To be called ONLY by the RewardManager after a successful reward payment.
*/
function recordClaim(
address _user,
uint256 _poolId,
uint256 _layerId,
uint256 _strategyId,
bytes32 _stakeId,
LayerClaimType _claimType,
uint16 _claimDay
) external onlyRole(REWARD_MANAGER_ROLE) {
LayerClaimType currentLayerState = layerClaimState[_user][_poolId][
_layerId
];
if (_claimType == LayerClaimType.EXCLUSIVE) {
require(
currentLayerState == LayerClaimType.NORMAL,
LayerAlreadyHasClaim(_layerId, _claimDay)
);
} else {
// NORMAL or SEMI_EXCLUSIVE
require(
currentLayerState != LayerClaimType.EXCLUSIVE,
LayerAlreadyHasExclusiveClaim(_layerId, _claimDay)
);
if (_claimType == LayerClaimType.SEMI_EXCLUSIVE) {
require(
currentLayerState != LayerClaimType.SEMI_EXCLUSIVE,
LayerAlreadyHasSemiExclusiveClaim(_layerId, _claimDay)
);
}
}
// if current state is absent or normal,
// update it to the new claim type (normal, semi-exclusive or exclusive)
if (currentLayerState == LayerClaimType.NORMAL) {
layerClaimState[_user][_poolId][_layerId] = _claimType; // TODO BUG: Should be stakeId, not user
emit LayerStateUpdated(_user, _poolId, _layerId, _claimType);
}
// if current state is exclusive, update it to the max-level
// this will override the normal or semi-exclusive claim
// if it is already exclusive, it is redundant but safe to rewrite
// but cheaper in terms of gas (no extra checks on all updates)
if (_claimType == LayerClaimType.EXCLUSIVE) {
layerClaimState[_user][_poolId][_layerId] = _claimType;
emit LayerStateUpdated(_user, _poolId, _layerId, _claimType);
}
claimDates[_stakeId][_poolId][_strategyId] = _claimDay;
emit ClaimRecorded(_stakeId, _strategyId, _claimDay);
}
// ===================================================================
// VIEW FUNCTIONS
// ===================================================================
function getLayerClaimState(
address _user,
uint256 _poolId,
uint256 _layerId
) external view returns (LayerClaimType) {
return layerClaimState[_user][_poolId][_layerId];
}
function getLastClaimDay(
bytes32 _stakeId,
uint256 _poolId,
uint256 _strategyId
) external view returns (uint16) {
return claimDates[_stakeId][_poolId][_strategyId];
}
}
"
},
"src/reward-system/PoolManager.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
contract PoolManager is AccessControl {
using EnumerableSet for EnumerableSet.UintSet;
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE");
enum StrategyExclusivity {
NORMAL, // can be combined with any other
EXCLUSIVE, // excludes all other on the layer
SEMI_EXCLUSIVE // excludes only other SEMI_EXCLUSIVE and EXCLUSIVE
}
struct Pool {
bool hasAnnounced; // if false it is possible to setup pools in the past
bool toSkipInUI;
uint16 startDay;
uint16 endDay;
uint256 totalPoolWeight;
uint256 parentPoolId;
}
uint256 public nextPoolId;
mapping(uint256 poolId => Pool) public pools;
// poolLiveWeight is used to calculate the preliminary rewards for the pool
mapping(uint256 poolId => uint256) public poolLiveWeight;
mapping(uint256 poolId => EnumerableSet.UintSet) internal _poolLayers;
mapping(uint256 poolId => EnumerableSet.UintSet) internal _poolStrategies;
mapping(uint256 poolId => mapping(uint256 layer => EnumerableSet.UintSet))
internal _poolLayerStrategies;
mapping(uint256 poolId => mapping(uint256 layer => mapping(uint256 strategyId => StrategyExclusivity)))
public exclusivity;
mapping(uint256 poolId => mapping(uint256 layer => EnumerableSet.UintSet))
private _ignoredStrategies; // ignored strategies for UI
// Cache for quick search of strategy layer
mapping(uint256 poolId => mapping(uint256 strategyId => uint256))
public strategyLayer;
mapping(uint256 poolId => mapping(uint256 layer => bool))
public hasExclusiveStrategies;
event PoolUpserted(
uint256 indexed poolId,
uint16 startDay,
uint16 endDay,
uint256 totalPoolWeight,
uint256 indexed parentPoolId
);
event StrategyAddedToLayer(
uint256 poolId,
uint256 layer,
uint256 strategyId
);
event AnnouncePool(uint256 indexed poolId, uint16 startDay, uint16 endDay);
event StrategyRemovedFromLayer(
uint256 indexed poolId,
uint256 layer,
uint256 strategyId
);
error PoolNotEnded();
error PoolAlreadyCalculated();
error InvalidDates();
error ParentPoolIsSelf();
error PoolDoesNotExist(uint256 poolId);
error PoolAlreadyAnnounced();
constructor(address admin, address manager, address con
Submitted on: 2025-10-30 12:08:19
Comments
Log in to comment.
No comments yet.