Verified contractExactApache-2.0
StakingWithUnbonding
Address0x4be8be2b72638f87c76f738cc1341665ed2f5876
- Balance
0.12384 ETH
- Transactions
1,372
- Compiler
solc 0.8.28
- Same code
1 more contract
Details
- Compiler
- solc 0.8.28+commit.7893614a
- Language
- solidity
- Optimization
- Yes, 2,000 runs
- EVM version
- cancun
- Via IR
- yes
- License
- Apache-2.0
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 23,163,207
- Creation transaction
- 0x46e61f0fc5…2e4f79acb4
19 files
- contracts/StakingWithUnbonding.solmain15.66 KB
- contracts/interfaces/IStakingBase.sol2.55 KB
- contracts/interfaces/IStakingWithUnbonding.sol3.38 KB
- contracts/interfaces/ITypes.sol234 B
- contracts/lib/FeeFunctions.sol403 B
- contracts/lib/StakingBase.sol13.13 KB
- contracts/lib/StakingErrors.sol2.01 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol10.08 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol2.09 KB
- lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol5.08 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/Hashes.sol1.03 KB
- lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol24.34 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
contracts/StakingWithUnbonding.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.28;
import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuardTransient } from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { ITypes } from "contracts/interfaces/ITypes.sol";
import { IStakingWithUnbonding, UnbondingStaker, UnbondingStakingInitParams, StakingSettings } from "contracts/interfaces/IStakingWithUnbonding.sol";
import { FeeFunctions } from "contracts/lib/FeeFunctions.sol";
import { StakingErrors } from "contracts/lib/StakingErrors.sol";
import { StakingBase } from "contracts/lib/StakingBase.sol";
contract StakingWithUnbonding is IStakingWithUnbonding, StakingBase {
using SafeERC20 for IERC20;
/// @dev APY represented as basis points (10000 = 100%).
uint64 public immutable APY_PERCENTAGE;
/// @dev Maximum stake duration.
uint64 public immutable MAX_STAKE_DURATION;
/// @dev Max unbonding period for the staker.
uint64 public immutable MAX_UNBONDING_PERIOD = 365 days * 5; // ±5 years
/// @dev Maps staker address to `UnbondingStaker` struct.
mapping(address => UnbondingStaker) public stakers;
/// @dev Unbonding period for the staker.
uint64 public unbondingPeriod;
constructor(
UnbondingStakingInitParams memory params,
address owner_
)
StakingBase(
BaseParams({
merkleRoot: params.merkleRoot,
whitelistStatus: params.whitelistStatus,
stakingToken: params.stakingToken,
poolMaxCap: params.poolMaxCap,
tierUpperBound: params.tierUpperBound,
tierLowerBound: params.tierLowerBound,
startStakingDate: params.startStakingDate,
endStakingDate: params.endStakingDate,
feeType: params.feeType,
fee: params.fee,
feeCollector: params.feeCollector,
feeFunctions: params.feeFunctions,
owner: owner_
})
)
{
if (params.maxStakeDuration == 0)
revert StakingErrors.InvalidMaxStakeDuration();
if (params.unbondingPeriod > MAX_UNBONDING_PERIOD)
revert StakingErrors.InvalidUnbondingPeriod();
unbondingPeriod = params.unbondingPeriod;
MAX_STAKE_DURATION = params.maxStakeDuration;
APY_PERCENTAGE = params.apyPercentage;
}
/// @notice Stake ERC20 Tokens.
/// @param _amount: Amount to stake.
function stake(uint256 _amount) external payable nonReentrant {
if (whitelistStatus != ITypes.WhitelistStatus.Disabled)
revert StakingErrors.WhitelistEnabled();
_stake(_amount, msg.sender);
}
/// @notice Stake ERC20 Tokens to a specific receiver.
/// @param _amount: Amount to stake.
/// @param _receiver: Address to receive the staked tokens.
function stake(
uint256 _amount,
address _receiver
) external payable nonReentrant {
if (_receiver == address(0)) revert StakingErrors.InvalidAddress();
// Revert if Merkle whitelist is enabled (should use merkle proof function)
if (whitelistStatus == ITypes.WhitelistStatus.Merkle)
revert StakingErrors.WhitelistEnabled();
// Check trusted distributor requirements
if (
(whitelistStatus == ITypes.WhitelistStatus.TrustedDistributors ||
whitelistStatus ==
ITypes.WhitelistStatus.MerkleAndTrustedDistributors) &&
!trustedDistributors[msg.sender]
) revert StakingErrors.OnlyTrustedDistributor();
_stake(_amount, _receiver);
}
/// @notice Stake ERC20 Tokens to a whitelisted receiver with Merkle proof.
/// @param _amount: Amount to stake.
/// @param _receiver: Address to receive the staked tokens.
/// @param merkleProof: Merkle proof for the receiver.
function stake(
uint256 _amount,
address _receiver,
bytes32[] calldata merkleProof
) external payable nonReentrant {
bytes32 node = keccak256(abi.encodePacked(_receiver));
if (!MerkleProof.verifyCalldata(merkleProof, merkleRoot, node))
revert StakingErrors.InvalidMerkleProof();
_stake(_amount, _receiver);
}
/// @notice Initiate unbonding process for staked tokens.
/// @param _amount: Amount to unbond.
function initiateUnbonding(uint256 _amount) external nonReentrant {
UnbondingStaker storage stakerData = stakers[msg.sender];
if (_amount == 0) {
revert StakingErrors.ZeroAmount();
}
if (stakerData.amountStaked < _amount) {
revert StakingErrors.WithdrawingMoreThanStaked();
}
// Check if remaining amount meets the tier lower bound
if (
stakerData.amountStaked - _amount > 0 &&
stakerData.amountStaked - _amount < TIER_LOWER_BOUND
) {
revert StakingErrors.RemainingAmountBelowLowerBound();
}
// Update rewards before unbonding
_updateUnclaimedRewardsForStaker(msg.sender);
// Initialize or add to unbonding
stakerData.unbondingAmount += _amount;
stakerData.unbondingTimestamp = uint128(block.timestamp);
// Update staked amount
stakerData.amountStaked -= _amount;
emit UnbondingInitiated(msg.sender, _amount);
}
/// @notice Complete unbonding process and withdraw tokens after unbonding period.
function completeUnbonding() external payable nonReentrant {
UnbondingStaker storage stakerData = stakers[msg.sender];
if (stakerData.unbondingAmount == 0) {
revert StakingErrors.NoTokensUnbonding();
}
uint256 feeAmount;
// appy gas fee if enabled for Withdraw function
if (
_hasFeeEnabled(FeeFunctions.FEE_ON_WITHDRAW) &&
FEE_TYPE == ITypes.FeeType.Gas
) {
if (msg.value != FEE) revert StakingErrors.InsufficientFee();
feeAmount = FEE; // Track gas fee amount
}
// Only check unbonding period if it's not set to zero (immediate withdrawals)
if (
unbondingPeriod > 0 &&
block.timestamp < stakerData.unbondingTimestamp + unbondingPeriod
) {
revert StakingErrors.UnbondingPeriodNotCompleted();
}
uint256 amountToWithdraw = stakerData.unbondingAmount;
stakerData.unbondingAmount = 0;
stakerData.unbondingTimestamp = 0;
stakingTokenBalance -= amountToWithdraw;
// If no more tokens staked and no unclaimed rewards, remove from stakers array
if (stakerData.amountStaked == 0 && stakerData.unclaimedRewards == 0) {
_removeStaker(msg.sender);
}
// Apply token fee if enabled for Stake function
if (
_hasFeeEnabled(FeeFunctions.FEE_ON_WITHDRAW) &&
FEE_TYPE == ITypes.FeeType.DistributionToken &&
FEE > 0
) {
feeAmount = (amountToWithdraw * FEE) / BASIS_POINTS;
amountToWithdraw -= feeAmount;
numTokenReservedForFee += feeAmount;
}
IERC20(STAKING_TOKEN).safeTransfer(msg.sender, amountToWithdraw);
emit TokensWithdrawn(msg.sender, amountToWithdraw, feeAmount);
}
/// @notice Claim accumulated rewards.
function claimRewards() external payable nonReentrant {
_claimRewards();
}
/// @notice Claim a specific amount of accumulated rewards.
/// @param _amount Amount of rewards to claim.
function claimRewards(uint256 _amount) external payable nonReentrant {
_claimRewards(_amount);
}
/// @notice Returns the information about a staker's stake.
/// @param _staker: Address of the staker.
function getStakeInfo(
address _staker
)
external
view
returns (
uint256 _tokensStaked,
uint256 _rewards,
uint256 _unbondingAmount,
uint256 _timeUntilUnbondingComplete,
uint128 _firstStakeTime
)
{
UnbondingStaker memory stakerData = stakers[_staker];
_tokensStaked = stakerData.amountStaked;
_rewards = _availableRewards(_staker);
_unbondingAmount = stakerData.unbondingAmount;
_firstStakeTime = stakerData.timeOfFirstStake;
if (
stakerData.unbondingTimestamp > 0 &&
unbondingPeriod > 0 &&
block.timestamp < stakerData.unbondingTimestamp + unbondingPeriod
) {
_timeUntilUnbondingComplete =
(stakerData.unbondingTimestamp + unbondingPeriod) -
block.timestamp;
} else {
_timeUntilUnbondingComplete = 0;
}
}
/**
* @notice Updates the unbonding period
* @param _newUnbondingPeriod The new unbonding period in seconds
* @dev Can only be called by the owner
* @dev Setting to 0 will allow immediate withdrawals with no unbonding period
*/
function setUnbondingPeriod(
uint64 _newUnbondingPeriod
) external override onlyOwner {
// Validate unbonding period
if (_newUnbondingPeriod > MAX_UNBONDING_PERIOD) {
revert StakingErrors.InvalidUnbondingPeriod();
}
uint64 oldUnbondingPeriod = unbondingPeriod;
unbondingPeriod = _newUnbondingPeriod;
emit UnbondingPeriodUpdated(oldUnbondingPeriod, _newUnbondingPeriod);
}
/// @notice Returns the APY in basis points.
function getAPY() external view returns (uint64) {
return APY_PERCENTAGE;
}
/// @notice Staking contract configuration helper for UI calls
/// @return StakingSettings: Staking contract settings
function stakingSettings() external view returns (StakingSettings memory) {
return
StakingSettings({
merkleRoot: merkleRoot,
whitelistStatus: whitelistStatus,
stakingToken: STAKING_TOKEN,
poolMaxCap: poolMaxCap,
maxStakeDuration: MAX_STAKE_DURATION,
apyPercentage: APY_PERCENTAGE,
tierUpperBound: TIER_UPPER_BOUND,
tierLowerBound: TIER_LOWER_BOUND,
startStakingDate: START_STAKING_DATE,
endStakingDate: END_STAKING_DATE,
unbondingPeriod: unbondingPeriod,
feeType: FEE_TYPE,
fee: FEE,
feeCollector: feeCollector,
owner: owner(),
feeFunctions: FEES_FUNCTIONS,
basisPoints: BASIS_POINTS
});
}
/// @dev Check if an address is in the stakers list.
function isInStakerList(address _staker) external view returns (bool) {
return stakers[_staker].stakersArrayIndex != 0;
}
/// @dev Get the index of a staker in the stakersArray.
function getAddressIndex(address _staker) external view returns (uint64) {
return stakers[_staker].stakersArrayIndex;
}
/// @notice Stake ERC20 Tokens.
/// @param _amount: Amount to stake.
function _stake(uint256 _amount, address _receiver) internal {
if (_amount == 0) revert StakingErrors.StakingZeroTokens();
if (block.timestamp < START_STAKING_DATE)
revert StakingErrors.StakingNotStarted();
if (block.timestamp > END_STAKING_DATE)
revert StakingErrors.StakingEnded();
UnbondingStaker storage stakerData = stakers[_receiver];
if (_amount + stakerData.amountStaked > TIER_UPPER_BOUND)
revert StakingErrors.StakingAmountExceedsUpperBound();
if (_amount + stakerData.amountStaked < TIER_LOWER_BOUND)
revert StakingErrors.StakingAmountBelowLowerBound();
uint256 feeAmount;
if (
_hasFeeEnabled(FeeFunctions.FEE_ON_STAKE) &&
FEE_TYPE == ITypes.FeeType.Gas
) {
if (msg.value != FEE) revert StakingErrors.InsufficientFee();
feeAmount = FEE; // Track gas fee amount
}
uint128 currentTime = uint128(block.timestamp);
// Update unclaimed rewards if already staking
if (stakerData.amountStaked > 0) {
_updateUnclaimedRewardsForStaker(_receiver);
} else {
// First time staking
_addStaker(_receiver);
stakerData.timeOfFirstStake = currentTime;
stakerData.timeOfLastUpdate = currentTime;
stakerData.unclaimedRewards = 0;
}
// Transfer tokens
IERC20(STAKING_TOKEN).safeTransferFrom(
msg.sender,
address(this),
_amount
);
// Apply token fee if enabled for Stake function
if (
_hasFeeEnabled(FeeFunctions.FEE_ON_STAKE) &&
FEE_TYPE == ITypes.FeeType.DistributionToken &&
FEE > 0
) {
feeAmount = (_amount * FEE) / BASIS_POINTS;
_amount -= feeAmount;
numTokenReservedForFee += feeAmount;
}
uint256 expectedPoolAmount = stakingTokenBalance + _amount;
if (expectedPoolAmount > poolMaxCap)
revert StakingErrors.PoolMaxCapExceeded();
stakerData.amountStaked += _amount;
stakingTokenBalance += _amount;
emit TokensStaked(_receiver, _amount, feeAmount);
}
/// @dev Logic for claiming rewards.
function _claimRewards() internal {
_claimRewards(0); // 0 means claim all available rewards
}
/// @dev Logic for claiming rewards with a specific amount.
/// @param _amount Amount to claim. If 0, claims all available rewards.
function _claimRewards(uint256 _amount) internal {
uint256 totalAvailableRewards = _availableRewards(msg.sender);
if (totalAvailableRewards == 0) {
revert StakingErrors.NoRewards();
}
uint256 rewards;
if (_amount == 0) {
// Claim all available rewards
rewards = totalAvailableRewards;
} else {
// Claim specific amount
if (_amount > totalAvailableRewards) {
revert StakingErrors.InsufficientRewards();
}
rewards = _amount;
}
if (rewards > rewardsAvailable) {
revert StakingErrors.InsufficientRewardsAvailable();
}
uint256 feeAmount;
uint256 transferAmount = rewards;
// Apply fee if enabled for Claim function
if (_hasFeeEnabled(FeeFunctions.FEE_ON_CLAIM)) {
// Fee validation
if (FEE_TYPE == ITypes.FeeType.Gas) {
if (msg.value != FEE) revert StakingErrors.InsufficientFee();
feeAmount = FEE; // Track gas fee amount
}
if (FEE_TYPE == ITypes.FeeType.DistributionToken && FEE > 0) {
feeAmount = (rewards * FEE) / BASIS_POINTS;
transferAmount = rewards - feeAmount;
numTokenReservedForFee += feeAmount;
}
}
UnbondingStaker storage stakerData = stakers[msg.sender];
stakerData.timeOfLastUpdate = uint128(block.timestamp);
// Update unclaimed rewards
stakerData.unclaimedRewards = totalAvailableRewards - rewards;
// Transfer rewards
rewardsAvailable -= rewards;
IERC20(STAKING_TOKEN).safeTransfer(msg.sender, transferAmount);
emit RewardsClaimed(msg.sender, transferAmount, feeAmount);
}
/// @dev Update unclaimed rewards for a user. Called for every state change for a user.
function _updateUnclaimedRewardsForStaker(address _staker) internal {
uint256 rewards = _calculateRewards(_staker);
stakers[_staker].unclaimedRewards += rewards;
stakers[_staker].timeOfLastUpdate = uint128(block.timestamp);
}
/// @dev Remove staker from stakersArray.
function _removeStaker(address _staker) internal {
uint64 index = stakers[_staker].stakersArrayIndex - 1; // - 1 because 0 means out of the array
address lastStaker = stakersArray[stakersArray.length - 1];
stakersArray[index] = lastStaker;
stakersArray.pop();
stakers[lastStaker].stakersArrayIndex = index + 1;
stakers[_staker].stakersArrayIndex = 0;
}
/// @dev Add a staker to the stakersArray.
function _addStaker(address _staker) internal {
stakersArray.push(_staker);
stakers[_staker].stakersArrayIndex = uint64(stakersArray.length); // we do not use 0 as index, so we can use it to check if the user is in the array
}
/// @dev Calculate rewards for a staker.
function _calculateRewards(
address _staker
) internal view returns (uint256) {
UnbondingStaker memory stakerData = stakers[_staker];
if (stakerData.amountStaked == 0) {
return 0;
}
uint256 startTime = stakerData.timeOfLastUpdate;
uint256 endTime = block.timestamp;
// Cap endTime to MAX_STAKE_DURATION from first stake
uint256 maxEndTime = stakerData.timeOfFirstStake + MAX_STAKE_DURATION;
if (endTime > maxEndTime) {
endTime = maxEndTime;
}
// No rewards if past the max duration
if (startTime >= endTime) {
return 0;
}
// Calculate pro-rata rewards
uint256 timeStaked = endTime - startTime;
uint256 rewardAmount = (stakerData.amountStaked *
timeStaked *
APY_PERCENTAGE) / (365 days * BASIS_POINTS);
return rewardAmount;
}
/// @dev View available rewards for a user.
function _availableRewards(
address _staker
) internal view returns (uint256) {
UnbondingStaker memory stakerData = stakers[_staker];
if (stakerData.amountStaked == 0 && stakerData.timeOfLastUpdate == 0) {
return 0;
}
return stakerData.unclaimedRewards + _calculateRewards(_staker);
}
}
contracts/interfaces/IStakingBase.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.28;
import { ITypes } from "contracts/interfaces/ITypes.sol";
interface IStakingBase {
/// @dev Emitted when a new staking contract is created.
struct BaseParams {
address stakingToken;
bytes32 merkleRoot;
ITypes.WhitelistStatus whitelistStatus;
uint256 tierLowerBound;
uint256 tierUpperBound;
uint80 startStakingDate;
uint80 endStakingDate;
uint256 poolMaxCap;
ITypes.FeeType feeType;
uint256 fee;
address feeCollector;
uint8 feeFunctions;
address owner;
}
/// @dev Emitted when contract is funded with rewards.
event ContractFunded(address indexed funder, uint256 amount);
/// @dev Emitted when excess rewards are withdrawn.
event ExcessRewardsWithdrawn(
address indexed admin,
uint256 amount,
bool fromExcessTokens
);
/// @dev Emitted when a trusted distributor is added or removed
event TrustedDistributorUpdated(address distributor, bool status);
/// @dev Emitted when contract admin updates the pool maximum capacity.
event PoolMaxCapUpdated(uint256 oldPoolMaxCap, uint256 newPoolMaxCap);
/// @dev Other token withdrawn event.
event OtherTokenWithdrawn(
address indexed admin,
address indexed token,
uint256 amount
);
/// @dev Emitted when a fee collector withdraws token fees.
event TokenFeeWithdrawn(
address indexed recipient,
address indexed token,
uint256 amount
);
/// @dev Emitted when a fee collector withdraws gas fees.
event GasFeeWithdrawn(address indexed recipient, uint256 amount);
/// @dev Emitted when fee collector is updated
event FeeCollectorUpdated(
address indexed oldFeeCollector,
address indexed newFeeCollector
);
/// @dev Emitted when the whitelist status is updated
event WhitelistStatusUpdated(
ITypes.WhitelistStatus oldStatus,
ITypes.WhitelistStatus newStatus,
bytes32 merkleRoot
);
/// @dev Emitted when tokens are staked.
event TokensStaked(
address indexed staker,
uint256 amount,
uint256 feeAmount
);
/// @dev Emitted when tokens are withdrawn.
event TokensWithdrawn(
address indexed staker,
uint256 amount,
uint256 feeAmount
);
/// @dev Emitted when a staker claims staking rewards.
event RewardsClaimed(
address indexed staker,
uint256 rewardAmount,
uint256 feeAmount
);
/// @notice Claim accumulated rewards.
function claimRewards() external payable;
/// @notice Claim a specific amount of accumulated rewards.
/// @param _amount: Amount of rewards to claim.
function claimRewards(uint256 _amount) external payable;
}
contracts/interfaces/IStakingWithUnbonding.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.28;
import { ITypes } from "./ITypes.sol";
import { IStakingBase } from "./IStakingBase.sol";
/// @notice Staker Info for StakingWithUnbonding contract.
/// @param amountStaked: Total amount of tokens staked by the staker.
/// @param unclaimedRewards: Rewards accumulated but not yet claimed by user.
/// @param timeOfFirstStake: Timestamp of user's first stake.
/// @param timeOfLastUpdate: Last reward-update timestamp.
/// @param unbondingTimestamp: Timestamp when user initiated unbonding.
/// @param unbondingAmount: Amount of tokens in the unbonding period.
/// @param stakersArrayIndex: Index of the staker in the stakers array, 0 if not in the array, index + 1 if in the array.
struct UnbondingStaker {
uint256 amountStaked;
uint256 unclaimedRewards;
uint128 timeOfFirstStake;
uint128 timeOfLastUpdate;
uint128 unbondingTimestamp;
uint256 unbondingAmount;
uint64 stakersArrayIndex;
}
/// @notice Staking with unbonding contract configuration parameters
struct UnbondingStakingInitParams {
bytes32 merkleRoot;
ITypes.WhitelistStatus whitelistStatus;
// Token params
address stakingToken;
uint256 poolMaxCap;
uint64 unbondingPeriod;
uint64 maxStakeDuration;
uint64 apyPercentage;
// Tier params
uint256 tierUpperBound;
uint256 tierLowerBound;
// Staking period params
uint80 startStakingDate;
uint80 endStakingDate;
// Fee params
ITypes.FeeType feeType;
uint256 fee;
address feeCollector;
uint8 feeFunctions;
}
/// @notice Staking contract configuration parameters
struct StakingSettings {
bytes32 merkleRoot;
ITypes.WhitelistStatus whitelistStatus;
address stakingToken;
uint256 poolMaxCap;
uint64 maxStakeDuration;
uint64 apyPercentage;
uint256 tierUpperBound;
uint256 tierLowerBound;
uint80 startStakingDate;
uint80 endStakingDate;
uint64 unbondingPeriod;
ITypes.FeeType feeType;
uint256 fee;
address feeCollector;
address owner;
uint8 feeFunctions;
uint256 basisPoints;
}
/// @notice Interface for the StakingWithUnbonding contract
interface IStakingWithUnbonding is IStakingBase {
/// @dev Emitted when unbonding is initiated.
event UnbondingInitiated(address indexed staker, uint256 amount);
/// @dev Emitted when contract admin updates the unbonding period.
event UnbondingPeriodUpdated(
uint64 oldUnbondingPeriod,
uint64 newUnbondingPeriod
);
/// @notice Initiate unbonding process for staked tokens.
/// @param _amount: Amount to unbond.
function initiateUnbonding(uint256 _amount) external;
/// @notice Complete unbonding process and withdraw tokens after unbonding period.
function completeUnbonding() external payable;
/// @notice Returns the total amount of tokens staked by a user, the total rewards, the unbonding amount, the time until unbonding is complete, and the first stake time.
/// @param _staker: Address of the staker.
function getStakeInfo(
address _staker
)
external
view
returns (
uint256 _tokensStaked,
uint256 _rewards,
uint256 _unbondingAmount,
uint256 _timeUntilUnbondingComplete,
uint128 _firstStakeTime
);
/// @notice Returns the APY in basis points.
function getAPY() external view returns (uint64);
/// @notice Updates the unbonding period
/// @param _newUnbondingPeriod The new unbonding period in seconds
function setUnbondingPeriod(uint64 _newUnbondingPeriod) external;
}
contracts/interfaces/ITypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;
interface ITypes {
enum FeeType {
Gas,
DistributionToken
}
enum WhitelistStatus {
Disabled,
Merkle,
TrustedDistributors,
MerkleAndTrustedDistributors
}
}
contracts/lib/FeeFunctions.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.28;
library FeeFunctions {
// Bitmask flags to determine which functions have fees
uint8 constant FEE_ON_STAKE = 1; // 00000001
uint8 constant FEE_ON_WITHDRAW = 2; // 00000010
uint8 constant FEE_ON_CLAIM = 4; // 00000100
uint8 constant FEE_ON_ALL = 7; // 00000111 (All functions)
uint8 constant FEE_ON_NONE = 0; // 00000000 (No fees)
}
contracts/lib/StakingBase.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.28;
import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuardTransient } from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import { ITypes } from "contracts/interfaces/ITypes.sol";
import { IStakingBase } from "contracts/interfaces/IStakingBase.sol";
import { StakingErrors } from "contracts/lib/StakingErrors.sol";
abstract contract StakingBase is
IStakingBase,
Ownable,
ReentrancyGuardTransient
{
using SafeERC20 for IERC20;
/// @dev Basis points for fee calculation.
uint256 public constant BASIS_POINTS = 10_000;
/// @dev fee functions bitmask.
/// @dev 1 = FEE_ON_STAKE
/// @dev 2 = FEE_ON_WITHDRAW
/// @dev 4 = FEE_ON_CLAIM
/// @dev 7 = FEE_ON_ALL
/// @dev 0 = FEE_ON_NONE
uint8 public immutable FEES_FUNCTIONS;
/// @dev Address of the ERC20 staking token.
address public immutable STAKING_TOKEN;
/// @dev Fee percentage (100% = 10 000)
uint256 public immutable FEE;
/// @dev Fee type (Gas or Token).
ITypes.FeeType public immutable FEE_TYPE;
/// @dev Maximum number of tokens that can be staked by a user.
uint256 public immutable TIER_UPPER_BOUND;
/// @dev Minimum number of tokens that can be staked by a user.
uint256 public immutable TIER_LOWER_BOUND;
/// @dev Start date of staking.
uint80 public immutable START_STAKING_DATE;
/// @dev End date of staking.
uint80 public immutable END_STAKING_DATE;
/// @dev Total amount of tokens staked in the contract.
uint256 public stakingTokenBalance;
/// @dev Max amount of tokens that can be staked in the pool.
uint256 public poolMaxCap;
/// @dev List of accounts that have staked the staking token.
address[] public stakersArray;
/// @dev Address of the fee collector.
address public feeCollector;
/// @dev Merkle root for whitelisting stakers.
bytes32 public merkleRoot;
/// @dev Controls whether whitelist is active for staking operations
ITypes.WhitelistStatus public whitelistStatus;
/// @dev Total amount of rewards available for distribution.
uint256 public rewardsAvailable;
/// @dev Allowed distributor contracts that can bypass whitelist
mapping(address => bool) public trustedDistributors;
/// @dev Total accumulated fees.
uint256 public numTokenReservedForFee;
// This checks if the msg.sender is the fee collector
modifier onlyFeeCollector() {
if (msg.sender != feeCollector) revert StakingErrors.OnlyFeeCollector();
_;
}
constructor(BaseParams memory params) Ownable(params.owner) {
if (params.stakingToken == address(0))
revert StakingErrors.InvalidAddress();
if (params.feeCollector == address(0))
revert StakingErrors.InvalidAddress();
// Validate tier bounds
if (params.tierLowerBound > params.tierUpperBound)
revert StakingErrors.InvalidTierBounds();
// Validate staking dates
if (params.startStakingDate >= params.endStakingDate)
revert StakingErrors.InvalidStakingDates();
if (params.startStakingDate < block.timestamp)
revert StakingErrors.StartDateInPast();
// Validate fee percentage, only if fee type is not Gas
if (params.feeType != ITypes.FeeType.Gas) {
if (params.fee > BASIS_POINTS)
revert StakingErrors.InvalidFeePercentage();
}
// Validate fee functions bitmask
if (params.feeFunctions > 7)
revert StakingErrors.InvalidFeeFunctionsMask();
// If merkle root is set, whitelist has to be Merkle or MerkleAndTrustedDistributors
if (
(params.whitelistStatus == ITypes.WhitelistStatus.Merkle ||
params.whitelistStatus ==
ITypes.WhitelistStatus.MerkleAndTrustedDistributors) &&
params.merkleRoot == bytes32(0)
) revert StakingErrors.InvalidMerkleRoot();
// If whitelist is Disabled or TrustedDistributors, merkle root has to be empty
if (
(params.whitelistStatus == ITypes.WhitelistStatus.Disabled ||
params.whitelistStatus ==
ITypes.WhitelistStatus.TrustedDistributors) &&
params.merkleRoot != bytes32(0)
) revert StakingErrors.InvalidMerkleRoot();
STAKING_TOKEN = params.stakingToken;
TIER_LOWER_BOUND = params.tierLowerBound;
TIER_UPPER_BOUND = params.tierUpperBound;
START_STAKING_DATE = params.startStakingDate;
END_STAKING_DATE = params.endStakingDate;
FEE_TYPE = params.feeType;
FEE = params.fee;
FEES_FUNCTIONS = params.feeFunctions;
poolMaxCap = params.poolMaxCap;
feeCollector = params.feeCollector;
_setWhitelistStatus(params.whitelistStatus, params.merkleRoot);
}
// ==============================
// 1. External Functions - Write
// ==============================
/// @notice Funds the staking contract with tokens to be distributed as staking rewards.
/// @param _amount: Amount of tokens.
function fundStakingContract(uint256 _amount) external onlyOwner {
if (_amount == 0) revert StakingErrors.ZeroAmount();
rewardsAvailable += _amount;
emit ContractFunded(msg.sender, _amount);
IERC20(STAKING_TOKEN).safeTransferFrom(
msg.sender,
address(this),
_amount
);
}
/// @notice Allows an admin to withdraw excess rewards or accidentally sent tokens from the contract.
/// @param _amount: Amount of tokens to withdraw.
/// @param _recipient: Address to send the withdrawn tokens to.
/// @param _fromExcessTokens: If true, withdraws from tokens sent to contract by mistake rather than from rewards.
function withdrawExcessRewards(
uint256 _amount,
address _recipient,
bool _fromExcessTokens
) external nonReentrant onlyOwner {
if (_amount == 0) revert StakingErrors.ZeroAmount();
if (_recipient == address(0)) revert StakingErrors.InvalidAddress();
if (_fromExcessTokens) {
uint256 contractBalance = IERC20(STAKING_TOKEN).balanceOf(
address(this)
);
uint256 tokensInUse = stakingTokenBalance +
rewardsAvailable +
numTokenReservedForFee;
uint256 excessTokens = contractBalance > tokensInUse
? contractBalance - tokensInUse
: 0;
if (_amount > excessTokens)
revert StakingErrors.InsufficientExcessTokens();
} else {
if (_amount > rewardsAvailable)
revert StakingErrors.InsufficientRewardsAvailable();
rewardsAvailable -= _amount;
}
IERC20(STAKING_TOKEN).safeTransfer(_recipient, _amount);
emit ExcessRewardsWithdrawn(msg.sender, _amount, _fromExcessTokens);
}
/// @notice Set whitelist status and merkle root
/// @param _status Whether whitelist should be enabled or disabled
/// @param _merkleRoot The Merkle root of the whitelist
function setWhitelistStatus(
ITypes.WhitelistStatus _status,
bytes32 _merkleRoot
) external onlyOwner {
_setWhitelistStatus(_status, _merkleRoot);
}
/// @notice Updates the fee collector address
/// @param newFeeCollector Address of the new fee collector
function transferFeeCollectorRole(
address newFeeCollector
) external onlyFeeCollector {
if (newFeeCollector == address(0))
revert StakingErrors.InvalidAddress();
address oldFeeCollector = feeCollector;
feeCollector = newFeeCollector;
emit FeeCollectorUpdated(oldFeeCollector, newFeeCollector);
}
/// @notice Withdraw accidentally sent tokens to this contract
/// @param _tokenAddress - the token which we want to withdraw
function withdrawOtherToken(address _tokenAddress) external onlyOwner {
if (_tokenAddress == address(0)) revert StakingErrors.InvalidAddress();
if (_tokenAddress == STAKING_TOKEN)
revert StakingErrors.InvalidAddress();
uint256 amount = IERC20(_tokenAddress).balanceOf(address(this));
if (amount == 0) revert StakingErrors.ZeroAmount();
emit OtherTokenWithdrawn(msg.sender, _tokenAddress, amount);
IERC20(_tokenAddress).safeTransfer(msg.sender, amount);
}
/// @notice Allows only fee collector to withdraw collected token fees
/// @param recipient Address to receive the fee
/// @param amount Amount to withdraw, if 0 withdraws all available fees
function withdrawTokenFee(
address recipient,
uint256 amount
) external onlyFeeCollector {
if (recipient == address(0)) revert StakingErrors.InvalidAddress();
if (FEE_TYPE != ITypes.FeeType.DistributionToken)
revert StakingErrors.InvalidFeeType();
uint256 amountToWithdraw = amount == 0
? numTokenReservedForFee
: amount;
if (amountToWithdraw == 0) revert StakingErrors.ZeroAmount();
if (amountToWithdraw > numTokenReservedForFee)
revert StakingErrors.ZeroAmount();
numTokenReservedForFee -= amountToWithdraw;
IERC20(STAKING_TOKEN).safeTransfer(recipient, amountToWithdraw);
emit TokenFeeWithdrawn(recipient, STAKING_TOKEN, amountToWithdraw);
}
/// @notice Allows only fee collector to withdraw collected gas fees
/// @param recipient Address to receive the fee
/// @param amount Amount to withdraw, if 0 withdraws all available fees
function withdrawGasFee(
address recipient,
uint256 amount
) external onlyFeeCollector {
if (recipient == address(0)) revert StakingErrors.InvalidAddress();
if (FEE_TYPE != ITypes.FeeType.Gas)
revert StakingErrors.InvalidFeeType();
uint256 amountToWithdraw = amount == 0 ? address(this).balance : amount;
if (amountToWithdraw == 0) revert StakingErrors.ZeroAmount();
if (amountToWithdraw > address(this).balance)
revert StakingErrors.ZeroAmount();
emit GasFeeWithdrawn(recipient, amountToWithdraw);
(bool success, ) = recipient.call{ value: amountToWithdraw }("");
if (!success) revert StakingErrors.TransferFailed();
}
/**
* @notice Sets or revokes multiple address status as trusted distributors
* @param distributors Array of distributor contract addresses
*/
function setBatchTrustedDistributors(
address[] calldata distributors
) external onlyOwner {
if (distributors.length == 0) revert StakingErrors.EmptyArray();
for (uint256 i; i < distributors.length; ++i) {
address distributor = distributors[i];
if (distributor == address(0))
revert StakingErrors.InvalidAddress();
trustedDistributors[distributor] = true;
emit TrustedDistributorUpdated(distributor, true);
}
}
/**
* @notice Removes a contract from the trusted distributors list
* @param distributor Address of the distributor contract to remove
* @dev This function completely deletes the entry from the mapping
*/
function removeTrustedDistributor(address distributor) external onlyOwner {
if (distributor == address(0)) revert StakingErrors.InvalidAddress();
if (!trustedDistributors[distributor]) return;
delete trustedDistributors[distributor];
emit TrustedDistributorUpdated(distributor, false);
}
/// @notice Update the pool maximum capacity
/// @param _newPoolMaxCap New maximum capacity
function updatePoolMaxCap(uint256 _newPoolMaxCap) external onlyOwner {
if (_newPoolMaxCap < stakingTokenBalance)
revert StakingErrors.NewCapBelowCurrentStake();
uint256 oldPoolMaxCap = poolMaxCap;
poolMaxCap = _newPoolMaxCap;
emit PoolMaxCapUpdated(oldPoolMaxCap, _newPoolMaxCap);
}
/**
* @notice Updates the maximum capacity of the staking pool
* @param _newPoolMaxCap The new maximum capacity value
* @dev Can only be called by the owner
*/
function setPoolMaxCap(uint256 _newPoolMaxCap) external onlyOwner {
if (_newPoolMaxCap < stakingTokenBalance)
revert StakingErrors.NewCapBelowCurrentStake();
uint256 oldPoolMaxCap = poolMaxCap;
poolMaxCap = _newPoolMaxCap;
emit PoolMaxCapUpdated(oldPoolMaxCap, _newPoolMaxCap);
}
// ==============================
// 1. External Functions - View
// ==============================
/// @notice Returns the total amount of tokens staked in the contract.
function getStakingTokenBalance() external view returns (uint256) {
return stakingTokenBalance;
}
/// @notice Returns the total amount of tokens available for rewards.
function getTotalAvailableReward() external view returns (uint256) {
return rewardsAvailable;
}
// ==============================
// 3. Internal Functions - Write
// ==============================
/// @notice Internal implementation of whitelist status update
/// @param _status Whether whitelist should be enabled or disabled
/// @param _merkleRoot The Merkle root of the whitelist
function _setWhitelistStatus(
ITypes.WhitelistStatus _status,
bytes32 _merkleRoot
) internal {
if (
(_status == ITypes.WhitelistStatus.Merkle ||
_status ==
ITypes.WhitelistStatus.MerkleAndTrustedDistributors) &&
_merkleRoot == bytes32(0)
) revert StakingErrors.InvalidMerkleRoot();
if (
(_status == ITypes.WhitelistStatus.Disabled ||
_status == ITypes.WhitelistStatus.TrustedDistributors) &&
_merkleRoot != bytes32(0)
) revert StakingErrors.InvalidMerkleRoot();
ITypes.WhitelistStatus oldStatus = whitelistStatus;
whitelistStatus = _status;
merkleRoot = _merkleRoot;
emit WhitelistStatusUpdated(oldStatus, _status, _merkleRoot);
}
// ==============================
// 3. Internal Functions - View
// ==============================
// Helper function to check if fees are enabled for a specific function
function _hasFeeEnabled(uint8 functionFlag) internal view returns (bool) {
return (FEES_FUNCTIONS & functionFlag) != 0;
}
}
contracts/lib/StakingErrors.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.28;
/**
* @title StakingErrors
* @dev Library of custom error types used across the staking contracts
*/
library StakingErrors {
// General errors
error InvalidAddress();
error ZeroAmount();
error ZeroBalance();
error TransferFailed();
error ArrayLengthMismatch();
error EmptyArray();
// Fee-related errors
error InsufficientFee();
error FeeTooLow();
error FeeTooHigh();
error InvalidFeeType();
error CustomFeeNotSet();
error CustomFeeAlreadySet();
// Authorization errors
error OnlyFeeCollector();
error OnlyTrustedDistributor();
error OnlyOwner();
// Staking-specific errors
error StakingNotStarted();
error StakingEnded();
error StakingZeroTokens();
error StakingAmountExceedsUpperBound();
error StakingAmountBelowLowerBound();
error ExitingTierLowerBound();
// Withdraw-specific errors
error WithdrawingZeroTokens();
error WithdrawingMoreThanStaked();
error NoTokensUnbonding();
error UnbondingPeriodNotCompleted();
error RemainingAmountBelowLowerBound();
// Administrative errors
error ConditionArraySizeLimitReached();
error InsufficientRewardsAvailable();
error InsufficientExcessTokens();
error TimeUnitUnchanged();
error RewardRatioUnchanged();
error TimeUnitCannotBeZero();
error DenominatorCannotBeZero();
error NewCapBelowCurrentStake();
error NewMaxConditionsBelowCurrentCount();
error ExceedsMaxConditionsLimit();
// Rewards-specific errors
error NoRewards();
error InsufficientRewards();
error RewardCapExceeded();
// Merkle proof errors
error InvalidMerkleProof();
error InvalidMerkleRoot();
error PoolMaxCapExceeded();
error WhitelistEnabled();
// Validation errors
error InvalidTierBounds();
error InvalidStakingDates();
error StartDateInPast();
error InvalidFeePercentage();
error InvalidFeeFunctionsMask();
error InvalidTimeUnit();
error InvalidRewardRatio();
error InvalidUnbondingPeriod();
error InvalidApyPercentage();
error InvalidMaxStakeDuration();
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// 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);
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @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, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @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 REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represents a slot holding an address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represents a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/Hashes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of standard hash functions.
*
* _Available since v5.1._
*/
library Hashes {
/**
* @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
*
* NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
*/
function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
lib/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.
pragma solidity ^0.8.20;
import {Hashes} from "./Hashes.sol";
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*
* IMPORTANT: Consider memory side-effects when using custom hashing functions
* that access memory in an unsafe way.
*
* NOTE: This library supports proof verification for merkle trees built using
* custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
* leaf inclusion in trees built using non-commutative hashing functions requires
* additional logic that is not supported by this library.
*/
library MerkleProof {
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProof(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function processProof(
bytes32[] memory proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProofCalldata(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function processProofCalldata(
bytes32[] calldata proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProof(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 2000,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"hardhat/=node_modules/hardhat/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.